Cloudflare Origin Issuer not getting ready

Question: I am currently debugging an strange error where my Cloudflare OriginIssuers are not getting ready, which blocks renewals.
I have tried restarting it once but that did not help, I looked at the port cert-manager uses and whitelisted it in the firewall and restarted cert-manager and the cloudflare origin issuer to no avail. It keeps throwing
{"level":"error","error":"resource default/staging is not ready","name":"controller","reconcilerGroup":"cert-manager.io","reconcilerKind":"CertificateRequest","controller":"certificaterequest","name":"certificate-private-hjbl4","namespace":"default","time":"2022-08-01T13:50:33Z","message":"Reconciler error"}
Looking at more logs doesn't get me any further as I cannot for the life of me find the exact error. The logs that get generated are the one above, but I cannot find a log anywhere where I see the error of the Issuer.
The config I used to deploy the Issuer is as follows
apiVersion: cert-manager.k8s.cloudflare.com/v1
kind: OriginIssuer
metadata:
  name: staging
  namespace: default
spec:
  auth:
    serviceKeyRef:
      key: key
      name: cloudflare-staging
  requestType: OriginECC

Answer: So as it turned out. The pod got OOMKilled for an unknown reason (still figuring this OOMKill out). But atleast the pod is running now.
Answer: The default chart/config of origin-ca-issuer deploys the pod with a memory limit of 50Mi. The uneventful termination logs which ends up with OOMKilled might get resolved if you increase it to a higher memory limit. e.g. 100Mi.


Drupal 8 HTML markup and semantics

Question: When building a bespoke site a pet hate is that you start with a front-end layout that is semantically sound and robust, but when you try and create said layout as a theme in Drupal, by default the system adds
 markup around whatever node, field or general piece of information it can find.
The result is that I usually begin with Mothership as a base theme to reduce the noise of excess markup.
Will Drupal 8 (both core modules and shipped themes) adopt cleaner HTML semantics? If so, how might the new front end HTML compare to its Drupal 7 predecessor?
HTML5 is an obvious assumption. The game is no longer "wrap it in a div" as HTML 5 empowers front end developers to a wealth of possible tags in order to best convey meaning  (e.g. aside, header, navigation). How will Drupal change to allow this new level of semantics choice to be controlled by developers?
Comment: I have a strong suspicion you've never come across [Fences](http://drupal.org/project/fences) before. It makes a lot of that extraneous markup configurable, even semantically so.
Comment: seems that all of them do not work for D8.5+ and none of them is ported to D9
Answer: Why should it change (drastically) -- it embraces a base of HTML5 markup; anything beyond that essentially becomes business need, accessibility requirements or simply put designer preference on what clean and simple means to them.

Mobile Initiative
Design Initiaive
HTML5 Initiative

From HTML5 Initiative page

We want to ensure we're spending our time implementing features that will directly benefit Drupal's user base the most. As part of this initiative we'll focus mostly on:

Adding support for the new form elements to Drupal's Form API.
Adding new semantic elements in core templates in an appropriate way.
Adding ARIA roles to markup to improve accessibility.
Simplifying style and script elements.
Ensuring input filters and functions accept HTML5
  elements.

Does the above goals mean that Drupal 8 HTML markup will be as lean turning on Fences in Drupal 7 and nuking all built-in markup? No, will the base markup be too complex, hardly. It will be designed to meet most peoples needs.

Drupal 8 HTML markup and semantics


Best way to change display for a field?

Question: I have a node display that shows about 20 different fields.
One of the fields is a list of years (multiple values). Instead of printing the list of years I would like to just show the first and last year, for example "1999-2005".
Views has a great formatter for those situations but I don't want to use views for the node display.
Answer: You might want to test the following simple formatter I put together for one of my projects - named mvspan (multivalue span). Soon after I wrote it, the specs of my client changed and I did not need it anymore, therefore it may need some more tests, therefore please accept it in its "as-is" shape.
It works for simple text or integer types, not date or datestamps, unfortunately. Feel free to shape it for your own needs.
It has two modes: displaying first/last values or min/max values. Plus, it allows you to set the delimiter to glue up the values.
mvspan.info:
name = Multi-value Span
description = "Formats multi-value fields to show first/last or min/max value spans."
core = 7.x
files[] = mvspan.module

mvspan.module:
<?php
 /**
 * Implements hook_field_formatter_info().
 */
function mvspan_field_formatter_info() {
  return array(
    // the key must be unique, so it's best to prefix with your module's name.
    'mvspan_formatter' => array(
      'label' => t('Multi-value Span'),
      'field types' => array('text', 'number_integer'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'settings' => array(
        'delimiter' => '...',
        'mode' => 'minmax',
      )
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mvspan_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  $delimiter = check_plain($settings['delimiter']); // The delimiter string in the settings form

  switch($settings['mode']){
    case 'minmax':
      $minv = NULL;
      $maxv = NULL;

      foreach($items as $delta => $item) {
        if(is_null($minv) || $item['value'] < $minv){
          $minv = $item['value'];
        }
        if(is_null($maxv) || $item['value'] > $maxv){
          $maxv = $item['value'];
        }
      }

      if($minv === $maxv) {
        $element[0]['#markup'] = $minv;
      } else {
        $element[0]['#markup'] = implode($delimiter, array($minv, $maxv));
      }

      break;

    case 'firstlast':
      reset($items);
      $firstv = $items[key($items)]['value'];
      end($items);
      $lastv = $items[key($items)]['value'];

      $element[0]['#markup'] = implode($delimiter, array($firstv, $lastv));
      break;
  }
  return $element;
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function mvspan_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state){
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();

  // settings
  $element['delimiter'] = array(
    '#type' => 'textfield',
    '#title' => t('Delimiter'),
    '#description' => t('Delimiter string to be inserted between min and max values.'),
    '#default_value' => $settings['delimiter'],
  );
  $element['mode'] = array(
    '#type' => 'select',
    '#title' => t('Value handling'),
    '#description' => t('How multiple values will be managed: min/max or first/last'),
    '#default_value' => $settings['mode'],
    '#options' => array(
      'minmax' => t('Minimum/maximum'),
      'firstlast'  => t('First/last'),
    )
  );
  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function mvspan_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();

  switch($settings['mode']){
    case 'minmax':
      $summary[] = t('Min/max values will be displayed');
      break;

    case 'firstlast':
      $summary[] = t('First/last values will be displayed');
      break;
  }
  $summary[] = t('using delimiter: "@delim"', array('@delim' => $settings['delimiter']));
  return implode('
', $summary);
}

Answer: I came across the theme_preprocess_field() function and got it working. But I feel it's not a slick solution:
function bartik_preprocess_field(&$variables) {
    if($variables['element']['#field_name'] == 'field_mc_years') {
        if(count($variables['items']) > 1) {
            $to_year = end($variables['items']);
            $mc_years = $to_year['#markup'] . ' - '.$variables['items'][0]['#markup'];

            //destroy the array and just set the string to position 0
            unset($variables['items']);
            $variables['items']['0']['#markup'] = $mc_years;
        }
    }
}

Best way to change display for a field?


Assign ID to datatable row from json data

Question: i'm new to datatable jquery plugin.
I got stuck with this for more than 2 days. I have a Json Data, i still cant load the table and i also want to assign first column to be id of the row
Here is html:

            Currency
            Current/Savings Account No.
            Securities Account No.

and my initialization
var oTable=$('#accDetailTable').dataTable( {
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": contextPath + "/user/investorAjax?method=getInvestorAccDetailList",
            "iDeferLoading": 57,
    } );

Return jsonData from server :
    {"sEcho":1,"iColumns":4,"iTotalRecords":16,"iTotalDisplayRecords":16,
"aaData":
    [{"DT_RowId":2032,"currency":1,"currentAccNo":"aa","secureAccNo":"aa"},
    {"DT_RowId":2033,"currency":1,"currentAccNo":"111","secureAccNo":"111"},
    {"DT_RowId":2034,"currency":1,"currentAccNo":"a","secureAccNo":"aa"},
    ]}
}

But it always hit :

DataTables warning (table id = 'accDetailTable'): Added data (size undefined) does not match known number of columns (3)
Comment: How about adding another hidden column to save the row id?
Comment: i try to add one more header  id and set style of it to hidden. but it shows :  Added data (size undefined) does not match known number of columns (5).  From 3 it jumps to 5 , still dont know why
Answer: It's kind of easy. Let's just do a tiny change, since you want the first column contains id, you may need to use fnRender, please check the api of datatables, I didn't add this part of code:
var oTable=$('#accDetailTable').dataTable({
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": contextPath + "/user/investorAjax?method=getInvestorAccDetailList",
    "aoColumns":[
        {"mDataProp":"currency"},
        {"mDataProp":"currentAccNo"},
        {"mDataProp":"secureAccNo"}
    ]
});

Comment: Thanks, but i try to config like this http://datatables.net/release-datatables/examples/server_side/ids.html : given the column data's name DT_RowId but it doesn't work.
Comment: OK, I think the reason is your json data format, see the difference: "DT_RowId":2032 VS  "DT_RowId": "row_9", reference this: http://datatables.net/forums/discussion/8962/dt_rowid-not-adding-id-to-tr/p1
Comment: i try ur solution but still : Added data (size undefined) does not match known number of columns (3)
Comment: currently i cannot load the table.
Comment: The datatables can not recognize your data format I think, so you just have 3 ths while you provides 4 columns data.
Answer: Your datatables is waiting for three entries per line and you give it four. In your table declaration (in html part) specify a new header cell  at the beginning of  your row. You will put ids in it. Then after your dataTables initialization you can hide the first column using fnSetColumnVis(index, visibility) function :
oTable.fnSetColumnVis(0, false); //It will hide your first column

Doing that each row is containing his id (DT_RowId) but not displaying it.
Comment: actually i try this http://datatables.net/release-datatables/examples/server_side/ids.html . It said that with DT_RowId property, datatable will automatically add it as Id of . I thought the error is not cause of JsonData.
Comment: In your given link, iColumns option isn't defined in json response. Can you try to remove it?
Comment: And adColumns definition in your dataTables initialization?
Comment: adColumns? can you give me an exp, i dont know about this prop
Comment: aoColumns sorry, try to remove it as it is not present in dataTables example


Avoiding first chance exception messages when the exception is safely handled

Question: The following bit of code catches the EOS Exception
using (var reader = new BinaryReader(httpRequestBodyStream)) {

    try {
        while (true) {
            bodyByteList.Add(reader.ReadByte());
        }
    } catch (EndOfStreamException) { }
}

So why do I still receive first-chance exceptions in my console?

A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll

Is there a way to hide these first chance exception messages?
Answer: To avoid seeing the messages, right-click on the output window and uncheck "Exception Messages".
However, seeing them happen might be nice, if you're interested in knowing when exceptions are thrown without setting breakpoints and reconfiguring the debugger.
Answer: The point of "first-chance" exceptions is that you're seeing them pre-handler so that you can stop on them during debugging at the point of throwing. A "second-chance" exception is one that has no appropriate handler. Sometimes you want to catch "first-chance" exceptions because it's important to see what's happening when it's being thrown, even if someone is catching it.
There's nothing to be concerned with. This is normal behavior.
Comment: Indeed, it is nothing to be concerned with, but they do clutter up the debug output log :(
Answer:
In Visual Studio you can change the settings for the way the Debugger handles (breaks on) exceptions.
Go to Debug > Exceptions. (Note this may not be in your menu depending on your Visual Studio Environment setting. If not just add it to your menu using the Customize menu.)
There you are presented with a dialog of exceptions and when to break on them.
In the line "Common Language Runtime Exceptions" you can deselect thrown (which should then stop bothering you about first-chance exceptions) and you can also deselect User-unhandeled (which I would not recommend) if want to.

The message you are getting should not be in the console, but should be appearing in the 'Output' window of Visual Studio. If the latter is the case, then I have not found a possibility to remove that, but it doesn't appear if you run the app without Visual Studio.
Answer: Unlike Java, .NET exceptions are fairly expensive in terms of processing power, and handled exceptions should be avoided in the normal and successful execution path.
Not only will you avoid clutter in the console window, but your performance will improve, and it will make performance counters like .NET CLR Exceptions more meaningful.
In this example you would use
while (reader.PeekChar() != -1)
{
    bodyByteList.Add(reader.ReadByte());
}

Comment: Sure it does. "Is there a way to hide these first chance exception messages?" - the first chance exceptions would not appear with this loop. :)
Comment: or you could get all the bytes in one shot with ReadBytes and also make use of buffering. but I guess that wasn't the question.
Answer: I had this problem and couldn't figure out where the exception was thrown. So my solution was to enable Visual Studio to stop executing on this kind of exception.

Navigate to "Debug/Exceptions"
Expand the "Common Language Runtime Exceptions" tree.
Expand the "System" branch.
Scroll down to where "NullReferenceException" is, and check the
"throw" checkbox, and uncheck the "user-handled".
Debug your project.
Answer: If you want more control over these messages, you can add a handler:
Friend Sub AddTheHandler()
AddHandler AppDomain.CurrentDomain.FirstChanceException, AddressOf FirstChanceExceptionHandler
End Sub

<Conditional("DEBUG")>
Friend Sub FirstChanceExceptionHandler( source As Object,  e As Runtime.ExceptionServices.FirstChanceExceptionEventArgs)
' Process first chance exception

End Sub

This allows you to silence them as mentioned in other comments, but still makes sure you are able to be aware of them.  I find it is good to see how many I am really throwing if I log a message and timestamp to a text file.
Comment: Good suggestion.  But it's worth noting that System.Runtime.ExceptionServices is only available in .Net 4.0 or higher.  For those of us dealing with legacy code written against .Net 3.5 (or older).
Comment: Thanks to this piece of code you do not need Visual Studio's built-in exception reporting in Output panel anymore and can turn it off (right-click on the Output panel and remove checkbox from "Exception Messages"). This code will report exceptions on its own (for example, using `Debug.WriteLine($"Exception thrown: '{e.Exception.GetType().FullName}' in {e.Exception.Source}");`) and it can also do some filtering, so it does not force reporting of all exceptions.
Comment: Is valid for ***ASP.NET*** ?
Answer: Actually if are having many exceptions per second, you would achieve must better performance by checking reader.EndOfStream-value.. Printing out those exception messages is unbelievably slow, and hiding them in visual studio won't speed up anything.
Answer: in VB.NET:
<DebuggerHidden()> _
Public Function Write(ByVal Text As String) As Boolean
   ...

Comment: This has nothing to do with the question.
Comment: It seems that using `DebuggerHiddenAttribute` just means the first chance exception will be shown on the calling method, rather than the method itself.
Comment: Actually, using [DebuggerNonUserCode] *does* hide "first chance exception" messages. I wouldn't be surprised DebuggerHidden also does this.
Comment: I'm not sure if these are considered exceptions, but [DebuggerNonUserCode] won't hide any of the "Managed Debugging Assistants". For example, I get BindingFailures when I use XmlSerializer, and I've yet to find a way to hide it, other than unchecking BindingFailure when Thrown from the Exceptions dialog.
Answer: I think the stream is throwing this exception, so your try is scoped to narrow to catch it.
Add a few more try catch combos around the different scopes until you catch it where its actually being thrown, but it appears to be happening either at our outside of your using, since the stream object is not created in the using's scope.


Amalgamated coproduct of two copies of a partially ordered monoid $S$

Question: The definition of the amalgamated coproduct $A(I)$ of two copies of a partially ordered monoid $S$ is as follows:
Let $I$ be a right ideal of a pomonoid $S$, $x,y,z$ not belonging to $S$, and $$A(I)=(\{ x,y\} \times (S\setminus I))\cup (\{ z\} \times I),$$ and the definition of a right $S$-action on $A(I)$ is as follows: $$(w,u)s=\begin{cases}(w,us) & \text{if}\;   us\not \in I, \; w\in \{ x,y\}\\ (z,us), & \text{if}\; us \in I. \end{cases}$$
My question is:  What is $(z,u)s$ if $us\not \in I$?
Answer: According to your definition, if $(z, u) \in A(I)$, then $u \in I$. Now since $I$ is an ideal, $us \in I$ for every $s \in S$. Thus the case you consider simply cannot occur.
Comment: You are right. I got it. Thank you very much.
Comment: You're welcome.


Not able fetch Value from Javascript Array and Uncaught SyntaxError: Unexpected identifier in jquery

Question: First of all I am new to Javascript.I am using an Array which gets its value during runtime like
var tablehash = [CS: "CS", tbl_master: "tbl_master"]

I have to fetch the value in the Array inorder to compare with a value I had tried like
var valtocompare = tablehash ["CS"];

but its giving me error  so I had tested the above array manually as
var tablehash = {CS: "CS", tbl_master: "tbl_master"}

and fetched the value it come correctly
My Question is Why can't I fetch the value from the Array that have [] as opening and closing symbols but I can fetch from array that have  {} as opening and closing symbols
Edit: value var tablehash = [CS: "CS", tbl_master: "tbl_master"]. is got from the line tablehash[xx[0]]=xx[0]; in my jquery during runtime it is enclosed with [] only what can I do

Kindly anyone point me what I am doing wrong.
Uncaught SyntaxError: Unexpected identifier in jquery Question
As I can,t ask a New Question I had added my new Question in this thread because the below mentioned script is in the same Jquery Library.
I am Calling the below mentioned jQuery library function from my page but at the line of evaluating my JSON String sent I am Getting the Uncaught SyntaxError: Unexpected identifier
Function called from page as
function BindSearchedQueryData(JsonString) {

        $('.sqlbuild').loadSQB(JsonString);
    }

The loadSQB is
loadSQB: function (jsonstr) {
        var $tt = this[0];

        $('.sqlcolumn').remove();
        $('.sqlwhere').remove();
        $('.sqlgroup').remove();
        $('.sqlsort').remove();

        var j=eval('(' + jsonstr + ')');  //Getting Error in this line

        var coldiv  =$(".addnewsqlcolumn");
        var sortdiv =$('.addnewsqlsort');
        var groupdiv=$('.addnewsqlgroup');
        var wherediv=$('.addnewsqlwhere');

        /*rebuild col data*/
        for(var i=0;i<j.columndata.length;i++){
            //j.columndata[i].columnslot, j.columndata[i].columnvalue
            coldiv[0].opts.onselect(j.columndata[i].columnslot,coldiv,{columnas:j.columndata[i].columnas});
        }
        /*rebuild sort data*/
        for(var i=0;i<j.sortdata.length;i++){
            //j.sortdata[i].columnslot, j.sortdata[i].columnas
            sortdiv[0].opts.onselect(j.sortdata[i].columnslot,sortdiv,{columnas:j.sortdata[i].columnas});
        }
        /*rebuild group by data*/
        for(var i=0;i<j.groupdata.length;i++){
            //j.groupdata[i].columnslot,
            groupdiv[0].opts.onselect(j.groupdata[i].columnslot,groupdiv,null);
        }
        /*rebuild where data*/
        for(var i=0;i<j.wheredata.length;i++){
            //j.wheredata[i].columnslot, j.wheredata[i].opslot,j.wheredata[i].chainslot,j.wheredata[i].columnvalue
            wherediv[0].opts.onselect(j.wheredata[i].columnslot,wherediv,{columnslot:j.wheredata[i].columnslot,opslot:j.wheredata[i].opslot,chainslot:j.wheredata[i].chainslot,columnvalue:j.wheredata[i].columnvalue});

        }

    }

Kindly Anyone point me what is going wrong here
Comment: This is not an array. If you want objects, use `{CS: "CS", tbl_master: "tbl_master"}`, if you want arrays, use `["CS", "tbl_master"]`. `[CS: "CS", tbl_master: "tbl_master"]` is just invalid syntax. Please use [JSHint](http://jshint.com) to validate your code.
Answer: Javascript does not have associative arrays, ie you can't have
var tablehash = [CS: "CS", tbl_master: "tbl_master"].
But you can have
var tablehash = {CS: "CS", tbl_master: "tbl_master"}, which is a valid object.
Once you do this, you can access the values with object.key syntax.
So, the value of tablehash.CS would be CS.
PS - use a linter in your ide/editor.
Comment: I am getting the specified value `var tablehash = [CS: "CS", tbl_master: "tbl_master"].` from the line  `tablehash[xx[0]]=xx[0];` in my javascript its coming with `[]` only what can I do
Answer: There is a difference between [] and {} in Javascript.
Values enclosed in [] are values in an array and values in {} makes {} a javascript object.
You can have associative arrays in Javascript like
    {a: 'apple', b: 'ball'} .
You can also have arrays as values
    {a: [1,2], b: [3,4]}.
So you need to form your hash as
    var tablehash = {CS: "CS", tbl_master: "tbl_master"}.
In order to access it you write like
    tablehash['CS'] or tablehash.CS
Answer: Answer to my Second Question Uncaught SyntaxError: Unexpected identifier
The value which I am passing to the Function loadSQB is a Javascript Object  so I used the JSON.stringify() to convert Javascript Object to a JSON string
loadSQB: function (jsonstr) {
    jsonstr=JSON.stringify(jsonstr); //Solution for the Question
    var $tt = this[0];

    $('.sqlcolumn').remove();
    $('.sqlwhere').remove();
    $('.sqlgroup').remove();
    $('.sqlsort').remove();

    var j=eval('(' + jsonstr + ')');  //Got Error in this line

    var coldiv  =$(".addnewsqlcolumn");
    var sortdiv =$('.addnewsqlsort');
    var groupdiv=$('.addnewsqlgroup');
    var wherediv=$('.addnewsqlwhere');

    /*rebuild col data*/
    for(var i=0;i<j.columndata.length;i++){
        //j.columndata[i].columnslot, j.columndata[i].columnvalue
        coldiv[0].opts.onselect(j.columndata[i].columnslot,coldiv,{columnas:j.columndata[i].columnas});
    }
    /*rebuild sort data*/
    for(var i=0;i<j.sortdata.length;i++){
        //j.sortdata[i].columnslot, j.sortdata[i].columnas
        sortdiv[0].opts.onselect(j.sortdata[i].columnslot,sortdiv,{columnas:j.sortdata[i].columnas});
    }
    /*rebuild group by data*/
    for(var i=0;i<j.groupdata.length;i++){
        //j.groupdata[i].columnslot,
        groupdiv[0].opts.onselect(j.groupdata[i].columnslot,groupdiv,null);
    }
    /*rebuild where data*/
    for(var i=0;i<j.wheredata.length;i++){
        //j.wheredata[i].columnslot, j.wheredata[i].opslot,j.wheredata[i].chainslot,j.wheredata[i].columnvalue
        wherediv[0].opts.onselect(j.wheredata[i].columnslot,wherediv,{columnslot:j.wheredata[i].columnslot,opslot:j.wheredata[i].opslot,chainslot:j.wheredata[i].chainslot,columnvalue:j.wheredata[i].columnvalue});

    }

}


Custom date formats in webform emails

Question: I have a webform that sends an email. The webform has a date field and I need to format that date field.
I have tried:
[submission:values:date_field:CUSTOM_FORMAT]
[submission:values:date_field:long]
[submission:values:date_field:value:custom:d-M-y]

Both result in a blank date.
How can I format the date in a webform email using a non-default (which appears to be short) date format?
Answer: I had to create a custom hook_tokens function:
/**
 * Implementation of hook_tokens().
 */
function MODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'submission' && !empty($data['webform-submission'])) {
    $node = isset($data['node']) ? $data['node'] : node_load($submission->nid);

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'values:date_field:custom_format':
          foreach ($node->webform['components'] as $cid => $component) {
            if ($component['form_key'] == 'date_field') {
              $replacements[$original] = format_date(strtotime($data['webform-submission']->data[$cid][0]), 'custom_format');
            }
          }
          break;
      }
    }
  }

  return $replacements;
}

Custom date formats in webform emails


Como incluir comando if ao add um novo objeto em uma lista?

Question: Utilizo esse comando pra salvar uma nova pessoa uma lista:
class pessoa
{
    string nome;
    int idade;
    int sexo;
}

List<pessoa> pessoas.add(new pessoa()
{
    nome = "italo rodrigo",
    idade = 34,
    sexo = 1
});

Pra mostrar ao usuário, eu criei uma classe "temporária" só pro usuário ver na tela:
class pessoaT
{
    string nome;
    int idade;
    string sexo; //alterei de int para string
}

Quero fazer o seguinte: tenho uma lista de objetos pessoa e quero convertê-los em pessoaT
foreach (pessoa item in pessoa)
{
    List<pessoaT> pessoasT.add(new pessoaT()
    {
        nome = item.nome,
        idade = item.idade,
        if (item.sexo == 0)
            sexo = "F"
        else
            sexo = "M"
    });
}

O código acima dá erro no if. Como devo fazer pra funcionar corretamente?
Answer: Você pode utilizar a condição ternário
foreach (pessoa item in pessoa)
{
    List<pessoaT> pessoasT=new List<pessoaT>()
    pessoasT.add(new pessoaT()
    {
        nome = item.nome,
        idade = item.idade,
        sexo=item.sexo==0?"F":"M"
    });
}


arrange view to show 3 x 3 grid of nodes

Question: How would i get Drupal to show a 3x3 grid of nodes of a certain content type.
I've tried using both Format:Grid and Format:Table. Also I used Show: Fields and Show: Teasers but it doesn't work out the way I want.
I am wondering if it's best to use 2 separate blocks of 3 nodes with an offset for the second block so that the 1st block shows nodes 1,2,3 and the 2nd block shows 4,5,6.
This is all related to 1 single content type with fields which include. 1 Image, and 1 URL.
Comment: You can show your own view mode (like teaser, but a display format you have defined yourself) in Views, so you could try using Drupal's built-in capabilities or the Display Suite module to get a view mode that shows the nodes the way you like, and then use a grid or table to display that view mode.
Comment: I had a look at display suite but that looks really complicated. I was hoping there might just be something to add to the CSS to make it work
Comment: You don't need Display Suite; you can use view modes without Display Suite and handle the display with a theme template.  You could also probably do it just in CSS but pure CSS questions are better asked on Stack Overflow than here.
Answer: Using format and pager settings this should be possible.
Add Format type of Grid

Set the number of columns under the Format settings to "3"

Set page to only show 9 items

Set the filter to only show nodes of a specific content type:

Now all you need to do is set the view fields, filter, sort, and other options to your liking.  Hope this helps!
Comment: That worked perfectly.


Microsoft Hosted Exchange: Possible to outsource single mail account?

Question: I have a customer who polls e-mail for a number of accounts in domain example.com via POP. Now they have a VIP user firstname.lastname@example.com who wants to use Microsoft Hosted Exchange on his mobile phone.
Unfortunately the descriptions of Hosted Exchange aren't too detailed and in heavy Microsoft lingo. My question is: Can it be configured so that it handles mail for this single user, while all other mail accounts remain on the POP server?
One approach for inbound mail would be to buy Hosted Exchange for a dedicated domain, such as exchange.example.com and reroute email@example.com to email@example.com.
Which leaves outbound mail: Can Hosted Exchange be configured to relay mail through my mail relay where I can rewrite the sender email@example.com to email@example.com? Or can it forge the sender address on outbound mail altogether, without relaying through my server? (SPF records are not an issue.)
Answer: "Can it be configured so that it handles mail for this single user, while all other mail accounts remain on the POP server?"
Yes, Exchange can be used to host a single account where the mail flow for the user is redirected from the another (POP) server. The user would just access the Exchange configuration versus the POP server.
"Can Hosted Exchange be configured to relay mail through my mail relay where I can rewrite the sender email@example.com to email@example.com?"
Yes, Exchange can be configured to relay through the existing servers (keeping spam management simpler/same) as well as present email@example.com as the return address.
Comment: Thanks! Can you provide a few more words on how outbound mail works? Does this involve my subdomain approach and set a reply-to header, or what is exactly happening?
Comment: You should not need to modify the "reply-to" as the Exchange address space can be set to match the domain of the original forwarding (POP) server. Everything, incoming and outgoing, can route through the original (POP) infrastructure.


Generating hierarchic URI's based on taxonomy

Question: I was wondering whether it is possible to have a taxonomy whose URL's are based on taxonomy.
Example: I have a taxonomy list called 'Gallery type' which exists of the following items in which 'Pictures' and 'Movies' are higher in the hierarchy than the subitems:
pictures

pictures-2009
pictures-2010
pictures-2011
pictures-2012

movies

movies-2009
movies-2010
movies-2011
movies-2012

I also have a (gallery) content type in which it is obliged to select an item from the taxonomy list (actually a submitter should select two items: one main item and one subitem (e.g. 'pictures' AND 'pictures-2012'). Then I have made a view for every item in the taxonomy list so that every taxonomy term is a page that contains links to the pages that are created with the term as obliged option (I know that this is hard to follow, but please bear with me)
Example: I create a new gallery named 'Animals' and select the options 'pictures' and 'pictures-2012'. This gallery 'Animals' will be visible on the corresponding views, i.e. /pictures AND /pictures-2012. The page its URI however will be /content/animals. My question is then if it is possible to make the URI follow the hierarchy posed in the taxonomy. In this case it would be: /pictures/pictures-2012/animals
If anything is not clear, please do tell me! English is not my mother tongue, so forgive me if it contains a lot of syntactic and/or grammatical errors!
Comment: Not to tell you what to do since I don't know the full use case here, but...... I would think it would be a lot easier and more powerful to have another taxonomy that is the year instead of type-year.  For instance, if you did it that way all of this would just fall into place from a hierarchy standpoint plus with the added bonus of being able to sort/search by year, eg, give me everything in 2009, or give me all pictures.  just 2 cents ;)
Comment: @Jimajamma do you mean a whole seperate list? So that I have a list called 'Gallery type' and one called 'year'? Or am I missing your point? If this is what you mean, how can this be hierarchially more logical?
Comment: if you have a one taxonomy vocabulary with a terms of years, eg, 2009, you can use it to tag any type of content with the year 2009, whereby with having a pictures-2009 term, that can only categorize pictures in the year 2009.  same with movies.  also with those terms you can't easily find all content from 2009 if you if wanted to.  so I would think it to be cleaner to create two vocabs. also, from a hierarchy standpoint, you can set up a view to look at something like of content/%type/%year and then select on type and year pretty easily.  just separating things more cleanly.
Comment: Well I've done what you said (i.e. deleted the pictures-2009 etc. and added a new list called 'year', cotaining all the different years). But what do I do now? I added an extra field to the gallery type, so one has to specify whether it is a picture or movie gallery and then one has to specify the year. Okay, that's fine. But how do I put up a view which gives me a hierarchial structure then? How can I put the year 'higher' than the gallery type?
Comment: It seems to be better if I just put it like this: pictures and movies as main taxonomy terms and the years as subterms. This way I can easily create aliases.
Comment: you can use views arguments/contextual filters, just use two (whatever order) taxonomy terms, and create a page display with those in the path, eg, whateverpath/%/%, and then when you goto whateverpath/pictures/2010 it will return content tagged with pictures and 2010.
Comment: I really don't have enough experience with views to accomplish this (I've use simple views thusfar). So maybe if you could post a more detail overview of what I should do (and possibly a screenshot of the settings of the view?) as an answer, I can check that as the correct answer.
Answer: From the comments, this is one way how I would do this:

create a taxonomy vocabulary called gallery type.
create a taxonomy vocabulary called year.
populate them with the appropriate terms.

Then I'd create a view:

filter it on gallery type (or whatever content types are tagged by the above vocabs)
also filter it on all nodes that are published

In arguments (d6) or contextual filters (d7) I'd put in two arguments.  They would be taxonomy terms and you can select them from the dropdown list from taxonomy:

For the first, select taxonomy term and then in validation, select taxonomy and term again and restrict it to the gallery type vocabulary.
For the second select taxonomy term and then in validation, select taxonomy and term again restrict it to the year vocabulary.

Then, in the Fields, select whatever fields you want displayed.  For ease here, just select node title, but once in production I'd imagine they'd be title, a picture or image or two, a description, etc.
Now, create a page display in the view, and in the path enter
myfirstview/%/%
Change myfirstview to whatever makes sense on your website's hierachy.  What the two %'s do is substitute in the taxonomy terms above.
Save everything.
Now you have created a View that does all that hierarchy for you.  So, if someone goes to...
www.yourhost.com/myfirstview/movies/2009
...Views will create the page for you and display the title of whatever content has been tagged with both movies and 2009 (views takes the hardcoded myfirstview and substitutes in the movies and 2009 and then matches them against what content is tagged with those terms) and if they went to...
www.yourhost.com/myfirstview/pictures/2012
...Views would create a page of all pictures from 2012 doing the same logic.
What is nice is that you can then create a views that filter on only one of the vocabularies, eg,
www.yourhost.com/mysecondview/pictures
that would list all pictures
or
www.yourshost.com/mythirdview/2012
that would list all content from 2012
As you get more comfortable with Views you can then add all kinds of different sortings, eg, sort by posting or last edit date, sort alphabetically by title, etc, but this should get you on your way.  Just play around with the settings and hit Preview a lot.  You'd be amazed how simple it is once you get past the up front daunting nature of all the various options you have.


SSH to server with xargs

Question: I have a pretty easy problem I'm trying to resolve here. I'm constantly running the (host) command on domains, to get their IPs, then (host) again on those IPs to get their PTRs, then I'm SSHing to that server represented in the PTR:
[root@box ~]$ host DomainIWant.com
DomainIWant.com has address 22.214.171.124

[root@box ~]$ host 220.127.116.11
18.104.22.168.in-addr.arpa domain name pointer vps2010.DomainIWantHosts.com

[root@box ~]$ ssh vps2010.DomainIWantHosts.com

Simple enough right? It's just tedious doing this over and over, so as with everything Linux I want to speed it up by automating it:
[root@box ~]$ host DomainIWant.com | awk '{print $4}' | xargs host | awk '{print $5}' | xargs ssh -tt

The problem that I'm having is when I call ssh via xargs, I do get SSH'd into the remote server but with the error [tcgetattr: Invalid argument]. I'm sitting at the remote server's shell but when I try to run any command it just hangs and eventually I have to Ctrl-C to break out of it.
If I don't tack on the (ssh -tt) then I get a [Pseudo-terminal will not be allocated because stdin is not a terminal] error. This seems like such a simply problem so I'm hoping someone more familiar with ssh via xargs can let me know if it's even possible.
Comment: Are you getting into the server using ssh? If so, this should not be the problem of the command you presented above.
Comment: Yes I'm SSHing into a box inside a network, then using that box to jump to other ones on the same network. Using the above commands both lead to the 2nd server I'm connecting to not allowing me to type in any input.
Answer: If you're using a shell that supports backticks- or $()-style command substitution (most shells do), then in your case, you can avoid using xargs entirely, like this:
ssh $(host -t PTR $(host -t A DomainIWant.com | awk '{print $4}') | awk '{print $5}')

(I added the -t flags to the host commands, to ensure they only emit 1 line of output.)
Comment: Thanks! This worked just as I wanted, nice to see I can bypass xargs all together. That's why I love Linux always more than one way to accomplish something.

SSH to server with xargs


Relation involving the inverse of a symplectic form

Question: I am working on Exercise 14.34 on Penrose's "The Road to Reality". I need to prove the following result as a means to show Jacobi's identity for Poisson brackets (which I know how to do). In what follows I am using abstract index notation and $\nabla$ is some (arbitrary) torsion-free connection.
Let $S_{ab}$ be a $(0,2)$ non-singular antisymmetric tensor ($S_{ba}=-S_{ab}$) that satisfies $d$S$=0$ or equivalently $\nabla_aS_{bc} + \nabla_bS_{ca} + \nabla_cS_{ab} = 0$. Let also $S^{ab}$ be the inverse of $S_{ab}$ (namely, $S^{ab}S_{bc} = \delta^a_c$, where $\delta$ is Kronecker's delta tensor). I need to show the following:

$$S^{ab} \nabla_a S^{cd} + S^{ac} \nabla_a S^{db} + S^{ad} \nabla_a S^{bc} = 0$$

My understanding - although Penrose is not always clear about those things - is that I can show the result using just the assumptions above. In particular, without any use of a metric for index lowering. Is that possible?
What I tried was to differentiate $S^{ab}S_{bc} = \delta^a_c$ using Leibniz rule (aka the product rule) but this led me to a dead end as there is always lower index terms that I cannot get rid of.
Note: I am not necessarily looking for a full answer, as I want to figure out this myself. I am interested in a hint and also potentially making sure I am not missing any assumptions. Penrose is notoriously vague about those things sometimes (although this is otherwise some excellent and concise work).
Comment: Can you say something about that equality? Is that just an exercise or it is of any use?
Comment: @ArcticChar Sure, like I mentioned in the post it is sufficient to prove Jacobi's identity for Poisson brackets. A poisson bracket is $\lbrace f, g \rbrace = - \frac{1}{2} S^{ab} \nabla_a f \nabla_b g$ where $f$ and $g$ are scalar fields. Jacobi's identity is $\lbrace f, \lbrace g, h \rbrace \rbrace + \lbrace g, \lbrace h, f\rbrace \rbrace + \lbrace h, \lbrace f, g \rbrace \rbrace =0$. The equality then yileds Jacobi's identity by also making use of the torsion-free property (since we have to take severals covariant commutators on these scalars).
Answer: Differentiate $S^{ab}S_{bc} = \delta^a_c$ gives (I hope I did not mess up the sign)
$$ \nabla_c S^{ab} =  S^{ad} S^{be} \nabla_c S_{de}.$$
With that, you should be able to show
\begin{align}
S^{ab}& \nabla_a S^{cd} + S^{ac} \nabla_a S^{db} + S^{ad} \nabla_a S^{bc} \\
&= S^{ab} S^{ce}S^{df} \nabla_a S_{ef} + S^{ac} S^{de} S^{bf} \nabla_a S_{ef} + S^{ad} S^{be} S^{cf}\nabla_a S_{ef}
\end{align}
all the repeated indices (a, e, f) are summed over. Of course we want to use
$$ \nabla_a S_{ef} + \nabla_e S_{fa} + \nabla_f S_{ae} = 0,$$
and to do that, you can rename a, e, f on the second and third terms: e.g. renaming $a\to e$, $e\to f$, $f\to a$ respectively, we have
$$S^{ac} S^{de} S^{bf} \nabla_a S_{ef} = S^{\color{red}{e}c} S^{d\color{green}{f}} S^{b \color{pink}{a}} \nabla_{\color{red}{e}} S_{\color{green}{f}\color{pink}{a}}= S^{ab} S^{ce} S^{df} \nabla_{e} S_{fa},$$
where in the last equality we used $S^{ab}  = - S^{ba}$. One can similarly deal with the third terms and obtain
$$S^{ad} S^{be} S^{cf}\nabla_a S_{ef}= S^{ab} S^{ce} S^{df} \nabla_{f} S_{ae}.$$
Thus we have
$$S^{ab} \nabla_a S^{cd} + S^{ac} \nabla_a S^{db} + S^{ad} \nabla_a S^{bc} = S^{ad} S^{be} S^{cf} (\nabla_a S_{ef} + \nabla_e S_{fa} + \nabla_f S_{ae})=0.$$
Comment: This is very good thanks. Loosely speaking (and very informally) the key insight is that even though we cannot avoid some stacking of the form $S^3$ it will be factored out. Indexing rearranging was never the issue for me, but the "stacking" made me a bit uncomfortable. Thank you for the great and thorough explanation!


Proving $((a\bmod n) (b\bmod n))\bmod n = ab\bmod n $

Question: I am trying to prove a property of modular arithmetic, namely:
$$[(a\bmod n)\times (b\bmod n)]\bmod n = ab\bmod n.$$
I have the basis and hypothesis steps down, but I am having trouble with the hypothesis step:
Proof
Let $P(n)$ be the predicate
$$P(n): [(a \bmod n) \times (b \bmod n)] \bmod n = a  b \bmod n.$$
Basis step:
$$\begin{align*}
\ [(a \bmod 1) \times (b \bmod 1)] \bmod 1  &=  (a  b) \bmod 1\\
\ [( 0 )\times ( 0 )] \bmod 1  &=  (a  b) \bmod 1  &&\text{(any \number is }0\text{ modulo }1\text{)}\\
                     0 \bmod 1 &=  (a  b) \bmod 1\\
                            0      &=      0            &&\text{(true for }n=1\text{)}
\end{align*}$$
Hypothesis step
(Assume that $P(n)$ is true for some $n=k$):
$$[(a \bmod k) \times (b \bmod k)] \bmod k = (a  b) \bmod k$$
Induction Step
(Prove that $P(n)$ is true for some $n = k + 1$)
$$\begin{align*}
\ [(a \bmod (k+1)) \times (b \bmod (k+1))] \bmod (k+1)  &= (a  b) \bmod (k+1)\\
\ [(a \bmod k) + 1 \times (b \bmod k)  + 1] \bmod (k+1)  &= (a  b) \bmod (k+1)\\
\end{align*}$$
I get to here then I can't figure out how to cancel out the 1's on the left hand side.
Any help would be appreciated.
Comment: Do you have to do this by induction? It can be done directly fairly easily, and I honestly do not see how to do it by induction on the modulus; it is not straightforward to see how to relate remainders modulo $k$ with remainders modulo $k+1$; they can be very different. In fact, for any pair of positive integers $r$ and $s$, $0\leq r,s\lt k$, you can find an integer $a$ such that $a\bmod k = r$ and $a\bmod (k+1) = s$.
Comment: If you **really** need to do it by induction, fix $a$, and do an induction on $b$ (assumed non-negative, you can pick up the negatives easily once you have the positives).
Comment: It is incorrect that $a\bmod (k+1) = a\bmod k + 1$. For example, take $a=4$, $k=7$. Then $a\bmod k+1 = 4$, but $a\bmod k + 1 = 5$.
Comment: @ArturoMagidin The assignment only said prove, but induction happens to be the only method of proving that I know.
Comment: @Hunter: Surely you know how to prove things directly? For example, do you prove that if $a|b$ and $b|c$, then $a|c$ by inductin? Or using the definition of "divides"? Use the definition here.
Comment: How would I go about proving this directly then?
Comment: Address $\: n\leq 0 \:$ separately. $\:\:\:$ For $\: 0\lt n \:$, $\:$ express $a$ and $b$ as multiples of $n$ plus members of $\{0,1,2,3,...,n+(-1)\}$. $\:\:\:$ Multiply, expand, and notice that adding multiples of $n$ does not change the result. $\;\;\;\;$
Answer: Note that by the Chinese Remainder Theorem, for any $k\gt 0$, and for any integers $a$ and $b$, there exists an integer $x$ such that
$x\bmod k = a\bmod k$ and $x\bmod (k+1) = b\bmod (k+1)$. That is: the remainders of $x$ modulo $k$ and modulo $k+1$ are completely unrelated. So I do not see how you are going to be able to leverage "knowing" the result modulo $k$ into a proof of the result modulo $k+1$, unless you simply prove it directly modulo $k+1$.
So it is really simpler to show that the result holds modulo $n$ directly, for any $n\gt 0$.
Remember that $x\bmod n = r$ if and only if $0\leq r\lt n$ and $x-r$ is a multiple of $n$.
So first show that $ab - (a\bmod n)(b\bmod n)$ is a multiple of $n$. For example, if $a\bmod n = r$ and $b\bmod n = s$, then $a-r$ and $b-s$ are both multiples of $n$; then $(a-r)b$ is a multiple of $n$, and $r(b-s)$ is a multiple of $n$, so...
Comment: Thank you this was a good start for me.
Answer: Let $c = a\bmod n$, true iff $a = jn +c$ for some integer $j$.  Similarly  $d = b\bmod n$ iff $b = kn +d$ for some integer $k$.
So,
$ab\bmod n = [(jn+c) \times (kn+d)]  \bmod n $
$= [(jkn+jd+kc)n + c \times d] \bmod n $
$ = c \times d \bmod n $
$=  [(a\bmod n)\times (b\bmod n)]\bmod n$,
which is what you wanted to prove.
Comment: the last step. How prove `a * b mod n` = '[(a mod n) * (b mod n)] mod n`?
Comment: @Algebra My identities start at $ab\bmod n$  and finish at $=  [(a\bmod n)\times (b\bmod n)]\bmod n$.  What do you think is missing?


What is a collection of time series called?

Question: I am involved in an engineering project. We concern ourselves with a manufacturing process in which mechanical parts are processed. Every time a part is processed we get a set of time series data.
Let's say a part is produced in 5 seconds and we get temperature and torque with a rate of 1000 per second. So every Millisecond we write down the time (called timestamp) and the value and we do this for temperature and torque. Thus we get for each part two "lists" of time-value-pairs. Our system is not so exact so we cannot match up the time stamps exactly for both temperature and torque. Each of these lists is called a "time series" and for each time series we get about 5000 data entries (time-value-pairs). So for each processed part we have this data object which consists out of two time series. I am looking for a word for this data object. There is a mayor series of processed parts, where the parts are the elements of this series, but I am not concerned with that series.
With () being a pair and [] a list, we got
<code>timeseries = [ (timestamp, value), ...(timestamp, value) ]
word = [ ('temperature', timeseries), ('torque', timeseries) ]
mayorsieries = [word, ..., word]
</code>
So in total we have a series of "word" that consists out of multiple time series. Thus I am looking for a word for "multiple time series that belong together". It is not "multivariate time series" because the timestamps are not aligned.
What does one call this data object in question?
Comment: I would call such a data object a multivariate time series despite the timestamp for temperature and torque not being aligned. That's just an artifact of how these data are stored. You can view it as a missing data problem. As with any timeseries analysis, the first step will be to infer some type of continuous time trend before performing any inference or prediction. After that point, the alignment of timestamps for torque and temperature is no longer of concern.
Comment: I would call a time series a "crow" and therefore a related group of them that hang out together ought to be called a [murder of crows](https://en.wikipedia.org/wiki/A_Murder_of_Crows).  All facetiousness aside, could you tell us what your *statistical* question might be?
Comment: @whuber: the question is regarding statistical nomenclature / terminology.
Comment: I am not aware of a term although there may be a term in signal processing for a collection of signals or physics for sound/light waves.  Maybe we just take the waves bit and call it a beach? You could give signal processing forum a shot.
Answer: Answered in comments by AdamO:

I would call such a data object a multivariate time series despite the
timestamp for temperature and torque not being aligned. That's just an
artifact of how these data are stored. You can view it as a missing
data problem. As with any timeseries analysis, the first step will be
to infer some type of continuous time trend before performing any
inference or prediction. After that point, the alignment of timestamps
for torque and temperature is no longer of concern.


Código com JDBC falha com exceção

Question: Estou tentando realizar uma pesquisa no banco de dados através do java.
Estou utilizando esse código, mas esta entrando na exceção:
public ArrayList<Pessoas> pesquisar(String nome) {
    ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
    try(Connection con = new MySql().conecta()) {

        String sql = "select *"+
        " from pessoas"+
        "where nome like '%?%'";

        PreparedStatement stmt = con.prepareStatement(sql);

        stmt.setString(1, nome);

        java.sql.ResultSet rs = stmt.executeQuery(sql);

        while (rs.next()){

        Pessoas pesquisa = new Pessoas();
        pesquisa.setNome(rs.getString("nome"));
        pesquisa.setDataNasc(rs.getString("dataNasc"));
        pesquisa.setTipo(TIPO.valueOf(rs.getString("sexo")));
        pesquisa.setEmail(rs.getString("email"));
        pesquisa.setCelular(rs.getString("celular"));
        pesquisa.setTelefone(rs.getString("telefone"));
        pesquisa.setEndereco(rs.getString("endereco"));
        pesquisa.setNumCasa(rs.getString("numCasa"));
        pesquisa.setBairro(rs.getString("bairro"));
        pesquisa.setCidade(rs.getString("cidade"));
        pesquisa.setCep(rs.getString("cep"));
        pesquisa.setEstado(rs.getString("estado"));
        pesquisa.setObservacao(rs.getString("observacao"));

        // adicionando o objeto à lista
        lista.add(pesquisa);

        }

        rs.close();
        stmt.execute();
        stmt.close();

    } catch(SQLException e) {
        System.out.println("teste15");

    }
    return lista;

}

Comment: Esse  `System.out.println("teste15");` não serve pra nada nesse código, não ajuda a entender porque caiu no catch. Logo, remova isso, e troque por `e.printStackTrace();` que é o que realmente irá mostrar o motivo.
Comment: Então tire o `try-catch` para ver a exceção acontecer. Eu costumo dizer que meus código raramente passam de meia dúzia de `try-catch`, eu não entendo porque as pessoas enchem disso no código, captura exceção quase sempre deixa o código menos robusto e não mais.
Comment: @Maniero a exceção é checada, e as malditas IDEs indicam essa solução pra "resolver o problema" da exceção checada. Com uma boa intenção, a IDE acaba induzindo quem tá aprendendo a fazer uma coisa sem fazer ideia do que está fazendo.
Comment: De qualquer sorte, se você tivesse um pouco mais de cuidado e posto um espaço depois do nome da tabela ou um espaço antes do `where` você não teria gerado erro ao preparar consulta
Answer: Em primeiro lugar, o princípio da inversão de dependências diz que deve codificar-se para abstrações, e não para implementações. Uma aplicação bem direta desse princípio seria usar List ao invés de ArrayList.
Segundo, você já está usando o try-with-resources no seu Connection, mas é importante usá-lo adequadamente no PreparedStatement e no ResultSet também.
Terceiro, use a sintaxe do diamante sempre que possível.
Quarto, prefira usar nomes de classes sempre no singular.
Quinto, a sintaxe do seu SQL está errada. Você não deve colocar o ? dentro de aspas.
Sexto, ou você deve tratar as exceções adequadamente ou relançar. Não fazer nenhum dos dois é sempre uma má prática de programação que vai lhe ocultar os erros.
Sétimo, você tem um stmt.execute(); sobrando de bobeira no final.
Oitavo, você estava executando a SQL em dois lugares diferentes, com con.prepareStatement(sql) e com stmt.executeQuery(sql). Substitua a segunda forma por stmt.executeQuery().
Nono, nomes de classes não devem ser escritos em letras apenas maiúsculas (TIPO). Use Tipo. Veja mais sobre isso nessa resposta.
Eis o seu código revisado:
private static final String SELECT_SQL = "SELECT * FROM Pessoas WHERE nome LIKE ?";

public List<Pessoa> pesquisar(String nome) {
    try (
        Connection con = new MySql().conecta();
        PreparedStatement stmt = con.prepareStatement(SELECT_SQL))
    {
        stmt.setString(1, "%" + nome + "%");

        try (ResultSet rs = stmt.executeQuery()) {
            List<Pessoa> lista = new ArrayList<>();
            while (rs.next()) {
                Pessoa pesquisa = new Pessoa();
                pesquisa.setNome(rs.getString("nome"));
                pesquisa.setDataNasc(rs.getString("dataNasc"));
                pesquisa.setTipo(Tipo.valueOf(rs.getString("sexo")));
                pesquisa.setEmail(rs.getString("email"));
                pesquisa.setCelular(rs.getString("celular"));
                pesquisa.setTelefone(rs.getString("telefone"));
                pesquisa.setEndereco(rs.getString("endereco"));
                pesquisa.setNumCasa(rs.getString("numCasa"));
                pesquisa.setBairro(rs.getString("bairro"));
                pesquisa.setCidade(rs.getString("cidade"));
                pesquisa.setCep(rs.getString("cep"));
                pesquisa.setEstado(rs.getString("estado"));
                pesquisa.setObservacao(rs.getString("observacao"));

                // adicionando o objeto à lista
                lista.add(pesquisa);
            }
            return lista;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

Uma possível melhoria seria revisar a forma de se instanciar Pessoa. Leia essa resposta para maiores informações acerca disso.
Além disso, tenho certeza que esse new MySql().conecta() poderia ser feito de alguma outra forma melhor.
Answer: Não use SQLException no catch pois ele vai exibir somente exceções do tipo SQLException e esconder todas as outras, só vale a pena escolher o tipo de exceção se você for tratar ela.
Faça um teste e se der exception novamente trás da ROOT CAUSE aqui!
public ArrayList<Pessoas> pesquisar(String nome) {
    ArrayList<Pessoas> lista = new ArrayList<Pessoas>();

    try {
        Connection con = new MySql().conecta()

        String sql = "select *"+
        " from pessoas"+
        "where nome like '%?%'";

        PreparedStatement stmt = con.prepareStatement(sql);

        stmt.setString(1, nome);

        // trabalhe com PreparedStatement assim!
        stmt.executeQuery();
        java.sql.ResultSet rs = stmt.getResultSet();

        while (rs.next()){

        Pessoas pesquisa = new Pessoas();
        pesquisa.setNome(rs.getString("nome"));
        pesquisa.setDataNasc(rs.getString("dataNasc"));
        pesquisa.setTipo(TIPO.valueOf(rs.getString("sexo")));
        pesquisa.setEmail(rs.getString("email"));
        pesquisa.setCelular(rs.getString("celular"));
        pesquisa.setTelefone(rs.getString("telefone"));
        pesquisa.setEndereco(rs.getString("endereco"));
        pesquisa.setNumCasa(rs.getString("numCasa"));
        pesquisa.setBairro(rs.getString("bairro"));
        pesquisa.setCidade(rs.getString("cidade"));
        pesquisa.setCep(rs.getString("cep"));
        pesquisa.setEstado(rs.getString("estado"));
        pesquisa.setObservacao(rs.getString("observacao"));

        // adicionando o objeto à lista
        lista.add(pesquisa);

        }

        rs.close();
        //stmt.execute(); não precisa disso
        stmt.close();

    } catch(Exception e) {
        e.printStackTrace();
    }
    return lista;

}

Esta pergunta/resposta está associada com esta outra: Exceções em Java
Recomendo a leitura para um melhor entendimento.
Comment: A falta do espaço entre o nome da tabela `pessoas` e a palavra chave `where` continua gerando erro de sintaxe no SQL, a String sendo preparada é a absurda "`select * from pessoaswhere nome like '%?%'`"

Código com JDBC falha com exceção


Como criar uma lista de múltiplos de 3, a partir de outra lista de números?

Question: meus_numeros = [1, 56, 342, 12, 781, 23, 43, 45, 123, 567]

for c in meus_numeros:
    if c%3 == 0:
    print(c, end='')

File "<ipython-input-12-2b3fd4ceddad>", line 3
    print(c, end='')
        ^
IndentationError: expected an indented block

Comment: O `print` está identando no mesmo nível do `if`, é só arrumar a identação que funciona: https://ideone.com/T1wuoe - além disso, estou votando para fechar como "erro de digitação", seguindo o que foi definido aqui: https://pt.meta.stackoverflow.com/q/7476/112052
Answer: Você pode utilizar list comprehension, que irá te retornar uma nova lista com os múltiplos de 3:
meus_numeros = [1, 56, 342, 12, 781, 23, 43, 45, 123, 567]

nova_lista = [numero for numero in meus_numeros if numero % 3 == 0]
print(nova_lista)

Answer: Use a função .append()
.append() é um método que anexa um elemento ao final da lista. Logo, se você criar uma lista e usar .append(c), ele irá adicionar o c ao final da lista.
Seu código ficaria assim:
meus_numeros = [1, 56, 342, 12, 781, 23, 43, 45, 123, 567]
lista = []
for c in meus_numeros:
    if c%3 == 0:
        lista.append(c)

Comment: Printar uma lista não parece ser a vontade do autor da pergunta já que ele delcarou seu print como `print(c, end='')`
Comment: retirei o print
Answer: Seu problema foi ter colocado o print fora do laço if.
Já que o valor da variável C é a condição para printar ou não a linha (se o número testado for um número divisível por três) e como este valor depende da comparação do If, seu print deve estar identado dentro do laço:
meus_numeros = [1, 56, 342, 12, 781, 23, 43, 45, 123, 567]

for c in meus_numeros:
    if c%3 == 0:
        print(c, end=' ')

P.S. Seu end='' estava sem espaço, então os números eram printados "grudados". Coloquei um espacinho ali pra ficar inteligível.
Comment: Obrigado, resolveu meu problema.
Answer: Para você criar uma nova lista, contendo os múltiplos de 3, contidos inicialmente em uma outra lista, você pode utilizar o seguinte algoritmo...
meus_numeros = [1, 56, 342, 12, 781, 23, 43, 45, 123, 567]

multiplos_tres = list()
for c in meus_numeros:
    if c % 3 == 0:
        multiplos_tres.append(c)
multiplos_tres.sort()
print(f'\033[32mA lista dos múltiplos de "3" é: {multiplos_tres}')

Observe que este algoritmo varre a lista inicial e verifica se cada um dos elementos são múltiplos de 3. Caso positivo, inseri na lista multiplos_tres.
Depois de ter inserido todos os possíveis múltiplos em multiplos_tres, o algoritmo ordena os valores e, em seguida, os exibe.
Agora, se você deseja apenas exibir os elementos da lista original que são múltiplos de 3, Você pode utilizar o seguinte algoritmo...
meus_numeros = [1, 56, 342, 12, 781, 23, 43, 45, 123, 567]

print(f'\033[32mOs múltiplos de "3" são:')
for c in meus_numeros:
    if c % 3 == 0:
        print(c, end='')
        print(', ' if c < meus_numeros[-1] else '.', end='')

Neste caso, o algoritmo varre a lista original e, caso o elemento seja múltiplo de 3, exibe na tela.


How can i know that for how many days i am banned

Question: When i want to suggest some edits. This only gives me a message

You are temporarily banned from suggesting edits

I know that why i am banned! But now i want do everything on a right way.
So am i banned for lifetime?? If not then how can i know that after how many days i can start suggesting edit??
Any help will be appreciated from community members.
Answer: You are banned for 4 more days. You are banned because most probable you weren't paying attention and approved wrong edits.
Comment: I don't know. Do you plan to get there? :)
Comment: Thanks @Marius.
Comment: Is there is any way for user to know that??
Comment: Usually you should get a message below "You are temporarily banned from suggesting edits" saying "Come back in....days ... hours....". but I don't know why you don't have that.
Comment: oh! thanks.. may b this is a bug
Comment: @Marius can you tell what is ban is duration for second and third time?


If not minimizing SSEs, what am I doing?

Question: I've got a problem that can be summarized as a linear regression. Thus it takes the following form:
$$
Y=X \beta +\epsilon
$$
where $Y$ and $\epsilon$ are vectors of size $N\times1$, $X$ is a matrix of size $N\times3$, and $\beta$ is a vector of size $3\times1$ (i.e., I am solving for three parameters).
The proper way to solve this under an ordinary least squares framework is via the normal equations—that is, taking the partial derivative of the sum of squared errors with respect to each parameter, and solving for where that equals zero in order to minimize the sum of squared errors.
However, this works rather poorly for me. On a whim, I tried just doing the following to solve for the parameters instead:
$$
\beta = X^{-1}Y
$$
This actually works out really, really nicely. The problem is, I can't justify it, and I don't know what it's doing! Note that it's basically ignoring the idea that there are any errors at all.
Any ideas as to what's going on here? Thanks in advance.
Comment: Please define what you meant with $X^{-1}$. Is it the inversion on a non squared matrix?
Comment: I agree with niandra - you should be explicit about what you're actually doing when you're inverting $X$.
Answer: Since the regressor matrix is not square, it does not have an inverse. I suspect though that it is of full column rank ($=3$), i.e. that your three regressors are not perfectly colinear. Then, the regressor matrix has a "left inverse", i.e. a matrix $X^{-1}_{left}$ that satisfies
$$X^{-1}_{left}X =I$$
This matrix is, ahem, equal to $(X'X)^{-1}X'$. So essentially you found
$$\beta = X^{-1}_{left}Y = (X'X)^{-1}X'Y$$
which is exactly the solution to the normal equations written in matrix notation. I guess you did this by software -if you told the software to invert the regressor matrix, it, seeing that $X$ is not a square matrix, interpreted it as asking of it to calculate the left-inverse matrix.
Execution of statistical estimation does "ignore the idea that there are errors", because these errors are unknown, and so however we want it, they cannot be included in our calculations.
Comment: Ah! You hit it dead on the nose. I did indeed do this via software, and the [MATLAB help page](http://www.mathworks.com/help/matlab/ref/mldivide.html) about the `mldivide` function/operator does indeed explain the behavior. Thanks for the explanation, and your patience with my ignorance :-)


IntelliJ + Python plugin: Python remote interpreter gets created without classpath, does not work

Question: When I create a new remote Python interpreter, IntelliJ doesn't find any dependencies to my code and doesn't seem to index any libraries. Most of the code is red. I think I've pinpointed that to the "classpath" being completely empty, which is unlike some other Python SDKs that I have added (local ones). Some of the times I am able to get it to populate the classpath with paths pointing to the IntelliJ Caches directory by clicking around in the interface, but I most of the times it does not work and I cannot reproduce how to make it work. How do I make sure the classpath gets populated correctly?
I am using IntelliJ Ultimate version 2016.2.1. with the Python plugin version 2016.2.162.43. I am developing on a Vagrant virtual machine and I'm adding a Python remote interpreter that is inside a virtual environment (venv) inside the virtual machine. When I add the remote interpreter, I use:

On the SDKs tab - the + button.
Python SDK
Add Remote
I select the Vagrant option
Point it to my Vagrant project directory.
Point it to the python3.5 executable inside my virtualenv
Add the SDK

Then the classpath looks like this: https://www.dropbox.com/s/3xbzopb4y9bhn0u/Screenshot%202016-08-11%2017.19.43.png?dl=0 and IntelliJ doesn't recognize any libraries/builtins. For other SDKs, the classpath contains several entries with remote_sources, python_stubs or python-skeletons in the name and they work.
Answer: While this issue is a bit older, I had the same issue today with IntelliJ IDEA 2021.2.
I was able to solve this by using Navigate -> Search Everywhere -> Type interpreter -> Select Rescan Available Python Modules and Packages.
This prompted downloading of the remote resources and indexing. Afterwards, the classpaths were filled in properly.
Answer: As a workaround, I copied every entry from the local python interpreter classpath to the remote one and everything seems to work
Edit:
Actually, I don't know what triggered it, but some days after I wrote this, I noticed that IDEA started downloading source files from the server. I went to the interpreter settings, and the classpath entries I had manually added were gone and replaced by "system/remote_resources" entries. I think this is how it's supposed to work, but unfortunately I don't why I didn't work from the start nor how to trigger the correct behavior, it just started working on its own.
Comment: I did the same thing, but it's very time-consuming and I was hoping for a better solution.


Is it possible to compare an image with a list of images? [google-cloud-vision]

Question: I'm trying to compare one dog image with a bucket full of dog images and get their similarity, does anybody have some clue to do that?
Answer: You could try out Vision API's ProductSearch: https://cloud.google.com/vision/product-search/docs/
You build a ProductSet of Products. You add reference images to each Product. Later, you send a query image in and it will return the most visually similar results in your ProductSet.
Comment: Using AI would be the only way to do this.
Answer: You can use my Ruby gem that implementes two perceptual image hashing to calculate the image similarity.
<code>require "dhash-vips"

hash0 = DHashVips::IDHash.fingerprint "dog.jpg"

hash1 = DHashVips::IDHash.fingerprint "dog1.jpg"
hash2 = DHashVips::IDHash.fingerprint "dog2.jpg"

puts "dog1 is this much different: #{DHashVips::IDHash.distance hash0, hash1}"
puts "dog2 is this much different: #{DHashVips::IDHash.distance hash0, hash2}"
</code>


Using an array of index values to access a part of an array in JS

Question: I'm trying to find a way to access a part of an array with specific indexes, and the indexes are also in array. So, I have something like that:
var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];

And I'm searching for an easy way to use arrIndexes to access this specific part of arr, so that my output would be simply ['one', 'three', 'five'].
Answer: You can do it with slightly less computational effort by using Array.prototype.map() instead:

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];

const res = arrIndexes.map(i=>arr[i])

console.log(res);
Comment: Good answer! This is optimal (y)
Comment: Thanks! That helped a lot, I knew that there was something easy which I could not think of :)
Answer: You can do it by using Array.prototype.filter() and includes() function. Try this-

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];

const res = arr.filter((item, index) => arrIndexes.includes(index));

console.log(res);
Answer: you can using reduce function like this
 let newAr=arr.reduce((prev,curr,idx,arr)=>{
    if(arrIndexes.includes(idx)){
        prev.push(arr[idx]);
    }
    return prev;
},[])


How is the HPE SSA "remove drives" command supposed to work to shrink an array?

Question: I have an HPE ProLiant DL380 Gen9 Server with 15 internal 8TB SAS LFF drives, in a RAID6 configuration through an HP Smart Array P840ar controller.  It contains a single 94.6 TB Logical Drive [Size: 94.6 TB / Used Space: 109.2 TB (100.0%)]
The server is currently used as a data archive at rest, with no anticipated significant increase in the stored data (or active users, for that matter).  There is only about 55TB of this storage currently utilized, and I would like to remove the "unnecessary" drives for this archive.
My estimate is that only about ~11 of the 15 drives are needed:

Total space needed 55TB x 20% free space = 66TB
66TB / 8TB drive = ~9 drives
Plus 2 drives for RAID6 parity = 11 drives

So I'd like to remove 4 (maybe 5) drives from this configuration.
Page 8 of the HPE Smart Storage Administrator Guide (Part Number: 742648-008a, October 2016, Edition: 8) indicates that Smart HBA Gen9 controllers in RAID mode have a procedure that allows  Removing a drive from an array (restripe the data on an array to occupy fewer physical drives, then remove the excess drives from the array)
But I can not figure out how to make this actually happen.
I have tried the "shrink array" procedure documented on page 74 of the above:
[root@host] /opt/smartstorageadmin/ssacli/bin/ssacli ctrl slot=0
array a remove drives=1I:4:3

Error: This operation is not supported with the current configuration.
Use the "show" command on devices to show additional details about the
configuration.

Reason: Cannot shrink this array, Minimum physical drives reached

Here is the output of the "show" command:
[root@host:] /opt/smartstorageadmin/ssacli/bin/ssacli ctrl slot=0 ld 1
 show

Smart Array P840ar in Slot 0 (Embedded)

   Array A

      Logical Drive: 1
         Size: 94.6 TB
         Fault Tolerance: 6
         Heads: 255
         Sectors Per Track: 32
         Cylinders: 65535
         Strip Size: 512 KB
         Full Stripe Size: 6656 KB
         Status: OK
         MultiDomain Status: OK
         Caching:  Enabled
         Parity Initialization Status: Initialization Completed
         Unique Identifier: ***
         Logical Drive Label: ***
         Drive Type: Data
         LD Acceleration Method: Controller Cache

I don't see a way to use migration to "restripe" an array to occupy fewer drives - it just appears to change the data record size of the stripe (which doesn't correlate to the number of drives it uses)
I don't see a supported method to reduce the size of the 94TB logical volume.
I don't have the hardware resources to put this data "elsewhere" while I rebuild the array with fewer disks.
The only other option I would see might be to:

Migrate the array from RAID6 to RAID5
Remove the "unnecessary" disk with the remove drives command
Physically remove the unused disk
Migrate the (now smaller) array from RAID5 to RAID6
Repeat the above until I have removed 4 disks total

This seems tedious, and I'm not sure if it would actually work. I also don't like the idea of having the copy of the data at only RAID5 several times through this procedure.
I see from this Serverfault post and another that it's "not possible to reduce the size of a logical volume" but why does HP indicate in two areas of its documentation that it is possible to reduce the size of or number of disks in an array?
How does HPE intend the "shrink array" or "restripe data to occupy fewer drives" to work per this documentation?  Is there another option to remove a few drives from this configuration?
Comment: Why do you want to remove the drives?
Comment: @ewwhite I can use them in other systems, and I'd rather not have drives spinning that are serving no purpose.
Comment: That's a lot of effort to reclaim a couple of disks.
Answer: You only have one logical drive and zero free space.
That's why you can't shrink the array.
There is a "consolidatespace" command that rearranges logical drives to leave free space at the end, but the mistake in your environment was creating a logical drive that spans the entire array.
Here's an example of an environment where I can shrink...
For instance, if I removed logicaldrive 2, I could remove physical disks 3 and 4. (logicaldrive 1 contains the OS)
   Array A (Solid State SATA, Unused Space: 1467279  MB)

      logicaldrive 1 (72.00 GB, RAID 1+0, OK)
      logicaldrive 2 (1000.00 GB, RAID 1+0, OK)

      physicaldrive 1I:3:1 (port 1I:box 3:bay 1, SATA SSD, 960 GB, OK)
      physicaldrive 1I:3:2 (port 1I:box 3:bay 2, SATA SSD, 960 GB, OK)
      physicaldrive 1I:3:3 (port 1I:box 3:bay 3, SATA SSD, 960 GB, OK)
      physicaldrive 1I:3:4 (port 1I:box 3:bay 4, SATA SSD, 960 GB, OK)

Comment: So it sounds like if you accepted the default logical volume creation options (use all disks, maximum size), you're left with no option but to backup the contents of the logical volume, destroy the array, and rebuild a smaller array from the backup?

I don't see a `consolidatespace` option within the HPE SSA documentation.

It would seem that the only circumstance in which you could "restripe the array to occupy fewer drives" would be in the RAIDN+0 mirror options.
Comment: Yeah, the logical drive is too big. Plus, what about the practical aspects? What does your partitioning look like? OS-level changes would have also needed to be made.


Designing DataSource Connection for Concurrency

Question: This code below is the "base" servlet we use for our project:
public class MyServlet extends Servlet {
    private static final long serialVersionUID = 1L;

    protected Connection conn;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet() {
        super();
    }

    protected void connectDB() throws NamingException, SQLException {
        // get database settings

        InitialContext cxt = new InitialContext();

        DataSource ds =(DataSource)cxt.lookup( "java:/comp/env/jdbc/MyDB" );
        conn = ds.getConnection();
    }

    protected void closeDB() throws SQLException {
        try {
            if (conn!=null) conn.close();
        }
        finally {
            conn = null;
        }
    }

    protected void addCacheControl(HttpServletResponse response) {
        response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, pre-check=0, post-check=0");
        response.setHeader("Pragma", "no-cache");
    }

}

For example SomeServlet extends MyServlet ...
Now SomeServlet is access in the browser it do a forward() to a JSP page then it refresh for a certain period (say 10 sec.)
After a while that the page is open, this code throws NullPointerException:
stmt = conn.prepareCall("{call sp_someSP(?, ?, ?)}");

Answer: You cannot use instance fields of a Servlet like this, because it will be shared by multiple threads.
You need to explicitly pass the connection around as parameters and local variables through your program (so that they live on the stack, and each thread gets their own version), or maybe use a ThreadLocal if you want a more "global" approach. A ThreadLocal Connection can also be reliably closed by a ServletFilter when your request is done.
Comment: Yes, and that is exactly the problem here. Your code is not thread-safe. If you want to make it work more than "most of the time", you need to get rid of the non-thread-safe shared state.
Comment: you mean from the 'SomeServlet' I should not access the 'conn'... like stmt = conn.prepareCall("{call sp_someSP(?, ?, ?)}"); ?
Comment: No, I mean, the `conn` field should not exist at all. It should be a local variable or a ThreadLocal.
Comment: Ok, however SomeServlet works most of the time; the conn is just null sometimes
Comment: I mean when the servlet is accessed simultaneously in multiples tabs in a browser
Comment: When you say local variable you mean variable inside function?


Não consigo entender esse tipo de import

Question: Sou iniciante no Python é me deparei com uma coisa que eu não entendi:
import pygame

from pygame.sprite import Sprite

    class Bullet(Sprite):

        def __init__(self,ai_settings,screen,ship):

Minha pergunta é o que seria pygame.sprite import Sprite?
Comment: `from pygame.sprite import Sprite` significa: *Do módulo pygame.sprite importe a classe Sprite*. <(-_-)>
Comment: sprite é um submodulo ?
Comment: Qual a parte de **Do módulo pygame.sprite importe a classe Sprite.** você não entendeu?
Comment: é o pygame.sprite
Comment: Você tem a lib pygame, além da lib principal ela dividida em vários outros módulos, um para cada assunto. Então pode se entender como submodulo especializado, mas na realidade são módulos inclusos ou aninhados.
Answer: O primeiro import carregará o módulo pygame no escopo (namespace) do teu arquivo/módulo enquanto que o segundo carregará apenas a classe "Sprite" nele. Na verdade o segundo import está aí como um atalho já que nada te impede de escrever:
import pygame

class Bullet(pygame.sprite.Sprite):
    ...

Talvez só a praticidade já que "Sprite" é bem menor que "pygame.sprite.Sprite". :-)
Pois do ponto de vista da linguagem eles correspondem ao mesmo objeto:
>>> import pygame
pygame 2.0.1 (SDL 2.0.14, Python 3.8.6)
Hello from the pygame community. https://www.pygame.org/contribute.html
t>>> id(pygame.sprite.Sprite)
43004016
>>> from pygame.sprite import Sprite
>>> id(Sprite)
43004016

Comment: Mano valeu !!! Vc pode me indicar algum lugar para ver como funciona esses modulos aninhados ?
Comment: @kyo129, se a resposta é útil o ajudou você pode votar e a aceitar como resposta correta: Veja, [Como e por que aceitar uma resposta?](https://pt.meta.stackoverflow.com/q/1078/137387),  [Vote cedo, vote frequentemente](https://pt.meta.stackoverflow.com/q/159/137387) e [Como dizer obrigado em respostas](https://pt.meta.stackoverflow.com/questions/605/como-dizer-obrigado-em-respostas)


How to draw circle in cocos2dx

Question: How to draw circle or line in cocos2dx 3.0.
my code is
DrawNode *drawnode = DrawNode::create();
drawnode->drawDot(ccp(15,Director::sharedDirector()->getVisibleSize().height/2),50,Color4F(255,255,255,255));

this->addChild(drawnode);

Comment: explain what isn't working with this code
Comment: draw circle is not visible on layer....i don't know...this code is working or not.....

plz give me solution...and other function like drawPolygon and more drawing function also not working...

Thanks
Comment: i believe color4f should be 1,1,1,1 not 255..
Comment: Thanx..its work fine but i want transparent circle..now its fill with white color and also i want to change border color
Comment: the last value is the alpha channel, if you want to have a transparent white circle you can put `Color4F(1,1,1,0.5)`
Answer: to draw a line cocos2d-x has function
drawsegment
a circle is special type of polygon
so for circle drawpolygon function is used
// for line
 draw->drawSegment(startPoint, moved, 5,Color4F(1,222,120,1) );

// for circle
static CCPoint Circle [nCount]; // vertex array
for ( int i = 0 ; i <nCount; i ++) {
    float rads = i * coef; // radians
    Circle [i] .x = Radius * cosf (rads); //vertex x
    Circle [i] .y = Radius * sinf (rads); //vertex y
}
draw-> drawPolygon (Circle, nCount, blue, 0 , red);

Comment: I wish I could figure out the values for nCount, coef and Radius
Comment: nCount is number of vertices you want in polygon, you can keep it to 150 or something like that
coef is the angle between two adjacent vertices and center
take its value with respect to nCount
like, 2.0f * ( float ) M_PI / nCount

How to draw circle in cocos2dx


Determine the dimension of $V$

Question: Let $a,b \in \mathbb{R}$, with $a\neq b$ and let $V \subset P_n(\mathbb{R})$  be the linear subspace of all polynomials that vanish at $a$ and $b$, i.e. $V= \{f\in P_n(\mathbb{R}) \mid f(a)=f(b)=0\}$
$a$)  Define the nullspace $N(T)$, where $T:P_n(\mathbb{R})\to \mathbb{R^2}$ is some arbitrary linear transformation.
My answer, $N(T) = \{x\in P_n(\mathbb{R}) : T(x) = 0\}$
$b)$  Determine the dimension of $V$.
To answer this I have begun to use the rank-nullity/dimension theorem
Nullity($T$) + Rank($T$) = Dim($V$)
in this case would Nullity($T$) $=2$
Really not sure where to go from here or if I'm correct so far, thanks in advance
Comment: The number $n$ doesn't appear in the definition of $P_n(\mathbb{R})$? Are you sure about that?
Comment: I don't see how this is supposed to be an answer to my question.
Comment: $N(T) = \{v \in V : T(v) = 0\}$ just assumed i had to change it for this certain question? @JoséCarlosSantos
Answer: I suppose (cf.José Carlos comment) that by $P_n(\mathbb{R})$ You mean the polynomials of  degree at most $n$, then define
$$T:P_n(\mathbb{R})\rightarrow \mathbb{R}²,f\mapsto \begin{pmatrix}f(a)\\f(b)\end{pmatrix}$$
It is easy to check that $T$ is linear and obviously $N(T)=V$.
Then because $R(T)=\mathbb{R}²$ (where $R(T)$ is the range of $T$):
$$\underbrace{\dim(V)}_{\dim(N(T))}+\underbrace{\dim (R(T))}_{=2}=\dim(P_n(\mathbb{R}))=n+1$$
and thus $\dim(V)=n-1$.
Answer: We know that $\dim P_n(\mathbb{R}) = n+1$.
Notice that the subspace $W = \{f \in P_n(\mathbb{R}) : f(a) = 0\}$ has dimension $n$.
Indeed, check that $\{(x-a)^k : 1 \le k \le n\} \subseteq W$ is linearly independent so $\dim W \ge n-1$, and $W \ne P_n(\mathbb{R})$ so $\dim W < n+1$. Hence $\dim W = n$.
Now $V$ is a subspace of $W$ and check that $\{(x-a)^k(x-b) : 1 \le k \le n-1\} \subseteq V$ is linearly independent so $\dim V \ge n-1$. On the other hand, $V \ne W$ so $\dim V < \dim W = n$. Therefore $\dim V = n-1$.

Determine the dimension of $V$


Writing $U \subset \mathbb{C}$ as a countable union of open connected sets

Question: Let $U \subset \mathbb{C}$ be open. I want to show that we can write $U$ as a countable union of open connected sets.
If $U$ is empty there is nothing to prove. Else it contains some ball, and hence a point in $\mathbb{Q} + i\mathbb{Q}$.
Denote $U_{\mathbb{Q}} = U \cap \mathbb{Q} + i\mathbb{Q}$.
For each $q \in U_{\mathbb{Q}}$ let $U_q = \{ z \in \mathbb{C}$ | $\exists \gamma_z:[0,1] \to U$ a path connecting $z$ and $q \}$.
We'll show that $U_{q}$ is open and connected:
First if $z_1, z_2 \in U_q$ then $Im(\gamma_{z_1}), Im(\gamma_{z_2}) \subset U_q$, simply by shortening the paths.
It follows that joining these two paths results in a path in $U_q$ and so $U_q$ is path connected, and thus connected.
Now, if $z \in U_q$ by definition $z \in U$, being in the image of some path. Then choosing a ball around $z$ contained in $U$, and knowing the ball is path connected we can connect any point within to $q$. Thus $U$ is open.
Finally, $\cup_{i \in \mathbb{N}} U_{q_i} \subset U$, $\cup_{i \in \mathbb{N}}\{q_i\} = U_{\mathbb{Q}}$.
Letting $z \in U$ we choose a ball around it contained in $U$, and containing some 'rational' point $q$. Since the ball is path connected there is a path within the ball connecting $z$ and $q$, and so $z \in U_q$.
Is this alright?
Comment: The connected components of $U$ will do this for you.
Comment: @zhw. we're not assuming knowledge except basic analysis/calculus.
Comment: What do you mean with "by shortening the paths"?
Comment: @JoséCarlosSantos if a point $z$ is on the image of the path $\gamma_{z_1}$ then selecting $t$ s.t $\gamma_{z_1}(t) = z$; $\gamma_{z_1}|_{[t,1]}$ defines the correct path.
Comment: The proof is allright. I don't know how to write this as an answer tho.
Answer: $\mathbb{C}$ has a countable basis.  It is the collection of open balls of rational radii centered at $z=a+bi$, where $a$ and $b$ are rational.  Then any open $U \subset \mathbb{C}$ can be written as the countable union of these basis sets.
Another way of thinking about $\mathbb{C}$ is that it's isomorphic to $\mathbb{R}^2$.  In fact $\mathbb{R}^n$ has a countable basis.
Comment: thanks, I was looking for a verification though; also added the tag now.


Problema com Function

Question: Olá,
Estou tento um problema com meu código para consulta no mysql,
https://gist.github.com/Alkun/d2239eee1514a0dfc16a
Se o usuario digitar algum valor a pesquisa no banco de dados é feita normalmente, porém se ele deixar o formulário em branco meu isset() não funciona.
A mensagem que aparece é:

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\manos\resultado.php on line 17

<?php
include ("cabecalho.php");
include ("includes/conecta.php");
include ("includes/func.php");
?>

<?php

//Cria a variavel telefone enviada do formulario na pagina painel.php
$telefone = $_POST['telefone'];

//Verifica se o valor de telefone não é vazio.
if (!isset($telefone)) {
header("location: painel.php");
exit;
}
//Conecta com o banco e seleciona os arquivos para efetuar a contagem.
$con = mysqli_connect("localhost", "root", "", "pizzaria");
$query = mysqli_query($con, "SELECT nome, numero, endereco from clientes where telefone = $telefone");
$count = mysqli_num_rows($query);

//Se a contagem for 0
if ($count == 0) { ?>

Ops! não encontramos nenhum cliente com este telefone,
tente novamente!

<?php
die;
//Se a contagem for 1
} else {
if ($count == 1) { ?>

Encontramos 1 cliente com este telefone!

<?php
}
}
//Mostra todos os resultados encontrados.
while ($resultado = mysqli_fetch_assoc($query)) {
echo "Cliente: ". $resultado['nome']. "
";
echo "Endereço: ".$resultado['endereco']. "
";
echo "N°: ".$resultado['numero']. "
";
}

?>

Comment: Mude o `isset` para `empty`.
Comment: obrigado por editar o post, eu não estava conseguindo adicionar no formato código!

a função Empty() funcionou perfeitamente, obrigado! mas porque o isset() não estava funcionando?
Answer: isset verifica se a variável existe e não é nula(NULL), enquanto empty verifica se o valor não vazio para o php os seguintes valores são considerados como vazio ou false:
"" (string vazia)
0 (0 como inteiro)
0.0 (0 como float)
"0" (0 como string)
NULL
FALSE
array() (um array vazio)
$var; (variável declarada porém sem valor.)

No seu código faz mais sentido verifica se $telefone não é vazia do que se ela existe. Mude essa linha:
if (!isset($telefone)) {

Para:
if (!empty($telefone)) {

Problema com Function


View: display first value in a single field in field collection

Question:
Drupal 7, view 3 and field collection.
I have a custom content type with a field collection called personal detail.
Personal detail have 2 fields: name and contact.
Personal detail is zero to unlimited.
In view, I am able to display the values of 'name' field. The problem is there are multiple values for 'name' field. This caused me to have duplicated records (i.e. same node id appears more than once, because the 'name' field)
I only want to display the very first one value of 'name' field which is stored the order of a node.

Solution:
In Go to field collection in view's relationship (right column)
There is a statement: The delta allows you to select which item in a multiple value field to key the relationship off of. Select "1" to use the first item, "2" for the second item, and so on. If you select "All", each item in the field will create a new row, which may appear to cause duplicates.
So select "1" will show the first fields.
Answer: This can be done by modifying the Multiple field settings of your name field:

Click on the "name" field in your view (to edit the settings of field)
Navigate to "Multiple field settings" (present just above "Style" settings)
Click on the checkbox: "Display all values in the same row"
Choose "Display type": Ordered list
Below display type, there is one field "Display": Replace "ALL" with 1
Save the settings and the view.


Pygame not loading Menu straight away

Question: i'm having an issue with pygame, can anyone tell me why it doesn't display the menu GUI? Basically, i want it to load the GUI, and when i push space, it selects "Play Game" and launches the "Game" function. but before it even loads the menu, it's just plain grey. Also when i hit space it doesn't load the game. Thanks.
BTW "GAME()" IS A FUNCTION I MADE FURTHER BELOW, THAT I WANT IT TO LOAD.
import pygame, math, sys, random
pygame.init()

#Variables
darkYellow = 204,204,0
grey = 102, 102, 102
black = 0, 0, 0
white = 255, 255, 255
red = 255,0,0
marroon = 120, 0, 0
green = 0,255,0
blue = 0,0,255
darkBlue = 0,0,128

resolution = 650, 600
myFont = pygame.font.SysFont("Times New Roman", 30)
myFont2 = pygame.font.SysFont("Times New Roman", 15)
myFont3 = pygame.font.SysFont("Times New Roman", 60)

redLeft = 150, 575
redRight = 280, 575
blackLeft = 370, 575
blackRight = 500, 575
radius = 20

def main():
    global window
    window = pygame.display.set_mode(resolution)
    pygame.display.set_caption('Harrys Game')
    window.fill(grey)
    pygame.display.update()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit()
main()

def mainMenu():

    rectWidth = 150
    rectHeight = 40

    #Draw buttons
    pygame.draw.rect(window, (white),(250, 150, rectWidth, rectHeight),0)
    pygame.draw.rect(window, (white),(250, 225, rectWidth, rectHeight),0)
    pygame.draw.rect(window, (white),(250, 300, rectWidth, rectHeight),0)
    highlight = pygame.draw.rect(window, (darkYellow),(250, 150, rectWidth,         rectHeight),0)
    pygame.display.update()

    playGameText = myFont.render("Play Game", 1, red)
    window.blit(playGameText, (260, 150))
    optionsText = myFont.render("Options", 1, red)
    window.blit(optionsText, (275, 225))
    exitText = myFont.render("Exit", 1, red)
    window.blit(exitText, (300, 300))
    pygame.display.update()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                game()
def game():
    startBar = pygame.draw.lines(window, black, False, [(0,545.46),(541.7,545.46)], 5)
    bar2 = pygame.draw.lines(window, black, False, [(0,490.92),(541.7,490.92)], 5)
    bar3 = pygame.draw.lines(window, black, False, [(0,436.38),(541.7,436.38)], 5)
    bar4 = pygame.draw.lines(window, black, False, [(0,381.84),(541.7,381.84)], 5)
    bar5 = pygame.draw.lines(window, black, False, [(0,327.3),(541.7,327.3)], 5)
    bar6 = pygame.draw.lines(window, black, False, [(0,272.76),(541.7,272.76)], 5)
    bar7 = pygame.draw.lines(window, black, False, [(0,218.22),(541.7,218.22)], 5)
    bar8 = pygame.draw.lines(window, black, False, [(0,163.68),(541.7,163.68)], 5)
    bar9 = pygame.draw.lines(window, black, False, [(0,109.14),(541.7,109.14)], 5)
    bar10 = pygame.draw.lines(window, black, False, [(0,54.6),(541.7,54.6)], 5)

    #Draw side columns
    rightBar = pygame.draw.lines(window, black, False, [(541.7,600),(541.7,0)], 5)
    leftBar = pygame.draw.lines(window, black, False, [(108.3,600),(108.3,0)], 5)
    centreBar = pygame.draw.lines(window, black, False, [(325,0),(325,600)], 5)

    #Right column text
    label1 = myFont2.render("You rolled a:", 1, black)
    window.blit(label1, (545, 20))
    rollLabel = myFont2.render("Hit space", 1, black)
    window.blit(rollLabel, (545, 100))
    rollLabel2 = myFont2.render("to roll again", 1, black)
    window.blit(rollLabel2, (545, 117))

    #Display column numbers
    start1 = myFont.render("START", 1, black)
    window.blit(start1, (8, 545.46))
    side2 = myFont.render("2", 1, black)
    window.blit(side2, (54.15, 490.92))
    side3 = myFont.render("3", 1, black)
    window.blit(side3, (54.15, 436.38))
    side4 = myFont.render("4", 1, black)
    window.blit(side4, (54.15, 381.84))
    side5 = myFont.render("SAFE 5", 1, black)
    window.blit(side5, (8, 327.3))
    side6 = myFont.render("6", 1, black)
   window.blit(side6, (54.15, 272.76))
    side7 = myFont.render("7", 1, black)
    window.blit(side7, (54.15, 218.22))
    side8 = myFont.render("8", 1, black)
    window.blit(side8, (54.15, 163.68))
    side9 = myFont.render("9", 1, black)
    window.blit(side9, (54.15, 109.14))
    side10 = myFont.render("10", 1, black)
    window.blit(side10, (54.15, 54.6))
    finish11 = myFont.render("FINISH", 1, black)
    window.blit(finish11, (8, 0))

game()

Comment: do you call `mainMenu()` anywhere in your code? Just declaring the function won't do anything.
Answer: Since you never call mainMenu, none of the code in that function is ever executed.
You can modify your main function so that it calls mainMenu (and melding the two event.get() loops together, since you only need one):
import pygame, math, sys, random
pygame.init()

#Variables
darkYellow = 204,204,0
grey = 102, 102, 102
black = 0, 0, 0
white = 255, 255, 255
red = 255,0,0
marroon = 120, 0, 0
green = 0,255,0
blue = 0,0,255
darkBlue = 0,0,128

resolution = 650, 600
myFont = pygame.font.SysFont("Times New Roman", 30)
myFont2 = pygame.font.SysFont("Times New Roman", 15)
myFont3 = pygame.font.SysFont("Times New Roman", 60)

redLeft = 150, 575
redRight = 280, 575
blackLeft = 370, 575
blackRight = 500, 575
radius = 20

def mainMenu():

    rectWidth = 150
    rectHeight = 40

    #Draw buttons
    pygame.draw.rect(window, (white),(250, 150, rectWidth, rectHeight),0)
    pygame.draw.rect(window, (white),(250, 225, rectWidth, rectHeight),0)
    pygame.draw.rect(window, (white),(250, 300, rectWidth, rectHeight),0)
    highlight = pygame.draw.rect(window, (darkYellow),(250, 150, rectWidth,         rectHeight),0)
    pygame.display.update()

    playGameText = myFont.render("Play Game", 1, red)
    window.blit(playGameText, (260, 150))
    optionsText = myFont.render("Options", 1, red)
    window.blit(optionsText, (275, 225))
    exitText = myFont.render("Exit", 1, red)
    window.blit(exitText, (300, 300))
    pygame.display.update()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                game()

def main():
    global window
    window = pygame.display.set_mode(resolution)
    pygame.display.set_caption('Harrys Game')
    mainMenu()

main()

Resulting in your desired menu:
Comment: Also when i hit space nothing happens?
Comment: Yeh, i got the "X" working but the space still doesn't work :/
Comment: Are you sure the window has focus? You may need to click on the window before it can respond to key presses.
Comment: When i hit space it just stays on the same screen. Should i display update or something?>
Comment: _"Should [the] display update or something?"_ It should do whatever your `game()` function does. On my machine, I just have `def game(): print "you pressed space!"` Then when I press space, it prints "you pressed space!" as expected.
Comment: Would you like my game function so you can see?
Comment: Sure, it may be helpful.
Comment: Done, i added it to the main question.
Comment: I'm not sure if the code is showing in the edit, let me know?
Answer: The problem is, that you call your game function that draws all these lines, and return right away.
All the things are then overriten by the drawing code that is in the mainMenu function.
You are also missing a display.update() at the end.
To solve this, I would place another event loop in your game function, and a display.update() call at the end.

Pygame not loading Menu straight away