text:
Q: RegEx for String.Format Hiho everyone! :)
I have an application, in which the user can insert a string into a textbox, which will be used for a String.Format output later. So the user's input must have a certain format:
I would like to replace exactly one placeholder, so the string should be of a form like this: "Text{0}Text". So it has to contain at least one '{0}', but no other statement between curly braces, for example no {1}.
For the text before and after the '{0}', I would allow any characters.
So I think, I have to respect the following restrictions: { must be written as {{, } must be written as }}, " must be written as \" and \ must be written as \.
Can somebody tell me, how I can write such a RegEx? In particular, can I do something like 'any character WITHOUT' to exclude the four characters ( {, }, " and \ ) above instead of listing every allowed character?
Many thanks!!
Nikki:)

A: I hate to be the guy who doesn't answer the question, but really it's poor usability to ask your user to format input to work with String.Format. Provide them with two input requests, so they enter the part before the {0} and the part after the {0}. Then you'll want to just concatenate the strings instead of use String.Format- using String.Format on user-supplied text is just a bad idea.

A: It sounds like you're looking for the [^CHARS_GO_HERE] construct. The exact regex you'd need depends on your regex engine, but it would resemble [^({})].
Check out the "Negated Character Classes" section of the Character Class page at Regular-Expressions.info.

A: [^(){}\r\n]+\{0}[^(){}\r\n]+

will match any text except (, ), {, } and linebreaks, then match {0}, then the same as before. There needs to be at least one character before and after the {0}; if you don't want that, replace + with *.
You might also want to anchor the regex to beginning and end of your input string:
^[^(){}\r\n]+\{0}[^(){}\r\n]+$

A: (Similar to Tim's answer)
Something like:
^[^{}()]*(\{0})[^{}()]*$

Tested at http://www.regular-expressions.info/javascriptexample.html

A: I think your question can be answered by the regexp:
^(((\{\{|\}\}|\\"|\\\\|[^\{\}\"\\])*(\{0\}))+(\{\{|\}\}|\\"|\\\\|[^\{\}\"\\])*$

Explanation:
The expression is built up as follows:
^(allowed chars {0})+(allowed chars)*$

one or more sequences of allowed chars followed by a {0} with optional allowed chars at the end.
allowed chars is built of the 4 sequences you mentioned (I assumed the \ escape is \\ instead of \.) plus all chars that do not contain the escapes chars:
(\{\{|\}\}|\\"|\\\\|[^\{\}\"\\])

combined they make up the regexp I started with.


text:
Q: Sorting an array of structures by a non-member of the struct Person is a struct that contains 5 char arrays and nothing else.
Score is a float type number that I obtained from a function that uses some of Person fields to calculate it.
I don't wanna add score as a field in the struct Person for complicated reasons.
The goal is to print Person's information (fields) based on how high the score is (from lowest to highest), in order to do that I made this struct to try to connect the score to its corresponding person.
typedef struct PersonWithAScore {
    Person* P;
    float score;
};

(also, is creating that struct even
the right thing to do? )
 PersonWithAScore *PersonScores = (PersonWithAScore*)malloc(number_of_scores*sizeof(PersonWithAScore));

// a for loop is happening here, so I can get all my scores and person(s) in that table, so that I start sorting them
       PersonScores[i].Person = &query;        // query is a Person type
       PersonScores[i].Score = match;      // match is what the score function returns
.
.
.
// that is just a incomplete implementation I tried, you can just skip through and just read after the code

void swap(float *xp, float *yp)  // used in bubblesort
{
   float temp = *xp;
   *xp = *yp;
   *yp = temp;
}
void BubbleSort(PersonWithAScore* PWS, int n)    //n = number of scores
{                                                // void type? I might need to return an array (sorted)
 PersonWithAScore* Temp = PWS;
 int i, j;
   for (i = 0; i < n-1; i++)
   for (j = 0; j < n-i-1; j++)                  // m not so sure it's working, I didn't get to test it
       if (PWS[j].score > PWS[j+1].score)
           swap(&PWS[j].score, &PWS[j+1].score);
 return 0;
}

So after that, I'm hoping to get a sorted array of scores (what initially was PersonScores[]) .
Optimally, I would want to go through the array while I'm printing out Person's information that are associated to each score, that is my first concern.
My second concern, is I'm not sure what sorting is proper in a big database (m currently working with a static database that contains a 100 of Person)
is it better to implement a quicksort algorithm in that case?
I figured it takes a lot of memory, but it is significantly faster than the bubble sort,
I'm trying to get a good balance of both speed and minimizing memory usage. Any ideas ?

A: You can use qsort() to sort the array of structures and recompute the scores on the fly in the comparison function:
float computePersonScore(Person *p) {
    /* compute the score from the person's data */
    ...
}

int compare_scores(const void *e1, const void *e2) {
    float f1 = computePersonScore(e1);
    float f2 = computePersonScore(e2);
    return (f1 > f2) - (f1 < f2);
}

...
    Person array[n];
    ...
    qsort(array, n, sizeof(*array), compare_scores);
...

If computePersonScore() needs a second argument, you can use qsort_r if your system supports it:
float computePersonScore(Person *p, Person *ref) {
    /* compute the score from the person's data */
    ...
}

int compare_scores(const void *e1, const void *e2, void *opaque) {
    float f1 = computePersonScore(e1, opaque);
    float f2 = computePersonScore(e2, opaque);
    return (f1 > f2) - (f1 < f2);
}

...
    Person array[n];
    Person *reference = ...;
    ...
    qsort_r(array, n, sizeof(*array), compare_scores, reference);
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting the sum according to customer id after pivoting I want to get the total transaction of a customer after a pivoting. total should be the last row for customer data. For example customer, 12346.0 should have a total of 2.080. see the image below

A: You can aggregate sum per CustomerID before pivoting, add MultiIndex and then join to gdbf by concat with sorting index by DataFrame.sort_index:
df1 = pd.concat({'Total': df.groupby('CustomerID')[['UnitPrice']].sum()}).swaplevel(0,1)

df = pd.concat([gdbf, df1]).sort_index()


text:
Q: adding style to a javascript form error I am using an hubspot form in an external website:
I am unable to change the css attributes of the javascript body. My code is as below:
<script charset="utf-8" src="http://js.hsforms.net/forms/current.js"></script>
<script>
    hbspt.forms.create({
        portalId: '47773xx3',
        formId: 'xxxxxx',
    });
</script>

How do i add style to this? e.g.: background to it?
Thanks in advance!

A: Try this function below formId, if for instance you want to change background-color:
formData: {
    document.getElementsByTagName("body")[0].style.background-color = "...";
}

Edit:
Sorry, apparently this code is wrong. Try to give a look at this link, I think it can be useful.
http://help.hubspot.com/articles/KCS_Article/Forms/How-do-I-style-my-embedded-form


text:
Q: Ember - Using multiple models I'm trying to create a GUI for changing lots of attributes for lots of different models, from the single route.
So I've read a little about using multiple models [here].1
To give me the following:
    model: function() {

    return Ember.RSVP.hash({
        students: this.store.find('student'),
        objectives: this.store.find('objective')
    });
}

I was expecting that I could then display records etc with the following template code:

Objectives

{{#each objective in objectives}}

{{objective.name}}

{{/each}}

How should I access/display the records and their attributes in the template? Thanks

A: You need to specify that you want the objectives on the model:

Objectives

{{#each objective in model.objectives}}

{{objective.name}}

{{/each}}


text:
Q: Can't parse entities: unexpected end tag at byte offset 0 i dont known, pls help
async def getcatalog(message: types.message):
    if catalog.find_one({"type": 0}) is None:
        await message.answer('К сожалению, товаров нет в наличии')
    else:
        inline_kb = types.InlineKeyboardMarkup()
        for cat in catalog.find({"type": 0}):
            inline_btn = InlineKeyboardButton(cat['name'], callback_data=cat['name'])
            inline_kb = InlineKeyboardMarkup().add(inline_btn)
        await bot.send_message(message.from_user.id, f' Выберите нужный вам товар:', reply_markup=inline_kb)

Can't parse entities: unexpected end tag at byte offset 0

A: Replace:
 f' Выберите нужный вам товар:'

with:
 f' Выберите нужный вам товар:'


text:
Q: SPFx: pnp.sp.search how to get only list items I made search in SPFx, now i need to display only list items. My code example:
pnp.sp.search({
        Querytext: query,
        RowLimit: 20,
        StartRow: 0,
        QueryTemplate: "contentclass:sts_listitem"
    });

But I get not only list items.

A: Only sts_listitem would not sufficient because document is also considered as ListItem in SharePoint as we can still set metadata there.
Possible solution could use STS_ListItem_GenericList which will gives returns result from only custom lists.
Make sure that by using STS_ListItem_GenericList, it will not give result from special list types e.g. Events, Tasks, Discussion Boards, Announcements, etc. So if you want result from those special lists as well then you can add all possible option in query template.
You can find possible option here. (Unfortunately I couldn't find any official link from Microsoft)
So based on above, below code would give you result from all custom lists and also from all contact lists.
pnp.sp.search({
    Querytext: query,
    RowLimit: 20,
    StartRow: 0,
    QueryTemplate: "(contentclass:STS_ListItem_GenericList OR contentclass:STS_ListItem_Contacts)"
});

You can add additional condition based on your requirement with OR condition in QueryTemplate

A: Please refer to the following code to using pnp.sp.search :
import { spfi } from "@pnp/sp";
import "@pnp/sp/search";
import { ISearchQuery, SearchResults, SearchQueryBuilder } from "@pnp/sp/search";

const sp = spfi(...);

// text search using SharePoint default values for other parameters
const results: SearchResults = await sp.search("test");

console.log(results.ElapsedTime);
console.log(results.RowCount);
console.log(results.PrimarySearchResults);

// define a search query object matching the ISearchQuery interface
const results2: SearchResults = await sp.search(<ISearchQuery>{
    Querytext: "test",
    RowLimit: 10,
    EnableInterleaving: true,
});

console.log(results2.ElapsedTime);
console.log(results2.RowCount);
console.log(results2.PrimarySearchResults);

// define a query using a builder
const builder = SearchQueryBuilder("test").rowLimit(10).enableInterleaving.enableQueryRules.processPersonalFavorites;
const results3 = await sp.search(builder);

console.log(results3.ElapsedTime);
console.log(results3.RowCount);
console.log(results3.PrimarySearchResults);

More information for reference: https://pnp.github.io/pnpjs/sp/search/
Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.


text:
Q: Paypal can't reach my website (IPN, .htaccess) When someone pays with paypal standard in my opencart site, the payment gets done, but the IPN notification never reaches my site.
The return address is fine, but it seems like paypal is unable to reach my website.
Is there something I could change in my .htaccess file or hosting settings? I really don't know what to do now.
I even created a dummy php script called ipn.php in my site that sends me an email when it's opened. I gave it's address to paypal as the notification address but it doesn't get called neither!
UPDATE: After testing with the IPN simulator in Paypal's sandbox, I am getting the following error: IPN Delivery Failed:I/O error: Connection timed out; nested exception is java.net.ConnectException: Connection timed out
My htaccess file:
# 1.To use URL Alias you need to be running apache with mod_rewrite enabled.

# 2. In your opencart directory rename htaccess.txt to .htaccess.

# For any support issues please visit: http://www.opencart.com

Options +FollowSymlinks

# Prevent Directoy listing
Options -Indexes

# Prevent Direct Access to files
<FilesMatch "\.(tpl|ini|log)">
 Order deny,allow
 Deny from all
</FilesMatch>

# SEO URL Settings
RewriteEngine On
# If your opencart installation does not run on the main web folder make sure you folder it does run in ie. / becomes /shop/

#RewriteBase /
RewriteRule sitemap.xml /farmaciagimeno.com/index.php?route=feed/google_sitemap
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) /farmaciagimeno.com/index.php?_route_=$1 [L,QSA]

### Additional Settings that may need to be enabled for some servers
### Uncomment the commands by removing the # sign in front of it.
### If you get an "Internal Server Error 500" after enabling any of the following settings, restore the # as this means your host doesn't allow that.

# 1. If your cart only allows you to add one item at a time, it is possible register_globals is on. This may work to disable it:
# php_flag register_globals off

# 2. If your cart has magic quotes enabled, This may work to disable it:
php_flag magic_quotes_gpc Off

# 3. Set max upload file size. Most hosts will limit this and not allow it to be overridden but you can try
# php_value upload_max_filesize 999M

# 4. set max post size. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value post_max_size 999M

# 5. set max time script can take. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_execution_time 200

# 6. set max time for input to be recieved. Uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_input_time 200

RedirectMatch 301 ^/farmaciagimeno.com(.*)$ http://www.farmaciagimeno.com$1


text:
Q: Cloudfront Invalidation for custom origin root Anyone know how to invalidate the root document of a custom origin that use's friendly url's?
eg: example.com ?
What would be the correct Object Path to request via the AWS Create Invalidation dialog?
The documentation only refers to actual files eg: images/image1.jpg, and where it does mention folders there are never the root only images/ etc.

A: The leading slash is optional¹ in an invalidation request for anything other than the root, but for the root of the site, the path to invalidate should just be /.
¹ optional in the console only.  When interacting with the API (including with aws-cli and the SDKs) the leading slash is required.  It isn't clear why the console implicitly and invisibly adds a slash when one isn't supplied, but that's what is happenning.  Best practice would be to always supply the /.


text:
Q: Why does printing a return carriage significantly reduce the rate at which a printf statement executes in C The following code executes and prints a statement ~20 times a second.
    while (1) {
        TX(port, "j1");
        usleep(30000);
        printf("\nPosition:\t%s",  (*RX(port)).data);
    }

Rather than constant new lines, I wish to have a single line printed, with the string that follows Position: updated as quickly as possible. To do so, I've replaced the new line with a carriage return:
    while (1) {
        TX(port, "j1");
        usleep(30000);
        printf("\rPosition:\t%s",  (*RX(port)).data);
    }

It is producing the exact format I want, but now I only get a print every ~6 seconds. Can anyone explain why and offer a solution?

A: On many systems, the amount of time required to output M chunks of data totaling N bytes is proportional to some multiple of M plus some multiple of N.  To avoid wasting lots of time on small output operations, many versions of the Standard library will attempt to aggregate chunks of data to be output, so as to reduce the number of chunks involved.  Sending a newline to stdout is interpreted as a hint that the system should immediately output everything prior to that, without waiting for more data to come, but that only works if data has newlines.  If sending returns without newlines, it may be necessary to use fflush(stdout). to force the system to send data without waiting for more.

A: The reason the output does not update immediately is probably a buffering issue:

*

*stdout is typically line buffered when directed to the terminal.

*the \n in the first loop causes the pending output to be flushed at every iteration.

*The default buffer size varies from one system to another, typical sizes are 512, 1024, 2048 and 4096 bytes.

*each output has about a dozen bytes and occurs every 30 milliseconds or more: it takes about 6 seconds to produce 2 kilobytes, consistent with a 2KB buffer.

*when the buffer is full, it is flushed in one step and the terminal displays about 200 samples very quickly, leaving only the last one to show.

*flushing the output with fflush() or setting stdout as unbuffered at the beginning of the program will solve this issue (see https://stackoverflow.com/a/60202813/4593267 ).

*note however that shorter output strings will leave trailing characters from previous output visible at the end of the terminal line. You should output an escape sequence \033[K to clear the end of line if the terminal supports it (linux and MacOS terminals do, Windows' might not). Alternately, you can add trailing spaces to try and erase previous characters, but it is only a partial solution.

Here is a modified loop:
    for (;;) {
        TX(port, "j1");
        usleep(30000);
        printf("\rPosition:\t%s     ",  (*RX(port)).data);
        fflush(stdout);
    }


text:
Q: ASP.NET Core DI - Inject *only for* the dependency tree of a certain type I'm trying to configure ASP.NET DI to a certain behavior and I'm having trouble finding documentation to cover my specific case.
TL;DR: I have multiples implementations of a certain interface IBar. Multiple classes depend on it, but each class should receive a different implementation. How can I do it?

Let's say I have a class Foo that depends on a service IBar. Now, IBar is pretty generic, and can be used in multiple places, so maybe I also have Baz and Qux depending on IBar.
I have a very specific implementation of IBar, called FooBar, that I want to be injected on instances of Foo, but not on instances of Baz or Qux. Preferrably, I would also want that any dependency of Foo that requires a IBar also get FooBar, but that's not a big requirement.
I know I can do it very manually by registering a factory to Foo and them, inside the factory, use reflection to obtain ctors, and try to resolve them one by one by using the IServiceProvider and injecting IBar whenever the required ctor parameter is of that type --- thing is, this approach is like reimplementing a big part of the DI container, which I think is abominable. And if I want to be transitive about this (the preferred behavior above), I would have to reimplement all the logic scanning and building each type.
What I believe should be possible is something like using the container to create a derived/child container, register FooBar to it and just resolve Foo.


text:
Q: Should I always define a constexpr static data member outside of the class? Why a constexpr static data member needs to be defined outside of the class on C++11, C++14 but it doesn't need that requirement on c++ 17, 20 and above?
struct Array{
    int static constexpr sz_ = 5;
    int ar_[sz_]{};
};

//int constexpr Array::sz_; // needed on `C++11`, `C++14` but not needed for C++17, C++20

void foo(int const& x){

}

int main(){
    foo(Array::sz_);
}

*

*So is this a change in the standard? or should I always define that member outside of the class?

A: The wording of the question is very confusing. static constexpr members have to be defined inline since C++11:

If a static data member of LiteralType is declared constexpr, it must
be initialized with an initializer in which every expression is a
constant expression, right inside the class definition:

https://en.cppreference.com/w/cpp/language/static
Only when such members are ODR-used, a separate definition is required in C++11.
Since C++17, static constexpr members are implicitly inline, and thus no separate definition is required for ODR usage (although it could be provided).

A:
Should I always define a constexpr static data member outside of the class?

Always?! Only a Sith deals in absolutes.
C++17 made static constexpr variables implicitly inline (in the linkage sense, they always needed an in-class initializer). The out-of-class definition remains an optional but deprecated feature.

D.1 Redeclaration of static constexpr data members [depr.static_constexpr]
1 For compatibility with prior C++ International Standards, a
constexpr static data member may be redundantly redeclared outside
the class with no initializer. This usage is deprecated. [ Example:
struct A {
  static constexpr int n = 5;  // definition (declaration in C++ 2014)
};

constexpr int A::n;  // redundant declaration (definition in C++ 2014)

 — end example ]

It's still supported, so you don't have to go about updating all of your existing code bases today. But it may be removed in the future (three, six, maybe nine years from now?) So you won't be able to add a redundant declaration forever.
If you write a new piece of code that requires C++17 or newer, then there's no need to add this re-declaration out of some principle.


text:
Q: MS Access Dense Rank So I am trying to find a way to replicate the denserank() function on my MS Access table. I found the following query that has helped quite a bit:
SELECT
  Table1.ColA
  ,( SELECT Count(*)
     FROM
       Table1 AS T
     WHERE
       T.ColA = Table1.ColA AND
       T.PrimaryKeyFieldName <= Table1.PrimaryKeyFieldName) AS ColB;

This query works great as a way of replicating the rank() function. However, I would like to modify this query so that it replicates denserank() instead. In other words, the ranking for groups now looks like this:
Rank
0
0
0
3
3
3
6
6
6
Instead, what I am looking for is this:
Rank
0
0
0
1
1
1
2
2
2
Another example of what I'm trying to achieve can be seen in Example #3 here:
https://support.microsoft.com/en-us/kb/208946
Any ideas would be greatly appreciated! Thanks in advance!

A: I believe you just want the RANK to increment starting from zero, and incrementing by 1 for each group?  If so, try this:
select T1.*,
   (select count(*)
    from (select distinct T2.flda
          from table1 as T2
         )  as T2
    where T2.flda <= T1.flda
   ) as dense_rank
From table1 as T1;

Here is a second query as I mentioned earlier. However, I don't know if this will give you the grouping that you want.
SELECT T1.*,
   (select count(*)
    from (select distinct T2.flda, T2.fldb, T2.MyDate
          from table1 as T2
         )  as T2
    where (T2.flda <= T1.flda) AND (T2.MyDate <> T1.MyDate)
) AS dense_rank
FROM table1 AS T1;


text:
Q: Como separar un Json que por dentro tiene dos objetos (React Js y Spring boot) estoy desarrollando una aplicación web con React (Frontend) y Spring boot (Backend). Tengo un inconveniente, el cual es que al realizar una consulta a mi base de datos en Postgresql a la tabla proyecto que tiene dos llaves foráneas, me devuelve un Json con dos objetos y los demás atributos de esa tabla. Lo que he intentado hacer es pasar los atributos que necesito a un arreglo para luego mostrarlos en una tabla, pero no he tenido éxito. Quisiera saber si me ayudarían con este problema. Adjunto el código de las respectivas clases.
Clase EvaluarPro
import {ProyectoService} from "./service/ProyectoService";
import React, { Component } from "react";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import { Panel } from "primereact/panel";
import { Menubar } from "primereact/menubar";
import { Dialog } from "primereact/dialog";
import { InputText } from "primereact/inputtext";
import { Button } from "primereact/button";
import { Toast } from "primereact/toast";

import "primereact/resources/themes/nova-alt/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";

export default class EvaluarPro extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          proyectos: [],
          arrayProTable: [],
          proyecto: {
            id_pro: '',
            nombre_pro: '',
            fecha_limite: '',
            archivo_pro: '',
            estado_pro: '',
            retroalimentacion_pro: '',
            id_est_fk: '',
            identif_doc_fk: ''
          },
          estudiantes: [],
          docentes: [],
          identif_doc_busq: '',
        };
        this.proyectoService = new ProyectoService();
        this.jsonTable = this.jsonTable.bind(this);
      }

      componentDidMount() {
        this.proyectoService.getProyectDocent(this.props.identif_doc).then((res) => {
          this.setState( {
            proyectos: res
          });
        });
        this.jsonTable();
      }

      jsonTable(){
        this.state.proyectos.map( (i) => {
          this.setState({
            proyecto: {
              id_pro: i.id_pro,
              nombre_pro: i.nombre_pro,
              fecha_limite: i.fecha_limite,
              archivo_pro: i.archivo_pro,
              estado_pro: i.estado_pro,
              retroalimentacion_pro: i.retroalimentacion_pro
            }
          });
          this.state.estudiantes.push(i.estudiante);
          this.state.docentes.push(i.docente);
          this.state.arrayProTable.push(this.state.proyecto)
          this.setState({
            proyecto: {
              id_pro: '',
              nombre_pro: '',
              fecha_limite: '',
              archivo_pro: '',
              estado_pro: '',
              retroalimentacion_pro: ''
            }
          });
        });
        console.log(this.state.estudiantes);
        console.log(this.state.docentes);
        console.log(this.state.arrayProTable);
      }

      render() {
        return (
          console.log(this.state.proyectos),

{this.props.identif_doc}

              <Panel header="Proyectos">
                <DataTable
                  value={this.state.arrayProTable}
                  paginator = {true}
                  rows = "4"
                  selectionMode="single">
                </DataTable>
                  <Column field="id_pro" header="ID"></Column>
                  <Column field="nombre_pro" header="Titulo del Proyecto"></Column>
                   <Column field="fecha_limite" header="Fecha Limite para Evaluar"></Column>
                  <Column field="estado_pro" header="Estado"></Column>
                </Panel>

        );
    }
}

Clase VistaDocente
import { InputText } from "primereact/inputtext";
import React, { Component } from "react";
import { DocenteService } from "./service/DocenteService";
import { Panel } from "primereact/panel";
import { Button } from "primereact/button";
import { Toast } from "primereact/toast";
import EvaluarPro from "./EvaluarPro";
import root from ".";

import "primereact/resources/themes/nova-alt/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";

export default class VistaDocente extends Component {
  constructor(props) {
    super(props);
    this.Toast = React.createRef();
    this.state = {
      docente: [],
      identif_doc_busq: "",
    };
    this.docenteService = new DocenteService();
  }
  componentDidMount() {
    this.docenteService.getAll().then((data) => {
      this.setState({ docente: data });
    });
  }

  handleChangeIdentif_doc = (event) => {
    this.setState({ identif_doc_busq: event.target.value });
  };

  handleSubmit = (event) => {
    event.preventDefault();
    this.docenteService.existsById(this.state.identif_doc_busq).then((res)=>{
      if(res.data==true){
        this.Toast.current.show({
          severity: "success",
          summary: "Atención!",
          detail: "Se encontro el docente.",
        });
        this.props.history.push("/evaluarpro");
        root.render(<EvaluarPro identif_doc = {this.state.identif_doc_busq} />);
      } else {
        this.Toast.current.show({
          severity: "warn",
          summary: "Atención!",
          detail: "Docente no encontrado.",
        });
      }
    });
  };

  render() {
    return (

        <Panel header="Docentes">

          <form>

              <InputText
                name="identif_doc"
                onChange={this.handleChangeIdentif_doc}
                type="text"
              />
              Identificacion

            <Button
            type="submit"
            label="Ingresar"
            icon="pi pi-check"
            />
          </form>
        </Panel>
        <Toast ref={this.Toast} />

    );
  }
}

Respuesta de la consola


text:
Q: Is there a limit for exceptions fireable at runtime in java? I have a method, basically a loop (with all the proper catch conditions) where the exit condition is the frame being closed. This method that does something that needs an internet connection. If there isn't an internet connection it will recursively call itself until the internet connection is restored. I have noticed that after a certain amount of exceptions fired, it will simply stop to call recursively the method and therefore and no exceptions are fired after that. Is there a limit for exceptions fireable at runtime?
public Download()
{
    try {
            while(!frame.isWindowClosed())
            {
                //doSomething
            }
        } catch (FailingHttpStatusCodeException e) {
            e.printStackTrace();
            textArea.append("****** FailingHttpStatusCodeException ******\n");
            new Download();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            textArea.append("****** MalformedURLException ******\n");
            new Download();
        } catch (IOException e) {
            e.printStackTrace();
            textArea.append("****** IOException ******\n");
            new Download();
        } catch (Exception e) {
            e.printStackTrace();
            textArea.append("****** Exception ******\n");
            new Download();
        }
}

A: set the try inside the loop so as long as the frame is not closed, the loop will continue. If the catch block is the same for all your Exceptions you can just catch the highest Exception:
public Download() {
    while (!frame.isWindowClosed()) {
        try {
            // doSomething
        } catch (Exception e) {
            e.printStackTrace();
            textArea.append("****** "+e.getClass().getName()+" ******\n");
        }
    }
}

As long as doSomething() did not succeeded in closing the frame the while loop will retry.

A: I think it's better for you to have that loop inside a method that is not inside the constructor.. Then call the method from the constructor.
I think what you should be doing is having a mechanism to check if there is network connectivity.. Then perform the required operation if there is connection. If there is no internet connectivity, then continue. You'll have to wrap this inside a while loop of course


text:
Q: CakePHP not able to login with email I want to add some basic authentication to my app. So I mostly followed the cookbook tutorial but I want to sign in with my email instead of a username. So I wrote following lines:
AppController.php
public $components = array(
  'Auth' => array(
    'authentication' => array(
      AuthComponent::ALL => array(
        'fields' => array('username' => 'email')
      )
    )
  )
);

UsersController.php
public function login() {
  if ($this->request->is('post')) {
    if ($this->Auth->login()) {
      $this->redirect($this->Auth->redirectUrl());
    }
    $this->Session->setFlash(__('Invalid email/password combination'));
  }
}

login.ctp
<?php
echo $this->Form->create('User');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->end(__('Login'));
?>

User.php
public function beforeSave($options = array()) {
  $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
  return true;
}

I created a user before but I am not able to login. What am I doing wrong? I am getting crazy...

A: According to the CakePHP book the array should look like this:
public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email')
            )
        )
    )
);

A: DAMN IT
Instead of 'authenticate' => ..., I wrote 'authentication' => ....


text:
Q: UITextField shouldBeginEditing called every other time? iOS unfortunately doesn't have a dropdown picker like html does with the  tag. I decided that I was finally going to create one for my app, and it looks and works great. My dropdown object is a subclass of UITextField. However, I changed something and now it only works some of the time.
User interaction is enabled, but I don't want the textfield to be editable. The class in which my dropdown subclass resides is UITextField delegate, and should receive delegate methods for UITextField.
I have - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ where I check to see if the textfield in question is a dropdown menu, and if it is, I call a method to instantiate a popover and disable editing, but the dropdown only appears on every other tap.
For example, i'll tap the "textfield" and my popover displays. I tap out so the popover goes away, then I tap on the "textfield" and nothing happens. I tap on the textfield once again and the popover appears. No idea why this is happening, here is what i'm doing:
.h
subclass : UIViewController<UITextFieldDelegate>

.m
dropdownTextField.delegate = self;
...
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if(textField == self.measurementSelect){
        NSLog(@"IM CALLED");
        [self showPopover:textField];
        return NO;
    }
    return YES;
}

-(void)showPopover:(id)sender{
    if (_measurementPicker == nil) {
        _measurementPicker = [[iPadMeasurementSelect alloc] initWithStyle:UITableViewStylePlain];
        _measurementPicker.delegate = self;
    }

    if (_measurementPopover == nil) {
        _measurementPopover = [[UIPopoverController alloc] initWithContentViewController:_measurementPicker];
        [_measurementPopover presentPopoverFromRect:self.measurementSelect.frame inView:self.conversionView permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];

    }
    else {
        [_measurementPopover dismissPopoverAnimated:YES];
        _measurementPopover = nil;
    }
}

Every tap gets nslogged, so I assume my popover method is the culprit of this problem. Any ideas?

A: Let's rewrite by teasing apart existence of the UI elements and the visible state of the popover:
// canonical lazy getters for UI elements

- (iPadMeasurementSelect *)measurementPicker {
    if (!_measurementPicker) {
        _measurementPicker = [[iPadMeasurementSelect alloc] initWithStyle:UITableViewStylePlain];
        _measurementPicker.delegate = self;
    }
    return _measurementPicker;
}

- (UIPopoverController *)measurementPopover {
    if (!_measurementPopover) {
        _measurementPopover = [[UIPopoverController alloc] initWithContentViewController:self.measurementPicker];
    }
    return _measurementPopover;
}

// now the show/hide method makes sense.  it can take a bool about whether to show or hide
-(void)showPopover:(BOOL)show {

    if (show) {
        [self.measurementPopover presentPopoverFromRect:self.measurementSelect.frame inView:self.conversionView permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
    } else {
        [self.measurementPopover dismissPopoverAnimated:NO];
        // if you want/need to create a new one each time it is shown, nil the popover here, like this:
        // self.measurementPopover = nil;
    }
}

When the textField begins editing, show the popover like this:
[self showPopover:YES];

And when the delegate gets the didEndEditing message:
[self showPopover:NO];


text:
Q: WPF delete datagrid row based on cell value I am facing a problem right now, I need to delete a datagrid row based on 1 cell value, code samples below:
XAML:
<DataGrid
    x:Name="AccountGrid"
    IsSynchronizedWithCurrentItem="True"
    GridLinesVisibility="Vertical"
    ItemsSource="{Binding}"
    CanUserAddRows="False"
    CanUserReorderColumns="False"
    CanUserResizeColumns="False"
    CanUserSortColumns="False"
    AutoGenerateColumns="False"
    CanUserResizeRows="False"
    HorizontalContentAlignment="Left"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    Margin="208,0,0,135"
>
   <DataGrid.Columns>
       <DataGridTextColumn Header="VM-Name" Binding="{Binding Path=vmName}" MinWidth="80" IsReadOnly="True" />
       <DataGridTextColumn Header="Profile" Binding="{Binding Path=profileN}" MinWidth="100" IsReadOnly="True" />
   </DataGrid.Columns>
</DataGrid>

How I add items:
public class AddToGrid
{
   public string vmName   { get; set; }
   public string profileN { get; set; }
}

this.Dispatcher.Invoke(() =>
{
   var dat = new AddToGrid { vmName = clientSockets.Find(item => item.Item1 == current).Item2, profileN = profile.Item1 };
   AccountGrid.Items.Add( dat );
});

What I need to do is Delete a row from the grid, using the VM-Name, Thanks in advance!

A: *

*Rename your AddToGrid class to MyGridRow and move it to be a public type instead of a nested type.

*Add using System.Linq; and using System.Collections.ObjectModel; to your C# code-behind file.

*In your XAML code-behind, add this public property:
public ObservableCollection<MyGridRow> MyGridRows { get; } = new ObservableCollection<MyGridRow>();

*Change your XAML to this:
<DataGrid ItemsSource="{Binding MyGridRows}" ...>

</DataGrid>

*Change your code that adds items to this:
String vmName = clientSockets.Find( item => item.Item1 == current ).Item2;
String profile = profileN = profile.Item1;
this.MyGridRows.Add( new MyGridRow { VMName = vmName, ProfileN = profile } );

*To remove a row, do this:
MyGridRow itemToRemove = this.MyGridRows
    .FirstOrDefault( pair => pair.Item.VMName == "someName" )

if( itemToRemove != null )
{
    this.MyGridRows.Remove( itemToRemove );
}


text:
Q: Do I need to be concerned with timezones when creating events in my iCloud calendar? I live in California, and I need to enter over 20 events onto my calendar. These events are taking place on the east coast of the United States, which is where I will be during the events. How do I enter these events on my iPhone (to my iCloud calendar) so that the events list the correct times?
If I create an event beginning at 8pm and ending at 10pm for example, I do not want the event time to be shifted by three hours (going from PDT to EDT) when I travel. Since I am managing about 20 events on the calendar, it would be a hugely unpleasant task to update all of the events by hand.
For this example event going from 8pm to 10pm, do I:

*

*enter the event on my calendar as 8pm-10pm while in California

*enter the event on my calendar as 5pm-7pm (which would be the local time in California of an event 8pm-10pm on the east coast using daylight saving time)

*locate or change a setting on my iPhone that makes calendar events disregard timezones

*do something else?

A: If you have a number of events you want to enter and you have their times in another zone, it's very handy to use Calendar's time zone support.
First, go to Calendar->Preferences, and click Turn on time zone support.

This will enable a dropdown in the titlebar of your Calendar window:

You can then use this menu to change the display of everything in your calendar to a new time zone.  Pull it down and select Eastern time (or whatever other time zone or city your event is in), and Calendar will convert all your times to that zone.
At this point, you can start entering events, using the times listed in the program for the event.  You will also see a new detail in the event detail popup:

This shows what time zone the event is in.
Once you've entered all the events, turn the time zone back.  That will display all your events in your own time zone.  If you are syncing with your phone (which knows what time zone it is in) all the events will remind you at the right time.

A: Your calender knows the time zone you are in. I am east coast. If you want to get me on a conference call at noon your time, you send me an entry for just that, noon. My entry will be the correct time for me, 3PM.
To be clear, set the appt for the correct Cal time.


text:
Q: Click link on plugin/theme page and open the contextual help on a specific tab I've added a help section using the add_help_tab() function. I'd like to be able to click a link somewhere on the theme/plugin page and have the help panel open at whichever tab I need. Can someone help me out with the required JS for this?
Each tab panel has a unique hash link associated with it so I'd need to use this somehow I'm guessing
/themes.php?page=theme_options#tab-panel-general

A: Maybe the Q is bordering the off-topic, but IMO interesting in WordPress context.
I've tested this directly in FireBug, in the Dashboard page (wp-admin/index.php).
var $ =jQuery.noConflict();

// Remove 'active' class from all link tabs
$('li[id^="tab-link-"]').each(function(){
    $(this).removeClass('active');
});

// Hide all panels
$('div[id^="tab-panel-"]').each(function(){
    $(this).css('display','none');
});

// Set our desired link/panel
$('#tab-link-help-content').addClass('active');
$('#tab-panel-help-content').css('display','block');

// Force click on the Help tab
$('#contextual-help-link').click();


text:
Q: Media queries don't do anything I've been doing HTML and CSS with SASS for a while and all my responsive was working until today, suddenly my css media queries stopped reacting.
They are in the css file that is being loaded on the web page, but no elements react to them ... I can't copy a full css file of 3k lines to here..
But I think I'm missing something basic. I'm using gulp-sass and it reports no errors when processing the css.
I'm going nuts over this and I can't figure out the problem. Everything was working until today and I need to deliver a project till monday and I can't do the responsive.
All the queries were working. I didn't change anything today , when I ran the project the queries wouldn't do anything .
Any suggestions on what it may be ? Thanks guys.

A: Tests are usually your best bet. Make sure your media queries are at the bottom most of your prioritized CSS file - to ensure they aren't being overwritten. Regardless how many thousand lines your code is:
1) Comment out all your media queries
2) Run a test, for example:
@media screen and (max-width: 600px) {
    body {
      background-color: black;
    }
  }

3) Resize your browser to a width smaller than 600px, if your background colour changes to black, chances are nothing is wrong with your preprocessors and its time to debug your code.
4) Comment out your media queries one code block at a time until you discover the block that doesn't work.
5) Fix it. Relief


text:
Q: How to use Goutte Issue:
Cannot fully understand the Goutte web scraper.
Request:
Can someone please help me understand or provide code to help me better understand how to use Goutte the web scraper?  I have read over the README.md.  I am looking for more information than what that provides such as what options are available in Goutte and how to write those options or when you are looking at forms do you search for the name= or the id= of the form?
Webpage Layout attempting to be scraped:
Step 1:
The webpage has a form has a radio button to choose what kind of form to fill out (ie. Name or License).  It is defaulted to Name with First and Last Name textboxes along with a State drop down menu select list. If you choose Radio there is jQuery or JavaScript that makes the First and Last Name textboxes go away and a License Textbox appears.
Step 2:
Once you have successfully submitted the form then it brings you to a page that has multiple links.  We can go in to one of two of them to get our information we need.
Step 3:
Once we have successfully clicked on the link we want the third page has the data that we are looking for and we want to store that data into a php variable.
Submitting Incorrect information:
If wrong information is submitted then a jQuery/Javascript returns a message of
"No records were found." on the same page as the submission.
Note:
The preferred method would be to select the license radio button, fill in the license number, choose the state and then submit the form.  I have read tons of posts and blogs and other items about Goutte and nowhere can I find what options are available for Goutte, how you find out this information or how to use this information if it did exist.

A: The documentation you want to look at is the Symfony2 DomCrawler.
Goutte is a client build on top of Guzzle that returns Crawlers every time you request/submit something:
use Goutte\Client;
$client = new Client();
$crawler = $client->request('GET', 'http://www.symfony-project.org/');

With this crawler you can do stuff like get all the P tags inside the body:
$nodeValues = $crawler->filter('body > p')->each(function (Crawler $node, $i) {
    return $node->text();
});
print_r($nodeValues);

Fill and submit forms:
$form = $crawler->selectButton('sign in')->form();
$crawler = $client->submit($form, array(
        'username' => 'username',
        'password' => 'xxxxxx'
));

A selectButton() method is available on the Crawler which returns
  another Crawler that matches a button (input[type=submit],
  input[type=image], or a button) with the given text. [1]

You click on links or set options, select check-boxes and more, see Form and Link support.
To get data from the crawler use the html or text methods
echo $crawler->html();
echo $crawler->text();

A: After much trial and error I have discovered that there is a much easier, well documented, better assitance (if needed) and much more effective scraper than goutte.  If you are having issues with goutte try the following:

*

*Simple HTML Dom: http://simplehtmldom.sourceforge.net/
If you are in the same situation as I was where the page you are trying to scrape requires a referrer from their own website then you can use a combination of CURL and Simple HTML DOM because it does not appear that Simple HTML DOM has the ability to send a referrer.  If you do not need a referrer then you can use Simple HTML DOM to scrape the page.
$url="http://www.example.com/sub-page-needs-referer/";
$referer="http://www.example.com/";
$html=new simple_html_dom(); // Create a new object for SIMPLE HTML DOM
/** cURL Initialization  **/
$ch = curl_init($url);

/** Set the cURL options **/
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER,$referer);
$output = curl_exec($ch);

if($output === FALSE) {
  echo "cURL Error: ".curl_error($ch); // do something here if we couldn't scrape the page
}
else {
  $info = curl_getinfo($ch);
  echo "Took ".$info['total_time']." seconds for url: ".$info['url'];
  $html->load($output); // Transfer CURL to SIMPLE HTML DOM
}

/** Free up cURL **/
curl_close($ch);

// Do something with SIMPLE HTML DOM.  It is well documented and very easy to use.  They have a lot of examples.


text:
Q: Check if firebase has finished adding items to database I am sending data from my android app to a realtime firebase database.
I would like to check when firebase has finished adding these items into the database, as I will be calling a script on the server that will access the data in the database (through an asynctask).
But before I call the script, I need to make sure that firebase has finished adding all the items as to avoid any conflicts in the data. The code would be something like this:
myRef.child(userID).setValue(items); //add items to firebase database

new SendPostRequest().execute(); //call script on the server that will connect
                                    to firebase database and retrieve data.

I was wondering if the script would be called whilst firebase is adding data to the database therefore it would retrieve partial data, so I need to make sure that firebase has finished adding the items into the database first.

A: You can add a completion listener to setValue() to get notified when the call has completed.
See the section add a completion callback in the Firebase documentation for a full example.

mDatabase.child("users").child(userId).setValue(user)
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            // Write was successful!
            // ...
        }
    })
    ...


text:
Q: Python: Finding values after searching for a string in a text files I'm new to the world of python and I'm trying to extract values from multiple text files. I can open up the files fine with a loop, but I'm looking for a straight forward way to search for a string and then return the value after it.
My results text files look like this
SUMMARY OF RESULTS
Max tip rotation =,-18.1921,degrees
Min tip rotation =,-0.3258,degrees
Mean tip rotation =,-7.4164,degrees
Max tip displacement =,6.9956,mm
Min tip displacement =,0.7467,mm
Mean tip displacement = ,2.4321,mm
Max Tsai-Wu FC =,0.6850
Max Tsai-Hill FC =,0.6877

So I want to be able to search for say 'Max Tsai-Wu =,' and it return 0.6850
I want to be able to search for the string as the position of each variable might change at a later date.
Sorry for posting such an easy question, just can't seem to find a straight forward robust way of finding it.
Any help would be greatly appreciated!
Matt

A: You can make use of regex:
import re

regexp = re.compile(r'Max Tsai-Wu.*?([0-9.-]+)')
with open('input.txt') as f:
    for line in f:
        match = regexp.match(line)
        if match:
            print match.group(1)

prints:
0.6850

UPD: getting results into the list
import re

regexp = re.compile(r'Max Tsai-Wu.*?([0-9.-]+)')
result = []
with open('input.txt') as f:
    for line in f:
        match = regexp.match(line)
        if match:
            result.append(match.group(1))

A: My favorite way is to test if the line starts with the desired text:

keyword = 'Max Tsai-Wu'
if line.startswith(keyword):

And then split the line using the commas and return the value

try:
    return float(line.split(',')[1])
except ValueError:
    # treat the error

A: You can use regular expression to find both name and value:
import re

RE_VALUE = re.compile('(.*?)\s*=,(.*?),')

def test():
    line = 'Max tip rotation =,-18.1921,degrees'
    rx = RE_VALUE.search(line)
    if rx:
        print('[%s] value: [%s]' % (rx.group(1), rx.group(2)))

test()

This way reading file line by line you can fill some dictionary.
My regex uses fact that value is between commas.

A: If the files aren't that big, you could simply do:
import re
files = [list, of, files]
for f in files:
    with open(f) as myfile:
        print re.search(r'Max Tsai-Wu.*?=,(.+)', myfile.read()).group(1)


text: Q: how to make my fetch space your calls? I am making a movie search engine to an API. I have a Fetch that makes calls to the api with each search for a title, which has limited the requests to 6 per second. When I try to search for a movie with more than one result I get a warning saying that I have exceeded the number of requests per second. I would like to know how to make my Fetch make the calls intermittently, two per second, for example. That is to say, that it doses its calls in time.


text:
Q: Multicolumn issue with first item What am I seeing here? I do not mind the rest of the paragraphs do not line up, but the top ones must. What am I missing?
Browsers Fx 19 and Chrome 24 full screen on OSX Mountain Lion
NOTE: it goes away in a jsfiddle due to the normalised css that is inserted automatically
JSFIDDLE without normalised CSS

<!DOCTYPE html>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nulla lorem, tincidunt in pulvinar non

Suspendisse est odio, porttitor non semper porttitor, sagittis in enim. Aenean mollis elit dapibus

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

Etiam imperdiet suscipit odio, posuere ultrices diam porttitor nec. In tincidunt iaculis neque

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum porta consectetur sapien,

Donec tortor mauris, congue sit amet imperdiet sed, vehicula vel eros.

Curabitur porttitor mattis felis et placerat. Nulla facilisi. Curabitur varius imperdiet sapien,

in vulputate quam auctor id. In quis eros eget sapien dignissim porttitor.

 In hac habitasse platea dictumst. Nulla ut lorem sed felis blandit pretium.

 Donec eget turpis ac ante gravida aliquet at nec magna.

 Curabitur eleifend massa id sapien iaculis scelerisque.

Sed interdum, sapien ac laoreet tempus, orci turpis tristique sapien,

at ultrices dolor nulla eget dui. Vivamus sit amet turpis et erat vehicula tincidunt. Etiam a sodales neque.

A: The
 element has some top margin by default. Add a CSS rule to reset just the first paragraph like this:
p:first-of-type {
    margin-top:0;
}

A: I agree with Austin that p: first-of-type { margin-top:0; } fixes the issue.
My approach to troubleshooting this issue would have been to remove all p tags temporarily ... in other words filled all columns with just straight "Lorem ipsum" text without any p tags. When you do that top of all columns line up immediately ... so that way then you know for certain it was a p tag formatting issue.


text:
Q: Why is Image Capture showing two copies of every photo in my iPhone camera roll? I use Image Capture to import photos from my iPhone. I noticed recently that it shows two copies of every photo in the Image Capture window, both in list view and grid view.
There is only one copy of each photo in the iPhone camera roll, and when I drag them to a folder it only creates one copy of each. So it's not really causing a problem, but I'm curious why it is happening. I first noticed it in 10.10.1, and it continues in 10.10.2
See the screenshot below for an example. It is displaying two copies of IMG_6173.JPG and two copies of IMG_6172.JPG. There's only one copy of each in the camera roll. If I select all four and drag them to the desktop, it will create only one copy of each.

A: I just had this issue and found a solution on another site:
First, close Image Capture. Next, dismount the iPhone from the Mac by ejecting it with iTunes and unplug the cord from the iPhone. Then, just plug it back in and open up Image Capture again.
Worked for me - only one set of images.
Of course, this was after trying a couple other things... like turning off My Photo Stream (Settings>iCloud>iCloud>My Photo Stream: OFF) and turning off the "Keep Normal Photo" option (Settings>Photos & Camera>Keep Normal Photo: OFF), but I didn't notice any change immediately after doing these things  Only after unplugging and reconnecting the iPhone did the problem fix itself.  GOOD LUCK!

A: My first guess would be that you are using HDR
HDR will take 2 pictures, then 'meld' them together to give the best results.
Switch off 'Keep Normal Photo' in Settings > Photos & Camera


text:
Q: Count out object within mapStateToProps I have an object built as:
{
 id: // should be === to parentId
    0: {id: "", parentId: ""}
    1: {id: "", parentId: ""}
}

I somehow want to take this object and modify it within mapStateToProps
function mapStateToProps(state, ownProps) {
    const { id } = ownProps
    return {
        comments: state.comments

    }
}

So that comments: return the length of my object. Like state.comments.length but it ain't working properly

A: Objects generally don't have a length property.
You could count the number of entries in the object by first converting its keys to an array by doing Object.keys(state.comments).length.


text:
Q: Initializing BERT embeddings in a classification model I'm quite new to TensorFlow and trying to do a multitask classification with BERT (I have done this with GloVe in another part of the project). My problem is with the concept of placeholder in TensorFlow. I know that it is just a placeholder of some variables and will be filled. See this is the part of my classification model that I have problem with. I'll explain the exact problem down here.
def bert_emb_lookup(input_ids):
    # TODO to be implemented;
    """
    X is the input IDs, but a placeholder
    """
    pass

class BertClassificationModel(object):
    def __init__(self, num_class, args):
        self.embedding_size = args.embedding_size
        self.num_layers = args.num_layers
        self.num_hidden = args.num_hidden

        self.input_ids = tf.placeholder(tf.int32, [None, args.max_document_len])
        self.Y1 = tf.placeholder(tf.int32, [None])
        self.Y2 = tf.placeholder(tf.int32, [None])
        self.dropout = tf.placeholder(tf.float64, [])

        self.input_len = tf.reduce_sum(tf.sign(self.input_ids), 1)

        with tf.name_scope("embedding"):
            self.input_emb = bert_emb_lookup(self.)
...

It was easy to get the word embeddings from GloVe; I first loaded the glove vectors and then simply used tf.nn.embedding_lookup(embeddings, self.input_ids) to fetch the embeddings.
So in BERT classification model, I'm trying to do something similar by defining a function whose argument is input_ids, where I want to match input ids with their associated vocab (string). Thereafter, I'll use an API (BERT as a service) that gives BERT embeddings of any given list of strings at string-level/token-level. The problem is that since self.input_ids is just a placeholder, it shows it a NULL object. Is there any workaround that helps me with this?
Thanks!

A: You cannot use bert-as-service as a tensor directly. So you have two options:

*

*Use bert-as-service to look up the embeddings. You give the sentences as input and get a numpy array of embeddings as ouput. You then feed the numpy array of embeddings to a placeholder self.embeddings = tf.placeholder(tf.float32, [None, 768])
Then you use self.embeddings wherever you would have used tf.nn.embedding_lookup(embeddings, self.input_ids).

*The other option is probably overkill in this case, but it may give you some context. Here you do not use bert-as-service to get embeddings. Instead, you use the bert model graph directly. You would use BertModel from https://github.com/google-research/bert/blob/master/run_classifier.py to create a tensor which again can be used wherever you would use tf.nn.embedding_lookup(embeddings, self.input_ids).


text:
Q: Entity Framework 4.0 changes in NopCommerce 1.90 For learning EF, I was after a good example and I reached NopCommerce via google. I loved their implementation of EF and it's architecture in version 1.80.
I was very impressed with the Entity Framework Architecture in version 1.80. I liked the way of creating AspNetObjectContextManager and accessing the same objectContext for the request.
But now when I downloaded nopcommerce 1.90, I see all the classes AspNetOCM, ObjectContextHelper, ObjectContextManager, etc.. are removed and context is added to the Service classes (e.g. CustomerService).
Can I please know the reason behind it and if there are any shortcoming in the version 1.80's Entity Framework Architecture.
The reason I am concerned is that I don't want to learn the architecture with some shortcomings. I know NopCommerce development team have always maintained high level of quality in their coding, but I would love to know the reason behind removing the classes from version 1.90

A: I think this change relates to introduction of IoC/DI (inversion of control / dependency injection) pattern in 1.90.
This pattern enables you to set a service interface implementation (e.g. MyCustomerService for ICustomerService) in a config file, which contributes to loose coupling between client and service implementation(s).
However I've never tried NopCommerce 1.80, so can't tell what were the disadvantages of its architecture.


text:
Q: Why jquery defined two methods for the same purpose? size and length After reading this SE Discussion a question pops up. Why jquery defined two methods for the same purpose? Is there any purpose I missed?
Don't know this belongs to a wiki discussion. If so please guide me to change this so.

A: length is a property inherit from javascript
size() is a method

A: I would guess someone just didn't think it through, unless perhaps the earliest versions had some reason. I could only find source back to 1.2.6, and it is unchanged from the current version.
EDIT: It seems to have been unchanged since version 1.0.1.
The documentation for .size() suggests that it should not be used.

You should use the .length property instead, which is slightly faster.

A: size returns length. Length is a bit faster.

A: "most likely implemented to abstract away from the possibility of the length property being changed"


text:
Q: XMPPFramework - How to Add Users to MUC Room I am creating group chat app. I am able to create the group with below code.
_xmppRoomStorage = [[XMPPRoomCoreDataStorage alloc]init];
   XMPPJID *roomJID = [XMPPJID jidWithString:@"room1@conference.abc.biz"];
   _xmppRoom =[[XMPPRoom alloc] initWithRoomStorage:_xmppRoomStorage jid:roomJID];
   [_xmppRoom              activate:_xmppStream];
   [_xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
   xmppRoom joinRoomUsingNickname:_userNameEdit.text history:nil];

but now I need to add some users to this group. Can any one please let me know how to add or invite multiple users to this group.
I have one more problem. not able to create 2nd room when 1st group is active. When I try to create 2nd room it gives below error
"XMPPRoom[room2@conference.abc.biz] - Cannot create/join room when already creating/joining/joined"
Thanks.
Vaz

A: I fixed this issue by doing as follows:

*

*Create the room first
-(void) CreateRoom
{
    XMPPJID *roomRealJid = [XMPPJID jidWithString:jidRoom];// Room name ex. abc@conference.xyz.biz
    XMPPRoom *newXmppRoom = [[XMPPRoom alloc] initWithRoomStorage:[[self appDelegate] xmppRoomStorage] jid:roomRealJid    dispatchQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)];
    [newXmppRoom activate: [[self appDelegate] xmppStream]];
    [newXmppRoom fetchConfigurationForm];
    [newXmppRoom addDelegate:[self appDelegate] delegateQueue:dispatch_get_main_queue()];
    [newXmppRoom joinRoomUsingNickname:nickName history:nil password:[[NSUserDefaults     standardUserDefaults] stringForKey:kXMPPmyPassword]];
}

*Send invitations
// Once the room created, we get some responses from server.
// One of them is "didFetchModeratorsList".

- (void)xmppRoom:(XMPPRoom *)sender didFetchModeratorsList:(NSArray *)items
{
    DDLogInfo(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);

    if (check the flag for room create and invite) // This has to be done only when we intended
    {
        NSArray* users = list of users we need to invite.

        if (users.count > 0)
        {
            for (int i=0; i< users.count; i++)
            {
                NSString *jid = [NSString stringWithFormat:@"%@@xyz.biz", [users objectAtIndex:i]];
                XMPPJID *xmppJID=[XMPPJID jidWithString:jid];
                [sender inviteUser:xmppJID withMessage:@"Join Group."];
            }
            [sender sendMessageWithBody:@"Hi All"];
        }
    }
}

Hope this helps.


text:
Q: Laravel Backpack table field columns (json-array) validation rules not working I'm using BackpackForLaravel and I have a table type field in my code:
$this->crud->addField([
    'label'           => 'Contact persons',
    'name'            => 'contact',
    'type'            => 'table',
    'entity_singular' => 'contact',
    'columns'         => [
        'person' => 'Person',
        'email'  => 'Email',
        'number' => 'Phone number',
        'desc'   => 'Description',
    ],
    'attributes'        => [
        'required' => true
    ],
    'max'               => 5,
    'min'               => 1,
    'wrapper'           => [
        'class' => 'form-group col-12'
    ],
    'tab' => 'Contact data',
]);

The CRUD work fine, but when I add validation, something is not working properly.
My ClientRequest.php class has:
public function rules()
    {
        return [
            'cif'                            => "required|spanish_tax_number|unique:clients,cif,{$this->cif},cif",
            'name'                           => 'required|min:3|max:255',
            'address'                        => 'required|json',
            'weekly_rest'                    => 'nullable|array',
            'description'                    => 'nullable|max:255',
            'leaving_date'                   => 'nullable|date',
            'leaving_date'                   => 'nullable|date',
            'image'                          => 'nullable|image|mimes:jpeg,png',
            'contact'                        => 'required|array',
            'contact.*.person'               => 'required|email'
        ];
    }

contact field validation works well, but when I tried to use contact.*.person to validate all array fields named person, nothing happens.
I used the function prepareForValidation to modify field json format to array format:
protected function prepareForValidation()
    {
        $this->merge([
            'contact' => json_decode($this->input('contact'))
        ]);
    }

If I dump input data, I can view that function prepareForValidation is working well, but the validation isn't doing nothing.
I read about array validation here:

*

*https://github.com/Laravel-Backpack/CRUD/issues/1582

*https://laravel.com/docs/7.x/validation#validating-arrays
I do this, and works (do the validation in store/update controller function):

*

*https://github.com/Laravel-Backpack/CRUD/issues/607#issuecomment-293729520
But, I would like to do this without this vervosity, coding all in ClientRequest class.
I think that I'm doing well, but not works.
What am I doing wrong in ClientRequest?

EDIT
Output of request()->all() inside rules(), function of ClientRequest.php
array:15 [▼
  "_token" => "DGnGIZwertI6kupXwYgHr8as5MVbD2sPRlmbGJrK"
  "_method" => "PUT"
  "http_referrer" => "http://127.0.0.1:8000/admin/client?active=1"
  "id" => "21"
  "cif" => "123456789F"
  "name" => "Paco Porras SL"
  "address" => "Useful address, 1"
  "weekly_rest" => array:3 [▼
    0 => "2"
    1 => "3"
    2 => "4"
  ]
  "description" => "qweqwe"
  "discharge_date" => "2020-07-08"
  "leaving_date" => null
  "image" => null
  "contact" => "[{"person":"123123123","email":"sss.ssstyytrytr","number":"qwewqe","desc":"qweq"},{"person":"123123123","email":"123123","number":"123123","desc":"123213"}]"
  "current_tab" => "datos-de-empresa"
  "save_action" => "save_and_edit"
]

Output after prepareForValidation:
array:15 [▼
  "_token" => "DGnGIZwertI6kupXwYgHr8as5MVbD2sPRlmbGJrK"
  "_method" => "PUT"
  "http_referrer" => "http://127.0.0.1:8000/admin/client?active=1"
  "id" => "21"
  "cif" => "123456789F"
  "name" => "Paco Porras SL"
  "address" => "Useful address, 1"
  "weekly_rest" => array:3 [▼
    0 => "2"
    1 => "3"
    2 => "4"
  ]
  "description" => "qweqwe"
  "discharge_date" => "2020-07-08"
  "leaving_date" => null
  "image" => null
  "contact" => array:2 [▼
    0 => {#1557 ▼
      +"person": "123123123"
      +"email": "sss.ssstyytrytr"
      +"number": "qwewqe"
      +"desc": "qweq"
    }
    1 => {#1556 ▼
      +"person": "123123123"
      +"email": "123123"
      +"number": "123123"
      +"desc": "123213"
    }
  ]
  "current_tab" => "datos-de-empresa"
  "save_action" => "save_and_edit"
]

EDIT 2
I do this in store/update function of ClientController.php:
$validate = Validator::make($request->all(), [
            'contact'                          => 'required|array',
            'contact.person'                   => 'required|string',
            "contact.*.person"                 => 'required|string',
        ]);

dd($validate->messages());

And the output is:
Illuminate\Support\MessageBag {#1520 ▼
  #messages: array:2 [▼
    "contact" => array:1 [▼
      0 => "El campo contact debe ser un array."
    ]
    "contact.person" => array:1 [▼
      0 => "El campo contact.person es obligatorio."
    ]
  ]
  #format: ":message"
}

Something isn't working well because 'contact.*.person' is missing.

A: change
'contact' => json_decode($this->input('contact'))

on
'contact' => json_decode($this->input('contact'), true)

and leave your old rules


text:
Q: Get the CamelContext for standalone Apache Camel instance I'm using the Main class from Apache Camel to run it as standalone.
I need to use the JMS component so I have to add it to the CamelContext instance used by the Main class.
Of course I need to do that before calling main.run(args) method.
The problem is the following ...
Using main.getCamelContexts().get(0) returns an index out of bounds exception.
Using main.getOrCreateCamelContext() returns a valid CamelContext instance named "camel-1" to which I'm able to add my JMS component but .... when I execute main.run(args), another CamelContext named "camel-2" is used !
The only way I found to add my JMS component is to use :
main.bind("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
Is this the only way or the CamelContext way should work ?
Thanks,
Paolo.

A: You can provide completely own camel context to be used. To achieve that you can inherit org.apache.camel.main.Main and override only one method
protected Map<String, CamelContext> getCamelContextMap()

Here is the example of inherited body:
@Override
protected Map<String, CamelContext> getCamelContextMap() {
    Map<String, CamelContext> camelContextMap = new HashMap<>();
    DefaultCamelContext camelContext = new DefaultCamelContext();
    camelContext.setName("MyContext");

    // Add your context configuration here

    camelContextMap.put("connectorContext", camelContext);
    return camelContextMap;
}

In general it is better to create context map not in the "getCamelContextMap()" inherited method but somewhere in the constructor.

A: Old Question, but was able to figure it out - tried with camel 2.17.x version
private void runMyExample() {
    //Add a Main Listener
    main.addMainListener(new MyMainListener);
    main.run();
}

public static class MyMainListener extends MainListenerSupport {
    @Override
    public void afterStart(MainSupport main) {
        System.out.println("MainExample with Camel is now started!");

        //This is the right instance
        CamelContext context = main.getCamelContexts().get(0);
    }

    @Override
    public void beforeStop(MainSupport main) {
        System.out.println("MainExample with Camel is now being stopped!");
    }
}

Regards,
R.


text:
Q: Changing attribute dropdown to radio buttons I was wondering if there was any way to change the attribute display from dropdown list to radio buttons.
I know that there are extension doing this but they are very expensive for a simple feature like this that for my opinion Magento should implement itself without any extensions.
Is there any simple way to achieve that ?

A: If you are talking about the Dropdown options on a Configurable etc product then you can use this:
http://inchoo.net/magento/configurable-product-modification-in-magento/

A: It is not that easy, because a lot of JS is involved.
Magento renders the select fields one by one, after you chose an option, so you get only them for choice, which are available.
And yes, you can do this, by just reimplementing the JS and changing the templates.
I think you want to start here:
app/design/frontend/base/default/template/catalog/product/view/type/options/configurable.phtml
app/design/frontend/base/default/template/catalog/product/view/options.phtml

A: I recommend you this extension, it has what you are looking for and much more. You can add images for the buttons and change image depending on the attribute selected.


text:
Q: react-router-redux webpack dev server historyApiFallback fails After enabling historyApiFallback in the webpack config file and restarting the server, when changing location pathname, the browser refreshes, causing outer elements to re-mount (what I mean is that, I can see it flash white and back to normal) where this should only happen for nested the.props.children.
In my particular case, there's a <Navbar /> element that is always present at the top and a container that has the { this.props.children }. I wonder what's going on?
App entrypoint:
import React from 'react';
import ReactDOM from "react-dom";
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import { syncHistoryWithStore } from 'react-router-redux'
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import promise from 'redux-promise';
import reducers from './reducers';
import thunk from 'redux-thunk';

// const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
// const store = createStoreWithMiddleware(reducers);
const store = createStore(
    reducers,
    applyMiddleware(thunk)
);
const history = syncHistoryWithStore(browserHistory, store);

ReactDOM.render(
    <Provider store={ store }>
        <Router history={ history } routes={ routes } />
    </Provider>,
    document.getElementById('app')
);

webpack config file:
var path = require("path");
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    historyApiFallback: true,
    entry: [
        'webpack-dev-server/client?http://localhost:3000',
        'webpack/hot/dev-server',
        './src/js/index.js'
    ],
    output: {
        path: __dirname + '/static',
        filename: "index_bundle.js"
    },
    module: {
        loaders: [
            { test: /\.js$/, exclude: /node_modules/, loaders: ["react-hot-loader", "babel-loader"] },
            { test: /\.scss$/, loader: 'style!css!sass' },
            { test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, loader: 'file-loader' }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            inject: true,
            template: __dirname + '/src/' + 'index.html',
            filename: 'index.html'
        }),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ],
    resolve: {
        root: path.resolve(__dirname),
        extensions: ['', '.js'],
        alias: {
            "TweenLite": "src/libs/gsap/TweenLite",
            "CSSPlugin": "src/libs/gsap/plugins/CSSPlugin"
        }
    }
};

main wrapper/container:
import React, { Component } from 'react';
import Navbar from '../containers/navbar';
import ModalWindow from '../components/modalWindow';

// include the stylesheet entry point
require('../../sass/app.scss');

class App extends Component {
    render() {
        return (

                <Navbar />

                { this.props.children }

                <ModalWindow />

        );
    }
}

export default App;

router config file:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/app';
import InitialScreen from './containers/initialScreen';
import Reservation from './containers/reservation';

const routes = (
    <Route path='/' component={ App }>
        <IndexRoute component={ InitialScreen } />
        <Route path='your-trolley' component={ Reservation } />
    </Route>
);

export default routes;

So far, I think there's something wrong in the webpack dev config file.
Update
Random user asked how the location is changed, so here's the action:
export function fetchReservationData(reservation_code, onError) {

    return (dispatch) => {
        fetch(apiConfig.find_my_product)
            .then(function(response) {

                if (response.ok) {

                    response.json().then(function (data) {
                        if (data.trolley.length > 0) {
                            dispatch({ type: UPDATE_TROLLEY_DATA, payload: data });
                            // todo: use router-redux push instead
                            window.location.pathname = '/your-trolley';

                        } else {
                            dispatch({ type: TOGGLE_MODAL_WINDOW, payload: onError });
                        }
                    });

                } else {

                    // todo: handle exception
                    console.log('Network response was not ok.');
                    dispatch({ type: TOGGLE_MODAL_WINDOW, payload: onError });

                }

            })
            .catch(function (error) {

                // todo: handle error
                // handle it gracefully asked user to try again, if the problem keeps ocurring to
                // talk with a staff member to report it to the backend team
                console.log('There has been a problem with your fetch operation: ' + error.message);
                dispatch({ type: TOGGLE_MODAL_WINDOW, payload: onError });

            });
    }

}

Here's where the problem is; If I change the app entry point it works:
import React from 'react';
import ReactDOM from "react-dom";
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import { syncHistoryWithStore, routerMiddleware, push } from 'react-router-redux'
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import promise from 'redux-promise';
import reducers from './reducers';
import thunk from 'redux-thunk';

// const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
// const store = createStoreWithMiddleware(reducers);
const store = createStore(
    reducers,
    applyMiddleware(thunk),
    applyMiddleware(routerMiddleware(browserHistory))
);
const history = syncHistoryWithStore(browserHistory, store);

setTimeout(() => {
    store.dispatch(push('/your-trolley'));
}, 3000);

ReactDOM.render(
    <Provider store={ store }>
        <Router history={ history } routes={ routes } />
    </Provider>,
    document.getElementById('app')
);

So now I'll need to be able to dispatch the push from the action as I did in the entry point. It's a bit confusing because I'm pasing a middleware to the store and then the store is sync with the browserhistory, I guess I'll need to pass the return value from applyMiddleware(routerMiddleware(browserHistory)) in both cases (createstore and sunchistorywithstore)?

A: Since you're using react-router and don't want the browser to reload the entire page everytime you switch to new url, It's important to use the <Link> component provided by react-router or create your own version of the component.
To link between different pages you can
import { Link } from 'react-router';

And then you it in your render function, use it like
<Link to="/user/profile">Goto Profile Page</Link>
<Link to="/">Homepage</Link>

And if you want to programmatically redirect user to different url/location
import { browserHistory } from 'react-router';

let doSomething = () => {
  // do something
  browserHistory.push('/user/profile');
}

Edit: If you want to Redirect using push method provided by react-router-redux, You can do something like this
// import push from react-router-redux
import { push } from 'react-router-redux';

// when props.redirect is called, dispatch the push method
const mapDispatchToProps = ( dispatch, ownProps ) => {
  return {
    goto: (path) => dispatch( push(path) ),
  }
}

let Component = (props) => {

  // when called, this will call goto on props which inturn will dispatch the `push` method.
  let gotoNewPage = () => {
    props.goto('/some/page');
  }

  return (

Hello World

      <button onClick={ gotoNewPage }>Goto New Page</button>

  );

}


text:
Q: Installing gRPC for localhost I'm working with PHP library of Google Cloud Firestore, it requires me to install and enable the gRPC extension.. I've read the guide which says

Windows users can download and enable DLLs from PECL. Support for
  Windows is experimental

In the PECL site I can see many links to tgz and DLL files but without any explanation of how to use or activate them in the XAMPP as a localhost

A: I would like to add answer for 7.4.4 PHP Version,
I downloaded php_grpc-1.27.0-7.4-ts-vc15-x64.zip from this link https://windows.php.net/downloads/pecl/releases/grpc/1.27.0/
Then I copied pasted php_grpc.dll to C:\xampp\php\ext folder
In next step I opened php.ini under Dynamic extentions added extension=grpc
And then restarted and it was working fine.

A: With the help of this link.. I found that these steps will activate gRPC

*

*From PECL site (or windows.php.net which has the exact same files) .. choose DLL of the latest stable release

*According to the PHP version you have :

*

*For XAMPP with PHP > 7.2.15 .. choose Thread Safe (TS) x64

*For older XAMPP .. choose Thread Safe (TS) x86

*Download the ZIP file then extract its contents

*Copy the php_grpc.dll file to the extensions folder in XAMPP (you can find the path in php.ini) .. in my case it was extension_dir="C:\xampp\php\ext"

*Enable the extension in your php.ini file :

*

*For PHP version 7.2 and up .. add extension=grpc

*For older PHP .. add extension=php_grpc.dll

*Restart XAMPP and the extension will be activated as showed in phpinfo()

A: Windows 10 | PHP 7.1
I tried to debug this for 4 hours and could not find the right solution. I later on realized that besides the grpc extension, there were some other extensions also like oci which threw the same error when I tried to uncomment those (while keeping grpc commented) and running any php command like php --ini
On some other forum I read that a user had to manually install PHP using windows installer and then install DLL. I thought I'll try that but I could not find an MSI so I downloaded the latest PHP zip installer from https://windows.php.net/download/ I chose the x64 version for php 7.1.
Please note that I did not install this downloaded PHP but I noticed it had a php7.dll
I had used dependency walker from http://www.dependencywalker.com/ to check the dependencies of the php_grpc.dll and found php7.dll as a dependency.
So what I did was to copy both PHP7.dll and php_grpc.dll to system32 and then I tried to install that DLL. I ran a command prompt as Admin and navigated to C:\windows\system32 and executed the command regsvr32 php_grpc.dll (Please note that this does not work without PHP7.dll being present in the same folder - or at least it did not work for me). Upon execution, I got a message that the DLL was loaded but entry point was not found. At this time when I executed php --ini again (I also had php_grpc.dll loaded to ext folder under the XAMPP php folder) I got a new error finally which said that the module being loaded was Non thread safe (NTS) whereas PHP was TS (Thread Safe). So I went to PECL, downloaded the TS version of the grpc plugin for PHP7.1 and pasted the dll file to both system32 and also the ext folder. I ran the regsvr32 /U php_grpc.dll command which uninstalls and reinstalls the DLL i believe (I am not sure if this step made any difference but I am mentioning it here because I had performed this step before calling php --ini)
After this, finally php --ini ran  without any issues. I was able to use the composer command to successfully download the dependencies for cloud-firestore. It was a waste of 4 precious hours but I hope this helps someone else.
NOTE: Instead of downloading from PECL, I downloaded the grpc zip from https://windows.php.net/downloads/pecl/releases/grpc/
I don't know if this is different but it was the link mentioned on the installation site for Windows installation of PHP. Also someone else has that link here. I took the latest build which was 1.24.0 at the time of this post. And I chose the Thread Safe Version.
The reason I chose the thread safe version is because of the error that I received of version mismatch. You can also check your version by executing "php -i" in console which returns same info as phpinfo(); Copy and paste the output in some text editor and search for PHP Extension Build. below is what I saw
PHP Extension Build => API20160303,TS,VC14
Note, it is TS aka thread safe. So unlike other posts on the internet where folks downloaded non thread safe version of grpc, I downloaded threadsafe and it worked.

A: Please download grpc extension zip from here
https://windows.php.net/downloads/pecl/releases/grpc/1.10.0/
accorging to your php version (My PHP version is 7.2.6 and x86 architecture xampp) I downloaded php_grpc-1.10.0-7.2-ts-vc15-x86.zip
after downloading extract zip file copy php_grpc.dll in e.g C:\xampp\php\ext folder
open php.ini under Dynamic extentions add extension=grpc
restart your apache server for checking open up cmd and type php -m it will show you all the extension enabled.

A: For windows modern Xampp have as syntax in php.ini
extension=php_grpc
no need .dll as extension in trail

A: My PHP version is 7.2.
I downloaded and uploaded php_grpc.dll inside my xampp/php/ext/php_grpc.dll and added a code in php.init, extension=grpc (on latest version you don't need to add php_ and .dll), then I restart Xampp
Now terminal says

PHP Warning:  PHP Startup: Unable to load dynamic library 'grpc' (tried: E:\xampp\php\ext\grpc (The specified module could not be found.), E:\xampp\php\ext\php_grpc.dll (The specified module could not be found.)) in Unknown on line 0
Your requirements could not be resolved to an installable set of packages.
Problem 1
      - google/cloud-firestore v1.6.2 requires ext-grpc * -> the requested PHP extension grpc is missing from your system.
      - google/cloud-firestore v1.6.1 requires ext-grpc * -> the requested PHP extension grpc is missing from your system.
      - google/cloud-firestore v1.6.0 requires ext-grpc * -> the requested PHP extension grpc is missing from your system.
      - Installation request for google/cloud-firestore ^1.6 -> satisfiable by google/cloud-firestore[v1.6.0, v1.6.1, v1.6.2].
To enable extensions, verify that they are enabled in your .ini files:
      - E:\xampp\php\php.ini
    You can also run php --ini inside terminal to see which files are used by PHP in CLI mode.
Installation failed, reverting ./composer.json to its original content.


text:
Q: how to use array as function variable in bash I want to pass an array parameter to a function in bash, and writing some testing code as:
 #!/bin/sh

    function foo {
       a=$1;
       for i in ${a[@]} ; do
          echo $i
       done
    }
    names=(jim jerry jeff)
    foo ${names[@]}

the above code just show jim, rather than the three j*. so my question is:

*

*why my code doesn't work

*what's the right way to do it

A: #!/bin/bash
function foo {
a=($*)
for i in ${a[@]}
do
    echo $i
done
}

names=(jim jerry jeff)
foo ${names[@]}

Your code did not show jim to me, but "names", literally. You have to pass the whole array. And you have to recapture it with a=$($).
The manpage part in bash about Arrays is rather long. I only cite one sentence:

Referencing an  array  variable  without a subscript is equivalent to referencing the array with a subscript of 0.

A: You're fairly close; the biggest problem was the command a=$1, which assigns only the first parameter ($1) to a, while you want to assign the entire list of parameters ($@), and assign it as an array rather than as a string.  Other things I corrected: you should use double-quotes around variables whenever you use them to avoid confusion with special characters (e.g. spaces); and start the script with #!/bin/bash, since arrays are a bash extension, not always available in a brand-X shell.
#!/bin/bash

function foo {
    a=("$@")
    for i in "${a[@]}" ; do
        echo "$i"
    done
}

names=(jim jerry jeff "jim bob")
foo "${names[@]}"

A: For example like this:
my_array[0]="jim"
my_array[1]="jerry"

function foo
{
    #get the size of the array
    n=${#my_array[*]}
    for (( Idx = 0; Idx < $n; ++Idx  )); do
            echo "${my_array[$Idx]}"
    done
}


text:
Q: How to uplode a song in my laravel project I want to make a sound on my welcome page!! i don't know where i put the mp3 file in my project neither how to call it.
 i have created a folder under public named sounds where i put my .mp3 file and did this in blade page
<embed height="60" type="audio/midi" width="144" src="sounds/kism.mp3" volume="60" loop="false" autostart="true" />

A: You can use html5 to embed an audio source like this:
<audio controls preload="auto" autoplay="true">
    <source src="/sounds/kism.mp3" />
    This text displays if the audio tag isn't supported.
</audio>


text:
Q: Creating directory in Joomla What would be the easiest way to go about creating a directory based in Joomla similar to craigslist?
Thanks

A: You could have a look at this component http://www.mosets.com/tree/


text:
Q: Indexing, Strings, Lists Go through the list of fruits and print each one in the string "I added this  to our produce". The parameter is "a list of crop names (strings) and there is no return value.
Test Case
crops = ['apple', 'orange', 'banana', 'strawberry']
daysWork(crops)

I added this apple to our produce
I added this orange to our produce
I added this banana to our produce
I added this strawberry to our produce

My Code:
def daysWork(crops):
  for crop in crops:
    produce = crops[n]
  print 'I added this ' + str(produce) + ' to our produce'

The error I get is "The error was:n Name not found globally."
Is n not indexing the list at each element?

A: Python's for loop statement is actually a for-each statement, which differs from what you're used to in C or Java. for crop in crops references each element in crops with the variable crop.
What you want instead is:
for crop in crops:
    produce = crop


text:
Q: Earth's surface area
Here we are trying to calculate the earth's surface area via geodetic coordinates:
  \begin{align}
x&=(R\,p(\lambda)+h)\sin\lambda\,\cos\phi\\
y&=(R\,p(\lambda)+h)\sin\lambda\,\sin\phi\\
z&=[(1-e^2)R\,p(\lambda)+h]\cos\lambda
\end{align}
  where
  $$p(\lambda)=\frac 1 {\sqrt{1-e^2\cos ^2 \lambda}}$$
We first compute the flat metric $ds^2$ in these coordinates:
$$ds^2=dh^2+{[h+(1-e^2)R\,p^3]}^2 d\lambda ^2+{\sin^2\!\lambda\,(h+Rp)^2 d\phi^2}$$
Then we compute induced metric on the surface by putting $h=0$
$$ds_*^2=R^2p^2[(1-e^2)^2p^4 d\lambda ^2+\sin ^2\!\lambda\,d\phi ^2]$$
where the determinant of this metric is $g_*=R^4p^8(1-e^2)^2\sin ^2\lambda$
We found that
  \begin{align}
A&=\int\sqrt{g_*}\,d\phi\,d\lambda\\&=2\pi R^2(1-e^2) \left[\frac{1}{1-e^2}+\frac{\tanh^{-1}\!e}{e}\right]\\&=2\pi R^2\left[1+ \left(\frac{1}{e}-e\right)\tanh^{-1}\!e\right]\end{align}
$$e=0 \implies A=4\pi R ^2$$ and $$e\approx 0 \implies A\approx 4\pi R ^2 - \frac 4 3 \pi R^2 e^2 + O(e^4),$$

So from here, how do we get that for the Earth:
$$A_\text {ellipsoid}=5.10\times 10^8 \mathrm{km}^2$$ and $$A_\text{sphere}=5.12\times 10^8 \mathrm{km}^2$$
Plugging $e=0.0791$, $R_S=6380 $ into the formula I get $A_{sphere}=510439776.2$ instead of $5.12\times 10^8 km^2$
Similarly, plugging $e=0.0791$, $R_E=6360 $ into the formula I get $A_{ellipsoid}=507244542.9$ instead of $5.10\times 10^8 km^2$


text:
Q: How to find Longest path in graph I have one problem with my solution for finding longest path in graph. My Programm works very slow when vertices are close to each other. Here is my code please help me.

Test class

public class GraphTest : MonoBehaviour {

// Use this for initialization
void Start () {

    const int w = 5;
    const int h = 4;

    int[,] data = new int[h,w]{
        {0,0,0,1,0},
        {0,0,0,1,0},
        {0,0,1,1,0},
        {0,0,0,0,0}};

    Map map = new Map(data,w,h);

    List<Node> longest = map.longestPath();
    Debug.Log("LONGEST " + longest.Count);

    //INFO this doing for printing array with steps
    int c = longest.Count-1;
    foreach(Node n in longest)
        data[n.r,n.c] = c--;

    string st = "";
    for(int i = 0; i < h; i++ )
    {
        for(int j = 0; j < w; j++)
        {
            st += data[i,j] + ",";
        }
        st += "\n";
    }

    Debug.Log(st);
}
}

Node class

public class Node
{
public int r,c;
public int data;
public Node[] neighbors;

public Node(int r, int c, int data)
{
    this.r = r;
    this.c = c;
    this.data = data;
    neighbors = new Node[8];
}
}

Map class for finding paths

public class Map
{
public static int[] xDir = {1,1,1,0,-1,-1,-1,0};
public static int[] yDir = {-1,0,1,1,1,0,-1,-1};

public Node[,] map;
public int[,] mapData;

private int width,height;
private int[,] marks;
public Map(int[,] mapData,int width,int height)
{
    this.mapData = mapData;
    this.width = width;
    this.height = height;

    createNodes();
    initNeighbors();
}
//INFO create nodes
private void createNodes()
{
    map = new Node[height,width];
    for(int i = 0; i < height; i++ )
    {
        for(int j = 0; j < width; j++)
        {
            map[i,j] = new Node(i,j,mapData[i,j]);
        }
    }
}
//INFO assign neighbor nodes
private void initNeighbors()
{
    for(int i = 0; i < height; i++ )
    {
        for(int j = 0; j < width; j++)
        {
            for(int k = 0; k < 8; k++)
            {
                if(inRange(i+yDir[k],j+xDir[k]))
                {
                    map[i,j].neighbors[k] = map[i+yDir[k],j+xDir[k]];
                }
            }
        }
    }
}

private bool inRange(int r, int c)
{
    return r < height && r >= 0 && c < width && c >= 0;
}

public List<Node> longestPath()
{
    marks = new int[height,width];
    List<Node> nodes = new List<Node>();
    int c = dfs(map[0,0],nodes);

    //INFO Iterasions count
    Debug.Log("COUNT " + c);
    return nodes;
}

private int dfs(Node node, List<Node> nodes)
{
    int i = 1;
    List<Node> longest = new List<Node>();
    List<Node> list = null;
    marks[node.r,node.c] = 1;

    for(int n = 0; n < 8; n++)
    {
        //INFO if the neighbor node is not null and same type with parent node do dfs for neighbor node
        if(node.neighbors[n] != null &&
           marks[node.neighbors[n].r,node.neighbors[n].c] == 0 &&
           node.neighbors[n].data == node.data)
        {
            list = new List<Node>();
            i += dfs(node.neighbors[n],list);
           //INFO if the found nodes count is more than previous nodes count set new nodes to best nodes
            if(list.Count > longest.Count)
                longest = list;
        }
    }

    marks[node.r,node.c] = 0;
    longest.Add(node);
    nodes.AddRange(longest);

    return i;
}
}

A: As brz mentioned, this is an NP-complete problem; you won't be able to find a solution that is both efficient and guaranteed optimal. (Or, if you do, every programmer in the world will buy you a beer.)
That's not to say you can't do anything about it. Concentrate on the general shape of your particular use case, and any peculiarities, and decide how much inaccuracy you're willing to deal with.
The first thing you can do is look for a bottleneck -- a pair of adjacent traversable cells such that there is no path between them other than the direct one, and the start and goal nodes are on opposite sides of the pair. For the grid case, you can look at the cells which have exactly two neighbors, and then check for bottlenecks against those two neighbors. If you find a bottleneck, congratulations -- you've cut your problem into two subproblems, each of which will be much faster to solve.
You can also try randomized approaches, such as simulated annealing. Start with the shortest path, then perform some simple localized perturbation on it to make it longer, such as changing a straight line into a C-shape if the two nodes to one side of a part of the path are both unused by the path. Keep doing that until you can't make it any longer, then pick two nodes from your path at random, replace the path between them with the shortest path, re-elongate it, and consider taking that as the new path.
Ultimately, you need to remember that this is not a problem you can solve in its most theoretical, general form. You can concentrate on special cases, and you can relax your requirement of exact optimality. Theoretical CS has abandoned you; you need to turn to practical engineering instead.


text:
Q: Is it possible to extract node locations from a STL file? I have 3D scanned wheel geometries of deformed tyres in an STL file format, and I would like to be able to do geometric analysis on them. One way I am familiar with is using the node locations to extract the information I am looking for.
I however cannot find a way to do this. If there is a program which can be used to analyse the geometry of STL files that would also be useful.