text:
Q: ¿Por qué hay conflictos entre las cabeceras y el programa que las implementa? Dadas las siguientes cabeceras:
(1) pilainfo.h
/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

(2) pilavector.h
#define MAXPILA 50

#include "pilainfo.h"

/*
 * El tipo pilavector define la pila y el indice a la cima
 * Se accederá mediante los habituales servicios push/pop
 */
typedef struct pilavector {
   tdata datos[MAXPILA];
   int top;
} tpv;

Dado prueba.c:
#include <stdio.h>

#include "pilainfo.h"
#include "pilavector.h"

tpv pv;

Si intentan compilar, verán que saltan bastantes errores. Se dividen en dos tipos de errores: los primeros en saltar son de redefinición de variables y los segundos sobre conflicto de tipos. Estoy seguro de que los segundos son consecuencia directa de los primeros.

Los primeros parecen surgir debido a algún tipo de conflicto con las cabeceras, pero no entiendo qué está mal. Las cabeceras están definidas correctamente e incluidas correctamente en prueba.c.
Este problema me ha surgido en un programa mayor donde pilavector.h presenta, además, cabeceras de métodos que luego hay que desarrollar dentro de prueba.c. A su vez, prueba.c servirá como programa auxiliar a otro mayor que es el que dirige toda la ejecución, es decir, el que tiene el main.

A: El error se produce porque no estás utilizando guardas en tus cabeceras.
Una cabecera típica de C debe tener la siguiente forma:
#ifndef [ID_CABECERA]
#define [ID_CABECERA]

// Código de la cabecera

#endif

En algunos casos también te lo puedes encontrar así:
#pragma once

// Código de la cabecera

La diferencia básica entre ambos ejemplos es que el primero es una solución estándar que funcionará siempre mientras que el segundo podría no funcionar en algunos compiladores.
Las directivas en rodean el código de la cabecera (en el primer caso) evitan que la propia cabecera se incluya varias veces en el código. Esto se hace así porque se evitan numerosos errores de compilación:

*

*Includes recursivos (A incluye B que a su vez incluye a A)

*Redefinición de funciones y estructuras

Pero, ¿por qué se producen estos errores?
Para entenderlo hay que comprender antes cómo funciona el proceso de compilación en C.
Cuando intentamos compilar un archivo en C, lo primero que entra en acción es el preprocesador. Este programa recorre el archivo y reemplaza todas las directivas del preprocesador por otra cosa:

*

*Las directivas condicionales #ifdef, #endif eliminarán el código que contienen si no se cumple la condición

*Las macros #define se reemplazan por el código correspondiente
#define SUM(a, b) a+b
int c = SUM(1, 3); -> int c = 1+3;

*Los includes se reemplazan por el archivo al que enlazan
Este proceso se repite hasta que no quede ninguna directiva de preprocesador en el código.
Es decir, en tu caso, en el archivo prueba.c sucederá lo siguiente:
Código original:
#include <stdio.h>

#include "pilainfo.h"
#include "pilavector.h"

tpv pv;

Se reemplaza el primer include:
// contenido de stdio.h ...

#include "pilainfo.h"
#include "pilavector.h"

tpv pv;

Se reemplaza el segundo include:
// contenido de stdio.h ...

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;
#include "pilavector.h"

tpv pv;

Se reemplaza el tercer include:
// contenido de stdio.h ...

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;
#define MAXPILA 50

#include "pilainfo.h"

/*
 * El tipo pilavector define la pila y el indice a la cima
 * Se accederá mediante los habituales servicios push/pop
 */
typedef struct pilavector {
   tdata datos[MAXPILA];
   int top;
} tpv;

tpv pv;

Ha aparecido otro include ... se reemplaza:
// contenido de stdio.h ...

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;
#define MAXPILA 50

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

/*
 * El tipo pilavector define la pila y el indice a la cima
 * Se accederá mediante los habituales servicios push/pop
 */
typedef struct pilavector {
   tdata datos[MAXPILA];
   int top;
} tpv;

tpv pv;

Como ves, ahora tenemos un problema y es que tanto pilainfo como tdata aparece definido dos veces:
// contenido de stdio.h ...

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo       // <<---- pilainfo(1)
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;                       // <<---- tdata(1)
#define MAXPILA 50

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo       // <<---- pilainfo(2)
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;                       // <<---- tdata(2)

/*
 * El tipo pilavector define la pila y el indice a la cima
 * Se accederá mediante los habituales servicios push/pop
 */
typedef struct pilavector {
   tdata datos[MAXPILA];
   int top;
} tpv;

tpv pv;

Este problema se soluciona definiendo las guardas en las cabeceras:
pilainfo.h
#ifndef PILAINFO_H
#define PILAINFO_H

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

#endif

pilavector.h
#ifndef PILAVECTOR_H
#define PILAVECTOR_H

#define MAXPILA 50

#include "pilainfo.h"

/*
 * El tipo pilavector define la pila y el indice a la cima
 * Se accederá mediante los habituales servicios push/pop
 */
typedef struct pilavector {
   tdata datos[MAXPILA];
   int top;
} tpv;

#endif

Ahora el código generado por el preprocesador variará ligeramente:
Código original:
#include <stdio.h>

#include "pilainfo.h"
#include "pilavector.h"

tpv pv;

Se reemplaza el primer include:
// contenido de stdio.h ...

#include "pilainfo.h"
#include "pilavector.h"

tpv pv;

Se reemplaza el segundo include:
// contenido de stdio.h ...

#ifndef PILAINFO_H
#define PILAINFO_H

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

#endif
#include "pilavector.h"

tpv pv;

Se procesa el condicional. Como el símbolo PILAINFO_H no está definido, el código permanece:
// contenido de stdio.h ...

#define PILAINFO_H

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

#include "pilavector.h"

tpv pv;

Se reemplaza el tercer include:
// contenido de stdio.h ...

#define PILAINFO_H

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

#ifndef PILAVECTOR_H
#define PILAVECTOR_H

#define MAXPILA 50

#include "pilainfo.h"

/*
 * El tipo pilavector define la pila y el indice a la cima
 * Se accederá mediante los habituales servicios push/pop
 */
typedef struct pilavector {
   tdata datos[MAXPILA];
   int top;
} tpv;

#endif

tpv pv;

Se procesa el condicional. PILAVECTOR_H no está definido, luego el código que engloba el condicional permanece intacto:
// contenido de stdio.h ...

#define PILAINFO_H

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

#define PILAVECTOR_H

#define MAXPILA 50

#include "pilainfo.h"

/*
 * El tipo pilavector define la pila y el indice a la cima
 * Se accederá mediante los habituales servicios push/pop
 */
typedef struct pilavector {
   tdata datos[MAXPILA];
   int top;
} tpv;

tpv pv;

Queda un #include, se reemplaza:
// contenido de stdio.h ...

#define PILAINFO_H

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

#define PILAVECTOR_H

#define MAXPILA 50

#ifndef PILAINFO_H
#define PILAINFO_H

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

#endif

/*
 * El tipo pilavector define la pila y el indice a la cima
 * Se accederá mediante los habituales servicios push/pop
 */
typedef struct pilavector {
   tdata datos[MAXPILA];
   int top;
} tpv;

tpv pv;

Se procesa el condicional. Ahora vemos que el símbolo PILAINFO_H ya se encuentra defindo más arriba, luego el condicional desaparecerá sin más:
// contenido de stdio.h ...

#define PILAINFO_H

/*
 * Este tipo define la información que contiene la pila (el contenido)
 */
typedef struct pilainfo
{
     int id;
     char matricula[10];
     char dni[10];
     char nombre[50];
     char mail[50];
     float nota;
} tdata;

#define PILAVECTOR_H

#define MAXPILA 50

/*
 * El tipo pilavector define la pila y el indice a la cima
 * Se accederá mediante los habituales servicios push/pop
 */
typedef struct pilavector {
   tdata datos[MAXPILA];
   int top;
} tpv;

tpv pv;

Como ves, esto hace que el símbolo que estaba repetido ya no lo esté, evitando los errores de compilación que se te estaban generando.


text:
Q: Difference between "crontab -e" & editing crontab file manually? I noticed some people use "crontab -l" to view cronjobs and "crontab -e" to edit them. However there are also times where people manually modify "/etc/crontab" to view/add/remove cronjobs.
Both methods work fine, the only thing I noticed is that cronjobs added with "crontab -e" doesn't show up inside "/etc/crontab" even though it still runs normally.
I'd like to know what are the differences between these 2 methods? Are there any advantages/disadvantages over each other?
PS. I'm on CentOS.

A: The normal per-user crontabs that you edit with crontab -e are located in /var/spool/cron.
/etc/crontab holds a "system-wide" crontab maintained by the system administrator.
There's typically also a /etc/cron.d directory where installed software can add entries.

redpajama_set_name: RedPajamaStackExchange


text:
Q: D3: How to conditionally bind SVG objects to data? I have here an array of objects that I'm visualising using D3. I bind each object to a group element and append to that an SVG graphic that depends on some object property, roughly like this:
var iconGroups = zoomArea.selectAll("g.icons")
        .data(resources)
        .enter()
        .append("g")

var icons = iconGroups.append(function(d){
         if(d.type == "Apple"){
             return appleIcon;
         }else if(d.type == "Orange"){
             return orangeIcon;
         })

etc. Now I'd like to extend some of those icons with an additional line. I could add a line element for each data point and set them visible only where applicable, but since I want to add them only for say one out of a hundred data points, that seems inefficient. Is there a way to bind SVG lines to only those objects where d.type == "Apple"?

A: You could add a class to the icons to be selected (e.g. appleIcon), and use that class in a selector to add the lines.

A: Use d3 filter.
selection.filter(selector)

Filters the selection, returning a new selection that contains only the elements for which the specified selector is true.
Reference: https://github.com/mbostock/d3/wiki/Selections#filter
Demo: http://bl.ocks.org/d3noob/8dc93bce7e7200ab487d

A: I would create separate selections for icons and lines, this way:
var iconGroups = zoomArea.selectAll('g.icons')
  .data(resources);
iconGroups
  .enter()
  .append('g')
  .classed('icons', true);
iconGroups.exit().remove();

var icons = iconGroups.selectAll('.icon').data(function(d) {return [d];});
icons
  .enter()
  .append(function(d) {
    if(d.type === 'Apple'){
      return appleIcon;
    }else if(d.type === 'Orange'){
      return orangeIcon;
    }
  }).classed('icon', true);
icons.exit().remove();

var lines = iconGroups.selectAll('.line').data(function(d) {
  return d.type === 'Apple' ? [d] : [];
});
lines
  .enter()
  .append('line')
  .classed('line', true);
lines.exit().remove();

.exit().remove() is added just because I add it always to be sure that updates work better. :)
Maybe the code is longer than .filter() but I use the following structure all the time and it's easier to scale it.
edit: apropos comment - If you need to pass indexes, you should pass them in binded data:
var iconGroups = zoomArea.selectAll('g.icons')
  .data(resources.map(function(resource, index) {
    return Object.create(resource, {index: index})
  }));

(Object.create() was used just to not mutate the data, you can use _.clone, Object.assign() or just mutate it if it does not bother you)
then you can access it like:
lines.attr("x1", function(d){ console.log(d.index);})


text:
Q: Testing async fire-and-forget methods in Java 8 I'm trying to write an integration test that involves a method that includes a fire-and-forget completion stage method in it in Java 8. The app code looks something like the following:
public CompletionStage<User> createAndStoreUser() {
    return createUser()
            .thenApply(this::store)
            .thenApply(user -> {
                findTeam(user)
                    .thenAccept(team -> { // fire and forget
                        thirdPartyClient.enqueue(team);
                    })
                    .handle(swallow(t -> log.error("Enqueue team failed", t)));
                return user;
            })
    })

Currently my integration test looks like this:
@Test
public void testCreateAndStoreUser() {
    User user = createAndStoreUser().toCompletableFuture().join();

    ItThirdPartyClient thirdPartyClient = itThirdPartyClient();
    assertThat(thirdPartyClient.getQueue(), hasSize(1));
}

But this isn't guaranteed to pass every time because the enqueue call is in a different thread and may not have completed by the time the assertion is made. Is there any way to force the nested CompletionStage to complete just for testing purposes, but not in the actual app where we want to fire-and-forget?

A: There are many options and library that you can use to "wait" for the result or better say, avoid the mean thread complete the test method before you can assert your async result:

*

*If you use Java Futures you can use the blocking methods to block the main thread until the future is complete, be aware that this can be blocked forever.

*If you can provide the Executor to your async method you can use a synchronous Executor in your unit test and an asynchronous executor in your production code.

*In other hand you can use some library to test this

*

*The first and easier solution is use CountDownLatch but you will found error very early when you try to return the assert result from your asynchronous thread to the main thread.

*My choice is concurrent unit https://github.com/jhalterman/concurrentunit a very good explanation can be found here https://github.com/playframework/play-java-ebean-example/blob/2.6.x/test/ModelTest.java

*Another good option is https://github.com/awaitility/awaitility you can see some example here https://github.com/playframework/play-java-ebean-example/blob/2.6.x/test/ModelTest.java


text:
Q: android: Get selected item from MultiAutoComplete Textview and maupulate and update the EditView? 1.I have created a MultiAutoCompleteTextview.(I have used SimpleAdapter to display the list)
2.I have tried searching for a string.
3.if i click on an item in the list it displayed the content of it in the EditText.
my question is that is there a possible way to save that text in a string and manipulate that string and display the updated string in the EditText of the MultiAutoCompleteTextVew. For example if the list show the list of name's and if i selected a name say "Mr.X" (by default it will display the text "Mr.X," in the EditText), but i want it to display "Mr.X - Male," in the EditText.
thanks :)

A:
For example if the list show the list of name's and if i selected a name say "Mr.X" (by default it will display the text "Mr.X," in the EditText), but i want it to display "Mr.X - Male," in the EditText.

(Honestly, this is the only part of your question that I understood. So I'll base my answer off of this example.)
Simply override a click listener to add the data that you want, like this:
mAutoComplete.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int index, long position) {
        // Query your data to determine if the person is male or female and store it in gender;
        String text = mAutoComplete.getText().toString();
        gender = determineGender(text); // returns a string either "Male" or "Female"
        mAutoComplete.setText(text + " - " + gender);
    }
});


text:
Q: How does one implement a dexterity.membrane user and group? On Plone 4.3.7, as per Products.Membrane & dexterity.membrane instructions, I've added a CustomMember & CustomGroup content type and assigned them the proper behaviors. After adding instances of them, going to membrane_tool, adding those types (seems this was required) to the selection of membrane content and reindexing, instances of custom member types show up in membrane_tool catalog.
However, groups do not show up (in membrane_tool catalog). Neither do the groups show up in the regular site management Users/Groups  UI, but I guess that's to be expected (given they are not catalogued).
Neither can I log in using the credentials entered when adding CustomMember instances.
What additional steps are there to make custom Dexterity-based Users & Groups work? Is the group assignment done by containment (ie. a CustomUser must be added inside a CustomGroup) or via some other mechanism? And how are roles assigned?
P.S. I've also tried out the example member content type provided by dexterity.membrane, but trying to add that results in an error.

A: The default implementation expects the membrane user to have a "enabled" workdflow state.


text:
Q: Adapter list item update issue I'm working on a screen where I have to display twice the same collection of items. I'm using two RecyclerView's each with a different instance of the same Adapter
Besides the two RecyclerViews in the screen I have a continue button to go to the next screen.
I want to put some constraints on the button so that the user will not be able to proceed to the next screen if he doesn't select an item from each RecyclerView
The following method is called when the user taps on an item.
fun setSelection(item: Item) {
    list.forEach {
        it.isSelected = false
        if (it.id == item.id) it.isSelected = true
    }
    notifyDataSetChanged()
}

And to verify if the list has at least one selected item I use this:
fun isAnySelected(): Boolean {
    return list.any { item -> item.isSelected }
}

In the button's clickListener I added this verification:
if ((first_recycler.adapter as CustomAdapter).isAnySelected() &&
   (second_recycler.adapter as CustomAdapter).isAnySelected())
{ //go to next screen }
else{
// select an item before continue }

My problem is that if I select an item only from one RecyclerView, when I tap on the continue button both of them will return true.
Why does (second_recycler.adapter as CustomAdapter).isAnySelected() returns true if only
(first_massage_display.mdl_recycler.adapter as MassageAdapter).setSelection(item)

Is called?

A: Sounds like the lists in each adapter are referencing the same list item instances. This could be because you passed the same list to both adapters, or simply that you have not created distinct list item instances in each list. If two lists reference the same list items, than changing a list item in one list also changes it in the other.
I recommend making Item a data class so you can easily make copies. Then create a copy of the list where every member of the list is also copied, and pass that to the second Adapter. You can use map() to do both steps of copying the list and the items within it all at once:
val secondList = firstList.map(Item::copy)


text:
Q: Help ID a trapped in time comic I'm trying to find an old comic I once read.
Details:The story involves a group of scientists that are tossed back in time to the 1800's. They have no way of getting back. I think they tried to make a binary computer (like in back to the future)
They realize that they are not the only ones thrown back, so they reach out to the others scattered by organizing a revival (or something) that is hosted by Mick Jagger with music by the Rolling Stones etc. This allows them to find many other people like them.
They are also, oddly enough, attacked several times by cyborgs flying ships that look like dirigibles. It seems all of the science they introduce before society is ready causes mass overpopulation, pollution, and ecological collapse...so this new time line send back people/assassins to stop them from making a horrible world like theirs.
I have tried multiple google searched about trapped in time, lost in time, etc, and get nothing, but it was a multi-edition comic.

A: Brave Old World, written by William Messner-Loebs and published by Vertigo.
Synopsis of Book 1 The Century Turns; Abort, Retry, Reboot?

When the computer glitch everyone feared instead causes time itself to flip back to the year 1900, it's up to a band of elite computer programmers to reinvent the technology of the digital age in a barely industrial America. Their plan is to hack their way back into the 21st century by creating a bug-free computer age, but other issues, such as survival, take precedence when aliens from an alternate, dystopian year 2000 (a timeline created by the team's activities in 1900) travel back in time with orders to kill.

First occurrence of a hostile time traveler in Book 1

Invitation to Mick Jagger's assembly in Book 4


text:
Q: if $p\mathcal{O}_K$ splits completely in Galois extension, are all primes lying over $p$ generated by one class in $CL(K)$? L.S.,
Studying for my exam on algebraic number theory, I was thinking of writing down tricks for computing the class group of a number field fast. I thought of the following one, but I don't know if it is true. Could one maybe help me show whether it is or isn't?
Trick:
Let $K:\mathbb{Q}$ be a Galois extension of the degree $n$. Let $(p)$ split completely in $\mathcal{O}_K$ as $(p) = \prod_{i = 1}^n \mathfrak{p}_i$, with all $\mathfrak{p}_i$ of norm $p$. Now all $[\mathfrak{p}_i] \in CL(K)$ are generated by one $[\mathfrak{p}_j]$ for some $1 \leq j \leq n$.
The reason I suspect this might somehow be true, is because I already know that the Galois group acts transitively on a set of prime ideals lying over some $(p)$, and also because it happened in most class groups I computed so far.
Many thanks!

A: After some playing around with Sage, here is a counterexample.
Let $K=\mathbb Q(\sqrt[3]{11}, \zeta)$ where $\zeta$ is a cubed root of unity. Then $K$ is Galois with class group $C_2\times C_2$.
The prime $19$ splits completely in $K$. Two of the primes of $K$ lying above $19$ are $$(19, \zeta-\sqrt[3]{11}-2)\qquad\text{ and }\qquad(19, \zeta-\sqrt[3]{11}+9)$$
Neither of these primes are principal. Hence, if their ideal classes are to lie in a cyclic subgroup of $C_2\times C_2$ (which must be of order $2$), then both ideals must be in the same ideal class, and hence their product should be principal. However, their product is not principal.
Sage code:
K.<a> = NumberField(x^3-11)
L.<b> = K.extension(x^2+x+1)
C = L.class_group(); C
OL=L.ring_of_integers()

split =[C(P) for P,e in (19*OL).factor()]
split

split[0].is_principal()
split[1].is_principal()
test = split[0]*split[1]
test.is_principal()

and output:
Class group of order 4 with structure C2 x C2 of Number Field in b with defining polynomial x^2 + x + 1 over its base field
[Fractional ideal class (19, b - a - 2), Fractional ideal class (19, b - a + 9), Fractional ideal class (19, b - a - 9), Fractional ideal class (19, b - a - 6), Fractional ideal class (19, b - a + 5), Fractional ideal class (19, b - a + 6)]
False
False
False


text:
Q: Surjectivity projection morphisms of the fiber product I am currently learning some algebraic geometry. I try to find out whether the projection morphisms of a fiber product are always surjective (as maps of the underlying sets). So suppose that $X_1,X_2$ are schemes over some scheme $S$. Are the morphisms $p_i: X_1 \times_S X_2 \to X_i$ then necessarily surjective? Are they surjective if $X_1,X_2$ are separated?
I tried to show that this is indeed the case, but I haven't achieved much. Here is my attempt. By symmetry, it suffices to show that $p_1$ is surjective. If we can construct a scheme $Z$ with morphisms $f_i: Z \to X_i$ such that $f_1$ is surjective, then by the universal property we get a morphism $\psi: Z \to X_1 \times_S X_2$ such that $f_1 = p_1 \circ \psi$ (from which the surjectivity of $p_1$ follows). If $X_1 = X_2$, we can just take $\psi$ to be the diagonal embedding and then we're done. In all other cases, I do not see how I can proceed.

A: Let $X\subset Y$ be proper closed subscheme and let $S=Y$, with the natural maps $X\to S, Y\to S$. Then $X\times_S Y\to Y$ has image precisely $X\neq Y$.


text:
Q: What is webassembly for socket-based applications, http or non-http( eg. MQTT) web based protocol I have started learning about WebAssembly few days back.
I understand that WebAssembly is a compiled binary which can be used along side javascript to run
applications written in languages like C/C++, Rust etc with minimal changes.
My question is , if I am implementing a TCP/IP (or UDP) Socket program or a HTTP based server and use emscripten SDK to compile it and run in browser what exactly I am getting ? What are the benefits ?
Does this mean, that I was able to run server from a terminal earlier and use browser or postman as client to do GET/POST requests. And currently with WebAssembly I am able to run that application over browser( which effectively means see the console over browser) ?
How does WebAssembly help if I can convert a IoT protocol like MQTT to WebAssembly ? What can be the use case for doing it ?
How is it different from implementing a MQTT-HTTP proxy to talk to edge cloud ?
Also is the WebAssembly binary running on client side ? If yes, users will be using browsers' local runtime to run the application after downloading the webassembly binary on client sides ?

A: WebAssembly (WASM) in the browser is executed on a user's local browser and is limited to the capabilities and restrictions of the browser. Since at this time browsers do allow for socket-based networking, any program you compile to WASM cannot do things like open sockets or directly communicate via non-web networking protocols like MQTT.
Emscripten as a library tries to emulate POSIX networking functionality by proxying over WebSockets, XHR or fetch. It puts restrictions on how you build your server and likely many existing applications will need to be modified in order to work with Emscripten. You'll also need an additional proxy server hosted somewhere else, like a web server or local machine. So with Emscripten it is theoretically feasible to talk to a web server from the browser or host a server in the browser, but with the specific caveats I mentioned.
WASM also can be run outside the browser, such as part of a web server or embedded system. In each of those different environments there may be less or different restrictions. WASI is the standardization effort for bringing APIs to WASM in a secure and portable way, such as sockets and HTTP.


text:
Q: How to create openapi parameter for azure function in pascal case? I am creating an azure function with open api support that receives a query parameter, this parameter should only allow a list of values, so I am using an enum as is showing in the following code:
[FunctionName("GetInformation")]
[OpenApiOperation(operationId: "GetInformation", tags: new[] { "Information" })]
[OpenApiParameter(name: "System", In = ParameterLocation.Query, Required = true, Type = typeof(SystemEnum), Description = "System that generates information")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "api/information")] HttpRequest req, ILogger log)
{

}

To use the enum as string I am using the following enum
[Newtonsoft.Json.JsonConverter(typeOf(StringEnumConverter))]
public enum SystemEnum
{
    SystemA,
    SystemB,
    SystemC
}

But when the azure function is launched, the system parameter appears with camelCase naming.

Also in the swagger.json specification appears with camelcase naming

How can I change this behavior? Or What Do I need to change to the code to change the enum to pascalcase?


text:
Q: Ruby: mnitest-rails + mocha The instructions for using the mocha mocking library with minitest don't work, and I don't know why...  minitest 4.2.0, minitest-rails 0.3, mocha 0.12.4.  Per the instructions, at the bottom of Gemfile I have

group :test, :development do
  gem 'mocha', :require => false
end

which is supposed to turn off auto-requiring.  And then at the bottom of the test helper files, I have require 'mocha' - the instructions say require 'mocha/setup', which doesn't even exist.  With these two bits of code in, all the tests that run fine without mocha in the gemfile all fail with "undefined method 'run' blah blah blah".  Anyone see what I'm missing here?

A: Sigh, apparently those messages are indicative of having failed to install the mocha rails plugin.  That was the problem here.


text:
Q: Using WebServiceHost in desktop apps I'm hosting a service using WebServiceHost in my desktop application and not closing this service if the process is terminated. I checked the port I used after the process terminates and it was closed, and I was able to reuse the same port properly.
From this thread, the close only switch the state for the WebServiceHost object.
I found no threads warns not to use close. Does the desktop application disposes the object properly when done? Or it is required to close the service as the app terminates.
WebServiceHost WCFService = new WebServiceHost(wcs, httpBaseAddress);
WCFService.Open();
WCFService.Close(); // Is this line of code required when using WebServiceHost


text:
Q: Konva get image ID from click event I am trying to get the ID of the image I am clicking on by using the following code:
theImg.on('click', function() {
    alert($(this).attr('id')); //Should show 'IDofImg'
});

The Konva code is this:
var theImg = new Konva.Image({
    image: imageObj,
    x: stage.getWidth() / 2 - 200 / 2,
    y: stage.getHeight() / 2 - 137 / 2,
    opacity: 0.8,
    shadowColor: 'black',
    shadowBlur: 5,
    id: 'IDofImg',
    shadowOffset: {
        x: 0,
        y: 0
    },
    startScale: 1,
    shadowOpacity: 0.6,
    draggable: true
});

As you see, I have id: 'IDofImg', within the making of the image but it seems not to output the needed ID.
It currently outputs this when clicked on:
function() {
   // setting
   if (arguments.length) {
       this[setter](arguments[0]);
       return this;
   }
   // getting
   else {
       return this[getter]();
   }
}

What am I missing?
Fiddle here

A: You should use this.id() because it is the Konva Image object, and not an html/javascript object.
See also the docs: http://konvajs.github.io/api/Konva.Node.html#id


text:
Q: How to stop rendering each frame of a moving image onto the Surface in pygame? I'm trying to make a simple rainfall animation using pygame. I am moving the image downwards but updating it's rect.y position; however, each frame of the raindrop's movement is rendering onto the screen. A lot of sources point to that I would somehow have to refresh the screen at each frame, but where else should the position updates go?
Here is the full code:
import sys
import pygame
from raindrops import Raindrop
from pygame.sprite import Group

def let_it_rain():
    '''initialize pygame, settings, and screen object'''
    pygame.init()
    screen_width = 1200
    screen_height = 800
    bg_color = (144, 177, 226)
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("Let It Rain")

    raindrop = Raindrop(screen)
    raindrops = Group()

    #number of drops in a row
    spacex = screen_width - (2 * raindrop.rect.width)
    raindrop_number_x = int(spacex / (2 * raindrop.rect.width))

    #start window for raindrops
    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        #create row of raindrops
        for raindrop_number in range(raindrop_number_x):
            raindrop = Raindrop(screen)
            raindrop.x = raindrop.rect.x + 2 * raindrop.rect.x * raindrop_number
            raindrop.rect.x = raindrop.x
            raindrops.add(raindrop)

        screen.fill(bg_color)
        raindrops.update()
        raindrops.draw(screen)
        pygame.display.flip()

let_it_rain()

And the associated raindrops module:
import pygame
from pygame.sprite import Sprite

class Raindrop(Sprite):

    def __init__(self, screen):

        #load image
        super(Raindrop, self).__init__()
        self.screen = screen
        self.pic = pygame.image.load('rain.png')
        self.image = pygame.transform.smoothscale(self.pic,(50,60))
        self.rect = self.image.get_rect()

        #starting position
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        #store exact decimal position of rainddrop
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)

    def update(self):
        speed = 5
        self.y += speed
        screen_rect = self.screen.get_rect()
        self.rect.y = self.y
        #once raindrops reach the bottom of the screen, reposition to the top corrdinates
        if self.rect.y == screen_rect.bottom:
            self.y = 0
            self.rect.y = 0

A: What you need to do is move the for loop that creates raindrops before the while loop, like so:
import sys
import pygame
from raindrops import Raindrop
from pygame.sprite import Group

def let_it_rain():
    '''initialize pygame, settings, and screen object'''
    pygame.init()
    screen_width = 1200
    screen_height = 800
    bg_color = (144, 177, 226)
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("Let It Rain")

    raindrop = Raindrop(screen)
    raindrops = Group()

    #number of drops in a row
    spacex = screen_width - (2 * raindrop.rect.width)
    raindrop_number_x = int(spacex / (2 * raindrop.rect.width))

    #create row of raindrops
    for raindrop_number in range(raindrop_number_x):
        raindrop = Raindrop(screen)
        raindrop.x = raindrop.rect.x + 2 * raindrop.rect.x * raindrop_number
        raindrop.rect.x = raindrop.x
        raindrops.add(raindrop)
    #start window for raindrops
    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        screen.fill(bg_color)
        raindrops.update()
        raindrops.draw(screen)
        pygame.display.flip()

let_it_rain()

When it was inside the loop, it kept recreating the raindrops at every new y position


text:
Q: How to use GitLab CI only:changes with only:refs? My .gitlab-ci.yml configuration has a job like:
Lint dummy:
  stage: prepare
  tags: [my-tag]
  only:
    refs: [merge_requests]
    changes: [Thorfile]
  script: "/bin/true"

The only difference from the real job is the tags. Everything else is exactly the same.
Yes, when creating a merge request where Thorfile has not been changed, the "Lint dummy" job is still created.
From the documentation as of 2019.03.14 (https://docs.gitlab.com/ee/ci/yaml/README.html#using-changes-with-merge_requests)

With pipelines for merge requests, make it possible to define if a job should be created base on files modified in a merge request.
For example:
docker build service one:
  script: docker build -t my-service-one-image:$CI_COMMIT_REF_SLUG .
  only:
    refs:
      - merge_requests
    changes:
      - Dockerfile

I am using GitLab 11.7.5.

A: Support for only:changes will be available in the next release:
https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/24490
Edit:
released now (version 11.9). here is the documentation:
https://docs.gitlab.com/ee/ci/yaml/#using-changes-with-merge_requests


text:
Q: Display text when header width = 300px, otherwise set display: none; I wrote a code for my header, when you hover the header, it resizes its width to 300px and now I would like to add text inside only when width = 300px or slowly add the text while resizing the header after hovering it with mouse.
This is the code I wrote.
CSS:

#header {width: 5px; height: calc(100vh - 30px); text-align: center; transition: width 0.5s ease-out; -o-transition: width 0.5s ease-out; -ms-transition: width 0.5s ease-out; -moz-transition: width 0.5s ease-out; -webkit-transition: width 0.5s ease-out;}
#header:hover {width: 300px; background: #171C21;}

HTML:

test

test

test

I'm looking for a CSS method if there is any method to make this in CSS.
Live preview: http://awesomeness.adam.zur.io/

A: I think this should be useful.

#header {
  width              : 10px                ;
  height             : calc(100vh - 30px)  ;
  text-align         : center              ;
  transition         : width 0.5s ease-out ;
  -o-transition      : width 0.5s ease-out ;
  -ms-transition     : width 0.5s ease-out ;
  -moz-transition    : width 0.5s ease-out ;
  -webkit-transition : width 0.5s ease-out ;
  background         : #171C21             ;
  overflow           : hidden              ;
  color              : white               ;
}

#header:hover {
  width : 300px ;
}

#textContent{
  visibility : hidden;
}

#header:hover  #textContent{
  visibility : visible;
}

test

test

test

A: You could make the text invisible by making it fully transparent with a color value of color: rbga(0, 0, 0, 0.0); and make the color solid on hover with  color: rbga(0, 0, 0, 1.0);
Here's a codepen demonstrating that  http://codepen.io/anon/pen/yeggKO
(edited, also has the 300px width now on hover)

A: You can do one thing :
Add one div with hidden element, when you hover on #header make display : block of that div tag.
Here is small example of it :

#header {width: 5px; height: calc(100vh - 30px); text-align: center; transition: width 0.5s ease-out; -o-transition: width 0.5s ease-out; -ms-transition: width 0.5s ease-out; -moz-transition: width 0.5s ease-out; -webkit-transition: width 0.5s ease-out;}
#header .hiddencontent{display:none;}
#header:hover {width: 300px; background: #171C21;}
#header:hover .hiddencontent{display:block;}

test

test

test

test

test

test

test

test

test

A: Well, everything seems to be solved, but something went wrong with the hover effect of the header. When I take off my mouse of the header it doesnt animate back to its original width, it gets back without animation.
html, body {background: #1A2026; font-family: "Open Sans", "sans-serif";}
* {margin: 0; padding: 0;}
a {display: block;}

/* DESKTOP */
#header {width: 5px; height: calc(100vh - 30px); padding-top: 10px; color: rgba(255,255,255,0.0); text-align: center; transition: width 0.5s ease-out; -o-transition: width 0.5s ease-out; -ms-transition: width 0.5s ease-out; -moz-transition: width 0.5s ease-out; -webkit-transition: width 0.5s ease-out;}
#header:hover {width: 300px; background: #171C21; color: rgba(255,255,255,1.0);}
#header .hidden {display:none;}
#header .hidden > p {font-size: 16px; text-transform: uppercase; margin-bottom: 10px; font-weight: 600;}
#header .hidden > a {margin-top: 5px; text-decoration: none; color: #fff; font-weight: 600;}
#header .hidden > a:hover {color: #27ae60;}
#header:hover .hidden {display:block;}

#footer {width: 100%; height: auto; bottom: 0px; position: absolute;}
#footer .copyright {height: 30px; background: #171C21; line-height: 30px;}
#footer .copyright > p {color: #fff; text-align: center; font-size: 13px;}


text:
Q: HighCharts Data and Legend Ordering I set up a HighChart to look at a MySQL database via a JSON feed, however the problem I have is that if the stacked column chart displays January to December from left to right the Legend shows it in reverse order December to January left to right.
Having tried to re-order the series in the code and poking around on the HighCharts information I am at a dead end.
Is this correctable, and if so could you let me know what to change please? Thanks.
Here's my code:
<?php
$con = mysql_connect("***","***","***");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("***", $con);

$query = mysql_query("SELECT * FROM viewByMonth");

$category = array();
$category['name'] = 'variety';

$series1 = array();
$series1['name'] = 'Jan';

$series2 = array();
$series2['name'] = 'Feb';

$series3 = array();
$series3['name'] = 'Mar';

$series4 = array();
$series4['name'] = 'Apr';

$series5 = array();
$series5['name'] = 'May';

$series6 = array();
$series6['name'] = 'Jun';

$series7 = array();
$series7['name'] = 'Jul';

$series8 = array();
$series8['name'] = 'Aug';

$series9 = array();
$series9['name'] = 'Sep';

$series10 = array();
$series10['name'] = 'Oct';

$series11 = array();
$series11['name'] = 'Nov';

$series12 = array();
$series12['name'] = 'Dec';

while($r = mysql_fetch_array($query)) {
    $category['data'][] = $r['variety'];
    $series1['data'][] = $r['Jan'];
    $series2['data'][] = $r['Feb'];
    $series3['data'][] = $r['Mar'];
    $series4['data'][] = $r['Apr'];
    $series5['data'][] = $r['May'];
    $series6['data'][] = $r['Jun'];
    $series7['data'][] = $r['Jul'];
    $series8['data'][] = $r['Aug'];
    $series9['data'][] = $r['Sep'];
    $series10['data'][] = $r['Oct'];
    $series11['data'][] = $r['Nov'];
    $series12['data'][] = $r['Dec'];
}

$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
array_push($result,$series3);
array_push($result,$series4);
array_push($result,$series5);
array_push($result,$series6);
array_push($result,$series7);
array_push($result,$series8);
array_push($result,$series9);
array_push($result,$series10);
array_push($result,$series11);
array_push($result,$series12);

print json_encode($result, JSON_NUMERIC_CHECK);

mysql_close($con);
?>

A: You can reverse legend order by parameter: reversed


text:
Q: Android custom CursorAdapter with AsyncTask I'm trying to build a list with an image that is taken from the device and a text. It turns out that taking images from the phone that was from the phone's camera is a task that takes a while so I'm trying to make it as fast as possible so the user experience won't get slower. All I got from this is that it looks like all the images are loaded in one ImageView and than the images spread to all the other ImageViews (I'm not completely sure that my implementation of the ViewHolder technique and Custom CursorAdapter is correct).
public class MyCustomCurserAdapter extends CursorAdapter {
  static class ViewHolder {
    public TextView nameText;
    public ImageView imageThumbnail;
  }

  Cursor cursor;

  public MyCustomCurserAdapter(Context context, Cursor c, int flags) {
    super(context, c, flags);
    // TODO Auto-generated constructor stub
  }

  @Override
  public void bindView(View view, Context arg1, Cursor cursor) {

    ViewHolder holder = (ViewHolder)view.getTag();

    int pathCol = cursor.getColumnIndex(NewPicSQLiteHelper.COLUMN_PATH);
    String imageInSD = cursor.getString(pathCol);
    File imgFile = new  File(imageInSD);

    if(imgFile.exists()){

        int nameCol = cursor.getColumnIndex(NewPicSQLiteHelper.COLUMN_PIC_NAME);
        String name = cursor.getString(nameCol);

        if (name != null)
            holder.nameText.setText(name);

        ImageTask task = new ImageTask(holder.imageThumbnail);
        task.execute(imgFile);
    }

  }

  @Override
  public View newView(Context arg0, Cursor cur, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.new_pic_item, parent, false);
    ViewHolder holder = new ViewHolder();

    holder = new ViewHolder();
    holder.nameText = (TextView) view.findViewById(R.id.pic_name_entry);
    holder.imageThumbnail = (ImageView) view.findViewById(R.id.pic_thumbnail);

    // The tag can be any Object, this just happens to be the ViewHolder
    view.setTag(holder);

    return view;
  }

  private class ImageTask extends AsyncTask<File, Void, Bitmap>{
    private final WeakReference <ImageView> imageViewReference;

    public ImageTask(ImageView imageView) {
        imageViewReference = new WeakReference <ImageView> (imageView);
    }

    @Override
    protected Bitmap doInBackground(File... params) {
        String path = params[0].getAbsolutePath();

        return decodeSampledBitmapFromResource(path,75,75);
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                if (result != null) {
                    imageView.setImageBitmap(result);
                    imageView.setVisibility(ImageView.VISIBLE);
                } else {
                                    imageView.setVisibility(ImageView.INVISIBLE);
                }
            }

        }

    }

    private Bitmap decodeSampledBitmapFromResource(String orgImagePath, int reqWidth, int reqHeight) {

    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

  }
}

A: I think probable reason thats its taking time is because the images would be of at least 1 mb size further you can change to thumbnail and retrieve it and also if still taking time you could put lazy downloading which is done when we take image from the server(Basically what it does is it loads the text and shows image when we get the image)

A: Remove ImageTask AsyncTask ..
Use a Libraries like Glide or Picasso . Very effective for almost any case where you need to fetch, resize, and display a remote image.
I used a glide for loading images from phone storage uri
Use any of the above and see the difference


text:
Q: Configure MSLocalDB in a .NET config file I have created a .NET Standard C# project and a SQL database in my LocalDB server (LocalDb)\MSSQLLocalDB.
I have tried to configure the connection string in the project web configuration file but in runtime the connection to SQL server is not succeeded.
How can I configure a local DB server in my project config file?
This is the connection string configured in my project web.config:
<connectionStrings>
    <add name="iPark.Database.Properties.Settings.iParkConnectionString"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=iPark;User ID=iParkUser;Password=iParkPassword1"
         providerName="System.Data.SqlClient" />
</connectionStrings>

When I try to access the database, the following error occurs:

Relative to the database, I've created the user iParkUser with authentication type "SQL Server Authentication". I can login to the server and the database with the user and its roles are the following:

*

*db_owner

*db_reader

*db_writer


text:
Q: Drupal 7 Accessing theme variables in page content I'm trying to set a variable in a drupal theme that is readable from PHP code in page content. The reason why I'm doing this is that I'm trying to code the page so that when the theme is activated (at a set time), it displays select content only when the theme is active. I do not want to use CSS because I don't want people to be able to get the information ahead of time.
Any ideas?

A: You can add an if statement in your theme that will show the content on the basis of a variable. You can then set this variable in your custom modules or hook functions.
Here is a tutorial how to set a variable in the hook and then print it out in the template:
http://purencool.com/drupal-7-preprocess-tutorial-adding-variable-to-template


text:
Q: Putting a Method in an array So I want to make an array that has methods in it. For example:
public static void givePointBoost(){
points += 30};

or
public static void giveSword(){
Actions.giveItems(Items.diamond_sword);
Actions.givePotion(Potions.slowness);};

As you can see, both of these methods are voids. What I want to do is have an array that has all these voids in it so that I can pick a random method out of it later on. But I can't put it into an array because It says that I can't have an array of voids. When I try to make it an array of objects, It says that it can't switch from object to void. So my question is:
How do you get methods inside of Arrays?

A: In Java, you do not have delegates or function pointers, which you can store in collections or arrays like objects, so you have to employ the Command Pattern to achieve this. Basically, you wrap a method in an object that you pass on. The receiver can then access the method via the object.

*

*Create a command interface:
interface ICommand {
    public void execute();
}

*Wrap a method (or multiple) in a class via inheritance...
class SpecificCommand implements ICommand {
    public void execute() {
        // Do something...
    }
}

*...or wrap existing methods directly in an anonymous class:
class SomeClass {

    private void someMethod(int someValue) {
        // Some stuff...
    }

    public static void main(String[] args) {

        List<ICommand> commands = new ArrayList<>();

        // Do something...

        // Add command directly
        ICommand command = new ICommand() {
            @Override
            public void execute() {
                someMethod(42);
            }
        }

        // Do something....

    }
}

*Call the commands from the list in a loop (or single):
for (ICommand command : commands) {
    command.execute();
}

A: Let's sort things out.
Arrays in Java can only contain objects or primitives.
Collections in Java can only contain objects.
What you're looking for is called a Command Pattern.
https://www.tutorialspoint.com/design_pattern/command_pattern.htm
You'll have a list of objects, each of them with single method, let's say "execute". With polymorphism, each of this objects will do something different.
Here's an example:
import java.util.ArrayList;
import java.util.List;

public class CommandPatternExample {
    public static void main(String[] args) {

        List<Command> commands = new ArrayList<>();
        commands.add(new GiveBoostCmmand("knight"));
        commands.add(new GiveItemCommand("sword", "knight"));

        for (int i = 0; i < 3; i++) {
            commands.get((int)(Math.random() * commands.size())).execute();
        }

    }

    public interface Command {
        void execute();
    }

    static class GiveBoostCmmand implements Command {
        private String targetName;

        public GiveBoostCmmand(String targetName) {
            this.targetName = targetName;
        }

        public void execute() {
            System.out.println("Boosting " + this.targetName);
        }
    }

    static class GiveItemCommand implements Command {

        private String itemName;
        private String targetName;

        public GiveItemCommand(String itemName, String targetName) {
            this.itemName = itemName;
            this.targetName= targetName;
        }

        public void execute() {
            System.out.println("Giving " + this.itemName + " to " + this.targetName);
        }
    }
}

A: Are you trying to say you want the result of the method to be added to the array?
As far as i know, i don't think you can put a method inside an array.
What you could do is create an interface, and provide implementations and then add those objects to an array. That way you could pick a random object and call the method defined in the interface.

A: The main question is Why do you need methods in an array?
The other solutions using the Command pattern are a great solution. But seeing your code I believe that you also should put that pattern in a specialized class whose purpose will be to initialize the pool of possible actions and select one at random when you need to.
Which would translate to the following UML
|RandomActionCaller      |
|------------------------|
|- List<Command> commands|
|------------------------|
|+ selectRandomEffect()  |

In the constructor you prepare the basic list of possible outcome, please refer to the other answers about the Command pattern. Maybe also add a method to add more commands to the list of commands from the outside of the class, this can be usefull.
The select random effect method would only select a random number between 0 and commands.size()-1, get the command instance and execute it. If you need to execute it somewhere else in your code just return it from the select random effect method.


text:
Q: Cakephp validations not working Validations are working but form is not getting submitted and data is not inserted:
addgroup.ctp:
echo $form->create('Group', array('url' => array('controller' => 'admin', 'action' =>'addgroup'), 'onSubmit' => 'return Validate()'));

echo $form->input('name',array('label' => false));

 <input type="submit"  value="Submit"/>

 <input type="button" value="Cancel"/>

Group Model:
var $validate = array(

    'name' => array(
        'isRequired' => array(
            'rule' => 'required',
            'message' => 'Enter group name.'
        ),
        'isUnique' => array(
            'rule' => 'isUnique',
            'message' => 'This group name has already been taken.'
        ),
    ),
);

in controller:
$this->Group->save($this->data,array('validate' => true)

If I make any empty entry or duplicate entry it gives errormessge,
but if I make valid entries then also form gives error-message,
What m I missing here?

A: you need to close the form $this->Form->end('Submit'); and the save function: $this->Group->save($this->data); It will validate when it saves.


text:
Q: Multiple inheritance in "broken" diamonds I was exploring how multiple inheritance might work in cases where one of the (two) parent classes doesn't inherit from the common base class. Here's the program:
'''Demomstration of MRO on 'broken' diamonds'''

class Base:
    def hello(self):
        print('Base')

class Left(Base):
    def hello(self):
        print('Left')
        super().hello()

class Right:
    def hello(self):
        print('Right')
        super().hello()

class Child1(Left, Right):
    '''Class has right edge missing'''
    def hello(self):
        print('Child1')
        super().hello()

class Child2(Right, Left):
    '''Class has left edge missing'''
    def hello(self):
        print('Child2')
        super().hello()

print(help(Child1))
print(help(Child2))

print('Child1 output:')
print('==============')
Child1().hello()
print('\nChild2 output:')
print('==============')
Child2().hello()

The help() says that in the first case, the MRO will be:
 |      Child1
 |      Left
 |      Base
 |      Right
 |      builtins.object

While in the second case it will be (please be a little careful: Right is actually on the left-hand side here):
 |      Child2
 |      Right
 |      Left
 |      Base
 |      builtins.object

But the output of the hello() functions is:
Child1 output:
==============
Child1
Left
Base

Child2 output:
==============
Child2
Right
Left
Base

So in the first case, the Right class has been entirely skipped! It's almost like the interpreter couldn't reach out to it because there was no connection to follow.
I can understand that this can be explained by working through the C3 Linearization algorithm, but isn't it a bit strange that one class in the hierarchy gets left out while in the mirror-image case it doesn't?

A: Your Base.hello function is "broken" with respect to this test. Consider the hello functions in your MRO:
Child1.hello
    print('Child1')  # PRINTED
    super().hello()  # super() -> Left
Left.hello
    print('Left')    # PRINTED
    super().hello()  # super() -> BASE
Base.hello
    print('Base')  # PRINTED
    # no call to super()!!!
Right.hello    # NEVER CALLED
    print('Left')
    super().hello()  # super() -> object
builtins.object.hello

So basically, once super().hello is resolved to Base.hello, the super chain stops. Base.hello misses a call to super to advance onto Right. Thus, Right.hello isn't called, even though Right is in the MRO.


text:
Q: What's the most abused features in Visual Studio / C#? For me, No.1 has to be code folding.
#region xxx
#endregion

All of sudden, people find an excuse to have big classes(files) because they can "organize" them nicely. I once saw a half-page-long class with 3,000 lines. I was speechless and they were like "what's the problem"?
No.2 is partial class. It's actually a nice feature especially when you work with generated code. However, some people use it to "break down" a class to multiple pieces. Why? Because that class is so big and popular that it's always locked in the source control. Instead of breaking down the class into different smaller classes, they create multiple files like my_Class1.cs, your_Class1.cs etc so that people can work on Class1 at the same time.
I would like to include "Copy&Paste" but it's not Visual Studio's fault...

A: Next to #region blocks I would say the ASP.NET IDataSource implementations (SqlDataSource, LinqDataSource) that force (allow) you to write data-access code directly into your aspx pages. I would not use this even for a really small demo app, but nowhere in the documentation of these classes is it mentioned that for a well-designed application you should not use these classes.

A: I think the most abused feature would be using the default templates as is.  Many of the templates include "partial" as well as the regions and include/using statements that aren't required by the code inside of the class.
After that, I'd have to agree with the #region blocks; however, those CAN be useful if done properly.  Usually though they are used as a means to organize classes that are larger than they probably should be.

A: Not paying attention to Warnings

A: Graphical editor for WebForms. Spoiled so many potentially good developers into drag-and-drop monkeys.


text:
Q: ayuda con este ejercicio que no entiendo Desarrolle el algoritmo solicitado:

*

*Desarrollar un módulo no void CorrerDatos que recibe entre otros los siguientes parámetros:

*

*un vector VLeg de 150 posiciones que contiene únicamente Legajos de tipo entero;

*un valor tope < 150 con la posición del último Legajo cargado en el vector;

*un valor pos <= tope;

*un nuevo Legajo a "insertar" en la posición pos del vector.

Debe

*

*Insertar en la posición pos de VLeg, el Legajo recibido sin perderse los datos ya cargados en el vector. Como pos es <= tope, en dicha posición y las que siguen hasta tope habrá Legajos ya cargados; por lo tanto para poder insertar deberá realizar el corrimiento de los elementos necesarios (copiando cada uno debajo de su posición actual).

*Retornar true en caso en que el vector se haya llenado; caso contrario retornar false.

    bool correrdatos(int vleg[150],int tope,int pos,int legajo)
    {
        int aux,aux2,i;

        for( pos ; pos<tope ; pos++)
        {
        aux=vleg[pos];
        vleg[pos]=legajo;
        legajo=aux;
        }

        if(pos==tope-1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Esto es lo que tengo hecho por mi, lo que necesitaría saber si esta correcto, ya que solo me pide la función.


text:
Q: Get path of image to fileupload I need to get path of selected image in grid view to file-upload.
For example I get selected value in cell to textbox by code below
 txtucname.Text = gridusers.SelectedRow.Cells[1].Text;

How to achieve that with file-upload
When editing any Customer record, if user doesn't select any Image, the previous image is removed.
if (imgup.HasFile)
{
    string imgName = imgup.FileName.ToString();
    imgup.SaveAs(Server.MapPath("../Images/Customer/") + imgName);
    string imgPath = "../Images/Customer/" + imgName;
    string msg = c.UpdateCustomer(txtcustid.Text, txtucname.Text, imgPath);
    msg = "<br>Image Uploaded Successfully";
    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg + "');", true);

}
else
{
    string msg2 = c.UpdateCustomer(txtcustid.Text, txtucname.Text,,null);
}

A: string Img1, unq1;
string filepath = "~/YourFolder/";
img1 = System.IO.Path.GetFileName(gridusers.SelectedRow.Cells[2].ImageName);
unq1 = filepath + img1;


text:
Q: Dump de todos os bancos para um usuário especifico Tenho o usuário plant652 que tem 54 bancos de dados e preciso fazer o backup de todos eles. Como fazer todos de uma única vez no CentOS 6 com cPanel?

A: Notei que você usou a tag do mysqldump. Já que você não informou o sistema operacional que está usando, vou assumir que seja Linux - que é o mais comum - caso não seja, você pode usar o conteúdo dessa resposta para adaptar ao seu ambiente. Você vai precisar logar com um usuário e senha pela ferramenta do mysqldump se quiser fazer qualquer operação.
Não é ideal executar nenhum script que um estranho na internet escreveu como root. :-)
Portanto não vou aconselhar que faça isso. Mas se tiver vários bancos pra ser feito backup e isso estiver devidamente separado em seus respectivos usuários, usar as credenciais de root vai te permitir executar o script uma única vez para todos os bancos. Como mencionou que os 54 bancos pertencem ao usuário plant652, recomendo que execute como tal. Lembrando, é claro, que para isso você vai precisar da senha.
Não sei de nenhum comando mágico para fazer backup de todos os schemas do MySQL "por padrão".
Por exemplo, criei este script pra resolver o seu (e o meu) problema:
#!/bin/bash

read -p "Input the desired MySQL user for backup: " USER
export USER=${USER}

if [ -z "${USER}" ];
then
exit
fi

read -p "Input specified user password: " PASSWORD
export PASSWORD=${PASSWORD}

if [ -z "${PASSWORD}" ];
then
exit
fi

export MYSQL_BACKUP_DIR="/backups/mysql"
mkdir -p ${MYSQL_BACKUP_DIR}/`date +%Y/%m/%d`

#rm "$MYSQL_BACKUP_DIR/*gz" > /dev/null 2>&1

databases=`mysql -h 127.0.0.1 -P3306 -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`

for db in $databases; do
    if [[ "$db" != "information_schema" ]] && [[ "$db" != "performance_schema" ]] && [[ "$db" != "mysql" ]] && [[ "$db" != _* ]] ; then
        echo "Dumping database: $db"
        mysqldump -h 127.0.0.1 -P3306 -u $USER -p$PASSWORD --databases $db > ${MYSQL_BACKUP_DIR}/`date +%Y/%m/%d`/$db-`date +%Y-%m-%d`.sql
        gzip ${MYSQL_BACKUP_DIR}/`date +%Y/%m/%d`/$db-`date +%Y-%m-%d`.sql
        tar -cvf ${MYSQL_BACKUP_DIR}/`date +%Y`.tar ${MYSQL_BACKUP_DIR}/`date +%Y`
    fi
done

unset PASSWORD;
unset USER;

Agora, explico. Para que o usuário e senha não fiquem armazenados no histórico do shell (e não precisar usar hacks como colocar espaço na frente do comando, que não é garantia de nada ou outras técnicas fora de padrão ou mesmo ficar contando com a memória em apagar o bash_history) fiz com o que toda vez que o script fosse executado, ele solicita o usuário e a senha a serem usados (no caso opto pelo root que vai enxergar todos os schemas) e define o local onde os backups serão salvos, neste caso /backups/mysql.
Ele cria as pastas e organiza o backup por YYYY-MM-DD, compacta com a ferramenta gunzip e depois cria os archives maiores (que no meu caso é importante) separados por ano pra poder fazer um download simples do ano todo. Ele sobrescreve os arquivos, não otimiza o uso de espaço e comete alguns outros possíveis pecados que pra mim não são relevantes.
No final do script você pode ver que ele descarta os valores das varíaveis que armazenavam o usuário e senha, em uma tentativa de manter isso o mais seguro possível dentro do escopo simples do script.
Se você não quiser digitar isso todas as vezes, provavelmente sua única solução é armazenar em plain text dentro do script e guardar isso no disco. Mas já podemos todos imaginar que essa idéia não é muito legal...
DISCLAIMER: USE AT YOUR OWN RISK.
Vale ressaltar a parte mais importante disso tudo:
databases=`mysql -h 127.0.0.1 -P63306 -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`

for db in $databases; do
    if [[ "$db" != "information_schema" ]] && [[ "$db" != "performance_schema" ]] && [[ "$db" != "mysql" ]] && [[ "$db" != _* ]] ; then
        echo "Dumping database: $db"
        mysqldump -h 127.0.0.1 -P3306 -u $USER -p$PASSWORD --databases $db > ${MYSQL_BACKUP_DIR}/`date +%Y/%m/%d`/$db-`date +%Y-%m-%d`.sql
        gzip ${MYSQL_BACKUP_DIR}/`date +%Y/%m/%d`/$db-`date +%Y-%m-%d`.sql
        tar -cvf ${MYSQL_BACKUP_DIR}/`date +%Y`.tar ${MYSQL_BACKUP_DIR}/`date +%Y`
    fi
done

Aqui ele pega o nome de todos os schemas (que é claro, têm sua visibilidade afetada pelo usuário cujas credenciais estão sendo usadas pela ferramenta), depois faz um loop e exclui os possíveis schemas que você não quer incluir no backup, mais notavelmente os schemas protegidos ou padrões do MySQL. A partir dessa lista final ele então faz um mysqldump para cada schema e salva/compacta conforme explicado anteriormente.
Importante lembrar: O usuário root ao que me refiro nessa resposta em nenhum momento é o root do sistema operacional, e sim o do banco de dados. Achei importante ressaltar isso para os visitantes da internet que podem passar por aqui no futuro.


text:
Q: Is it possible to convert an int to an array while using njit(numba)? I wondering if it is possible to convert an int to an array whilst using njit in numba?  Sorry if this is a simple question, I am new to the library and looking to learn more about it.
I have tried the following:
import numpy as np
from numba import njit

    @njit
    def top(f):
        if f =="TRUE":
             t = 0
             for i in range(10):
                  t = t+1
             t = np.array(t)
             return t

    top("TRUE")

but get the following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/numba/dispatcher.py", line 401, in _compile_for_args
    error_rewrite(e, 'typing')
  File "/usr/lib/python3/dist-packages/numba/dispatcher.py", line 344, in error_rewrite
    reraise(type(e), e, None)
  File "/usr/lib/python3/dist-packages/numba/six.py", line 668, in reraise
    raise value.with_traceback(tb)
numba.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Cannot unify int64 and array(int64, 0d, C) for 't', defined at <stdin> (4)

File "<stdin>", line 4:
<source missing, REPL/exec in use?>

[1] During: typing of assignment at <stdin> (7)

File "<stdin>", line 7:
<source missing, REPL/exec in use?>

A: You probably should not change the type of your variable within a numba function (similar as why you would not be able to do so in a C function). This seems to work:
@njit
def top(f):
    if f =="TRUE":
        t = 0
        for i in range(10):
            t = t+1
        return np.array([t])


text:
Q: Regex to allow only whitespace, letters and certain characters I need to allow only whitespace, letters, numbers and . , ! ? ( ) $ % *
I got something like this:
/[a-zA-Z0-9\s\.\*\(\)\?]/$

A: Your syntax is incorrect, the end of string $ anchor should be placed inside of the delimiters. You also need to precede your character class with a quantifier and anchor the entire pattern.
The following regular expression will allow the specified characters.
/^[a-zA-Z0-9\s.,!?()$%*]+$/


text:
Q: How to disable the unselected checkboxes and change the css class for selected checkboxes only using Angular 12 and Typescript? I have stored checkboxes dynamically using json array of object. What I need is, I have to select only 5 checkboxes. If my selection is reached 5, then I have to disable the unchecked checkboxes and change the css only for unchecked checkboxes only. I tried but when the selection is reached 5 I am not able to change the class to that unselected checkboxes.

        {{item.title}}

    {{ sublist.menu }}

    <input type="checkbox"
    [(ngModel)]="sublist.selected"
    [disabled]="disableCheckbox(sublist)"
    (change)="changeSelection($event, sublist)"

    style="display:none;">

component.ts file
private _jsonURL = 'assets/menus.json';

public getJSON(): Observable<any> {
 return this.http.get(this._jsonURL);
}

[{"title":"one",
"submenus": [
    {
        "id":1, "menu": "home", "selected": false
    },
    {
        "id":2, "menu": "about", "selected": false
    },

]

},

{"title":"two",

"submenus": [
    {
        "id":1, "menu": "Status", "selected": false
    },
    {
        "id":2, "menu": "Balance", "selected": false
    },

]
},

]

checkboxList = [];
public maxElementCheckbox = 5;

changeSelection($event, item){

if ($event.target.checked) {

  this.checkboxList.push(item);

 }

else {

  this.checkboxList.splice(this.checkboxList.indexOf(item), 1);
  console.log("esle part");
}
console.log(this.checkboxList);
}

 public disableCheckbox(id): boolean {

return this.checkboxList.length >= this.maxElementCheckbox && !this.checkboxList.includes(id);

}

A: If its not 100% necessary that the checkboxes will be disabled after the limit of 5 is reached, you could add a counter to your changeSelection function and highlight a error message to the user, if the limit is reached.
If it is fundamental for you to disable the checkboxes one first idea in my mind could be using something like a selector for all checkbox elements without an active attribute with .querySelectorAll('.specificClassForTheCheckboxes'); or give your checkboxes an id to select them specific on the attribute selected with the value false.

A: I don't find any condition in your ngClass for checking the unselected checkboxes after selecting 5 check boxes. That should help:
HTML:

    = maxElementCheckbox && !sublist.selected ? 'submenulist_label' : 'submenulist_label_checked'">

        <input
          type="checkbox"
          [(ngModel)]="sublist.selected"
          [disabled]="disableCheckbox(sublist)"
          (change)="changeSelection($event, sublist)"/>
          {{sublist.menu}}

TYPESCRIPT:
menuList = [
    {
      title: 'one',
      submenus: [
        {
          id: 1,
          menu: 'home',
          selected: false,
        },
        {
          id: 2,
          menu: 'about',
          selected: false,
        },
      ],
    },

    {
      title: 'two',

      submenus: [
        {
          id: 1,
          menu: 'Status',
          selected: false,
        },
        {
          id: 2,
          menu: 'Balance',
          selected: false,
        },
        {
          id: 3,
          menu: 'Test1',
          selected: false,
        },
        {
          id: 4,
          menu: 'Test2',
          selected: false,
        },
        {
          id: 5,
          menu: 'Test3',
          selected: false,
        },
      ],
    },
  ];

  checkboxList = [];
  public maxElementCheckbox = 5;

  changeSelection($event, item) {
    if ($event.target.checked) {
      this.checkboxList.push(item);
    } else {
      this.checkboxList.splice(this.checkboxList.indexOf(item), 1);
    }
  }

  public disableCheckbox(id): boolean {
    return (
      this.checkboxList.length >= this.maxElementCheckbox &&
      this.checkboxList.indexOf(id) == -1
    );
  }

CSS:
.submenulist_label {
  color: red;
}

Here's a running demo.


text:
Q: How can I access a nested JSON attribute in python? How do I access the description field in my request payload?
REQUEST PAYLOAD:
data = { "other_details" :{
            "my_story":true,
            "preferences":false,
            "profile_photo":false,
             },
             "experience_detail":[
                        {
                        "description":"Location: Indan\nCurrent job
                         responsibilities:\n\n• To manage, interpret,
                         and integrate inspection and function test data associated
                         with pressure relief
                         devices\n• Collection and Managing the database of
                         inspection/test records\n",
                        "employer_name":"Wood Group",
                        "end_date": "2020-04-28",
                         "id": "30dbe99d0c55435ea3d5119ece0ac873",
                         "is_current_employer": true,
                         "job_title": "Integrity Engineer",
                         "start_date": "2013-11-25"

                         },
                         {
                        "description":"Location: Indian\nCurrent job
                             responsibilities:\n\n• To manage, interpret,
                             and integrate inspection and function test data
                             associated with pressure relief devices\n•
                             Collection and Managing the database of
                             inspection/test records\n",
                         "employer_name":"QUESS CORP.",
                         "end_date": "2020-04-28",
                         "id": "30dbe99d0c55435ea3d5119ece0ac873",
                         "is_current_employer": true,
                         "job_title": "Integrity Engineer",
                         "start_date": "2013-11-25"
                         }
             ]
       }

I tried a few ways, but they didn't work.
Attempt 1:
def index():
    data = json.loads(request.data)
    clean_description = (data['other_details']
                             ['experience_detail']['description'])

Output:
clean_description = (data['other_details']['experience_detail']['description'])
**TypeError**: list indices must be integers or slices, not str

Attempt 2:
def index():
    data = json.loads(request.data)
    clean_description = (data['other_details']['experience_detail'])

Output:
[
   {
      "description":"Location: Australia\nCurrent job responsibilities:\n\n• To manage, interpret, and integrate inspection and function test data associated with pressure relief devices\n• Collection and Managing the database of inspection/test records\n• Pressure Relief Device (PRD) Inspection Report review/approval and recommendation\n• Compliance check on inspection reports in accordance with the scope and approve and/or send for re-review\n• Database management using Meridium, SAP and other Document Control Databases",
      "employer_name":"Wood Group",
      "end_date":"2020-04-28",
      "id":"30dbe99d0c55435ea3d5119ece0ac873",
      "is_current_employer":true,
      "job_title":"Integrity Engineer",
      "start_date":"2013-11-25"
   },
   {
      "description":"Location: Australia\n\nResponsibilities:\n• Experience in pressure relief device sizing and selection\n• Exposure to Upstream Facilities Engineering activities\n• Experience with SharePoint for document management\n• Experience with Meridium",
      "employer_name":"Jacobs Engineering",
      "end_date":"2013-10-25",
      "id":"7d8afe3cadaa4aee842bb4d8b000f5c7",
      "is_current_employer":false,
      "job_title":"Integrity Engineer",
      "start_date":"2011-11-25"
   }
]

It is displaying all the fields but I just need the description field.
Image of payload:


text: Q: How to implement my own backup agent in android I know there's the Android class BackupAgent class which allow users to backup and restore only their own apps data. However, I'm looking for a way to take over the Android's default backup and restore functionality and allow a user to choose a different cloud storage for data backing up and restoration. Furthermore, I need to backup all the stored data in the device.


text:
Q: How to Display Both Text and Check box on same Line in ChecklistBox I have used CheckListBox Control to Display List of Items. I want to Display both text and check box on same line but for Larger text it breaks down Text into next line like this

My Aspx Tag :
<asp:CheckBoxList ID="ChkLstProducts" runat="server" DataTextField="ProductName" DataValueField="ProductId" CssClass="productsf" Width="300"></asp:CheckBoxList>

CSS code:
.productsf {
    font-family: 'Segoe UI';
    font-size: 10px;
    overflow:hidden;
    text-overflow: ellipsis;
    color: #000;
    cursor: pointer;
    display:list-item
}


text:
Q: Декодировка письма Gmail Python Хочу прочитать последнее письмо которое мне пришло на прочту с помощью imaplib, Но тема и текст письма зашифрованы, как расшифровать?
Текст что мне выдает и сам код снизу
('none none', 'Тут почта от кого пришла')
Wed, 28 Jul 2021 00:36:09 +0300
=?UTF-8?B?0J3QvtCy0LDRjyDQt9Cw0Y/QstC60LAg4oSWMzY3ODk0MTE=?=
<CAAzzXJgMW=tfFRHKs+5eBujcphzfs67pBv5bnNPfO58deAJrFA@mail.gmail.com>

Код
import imaplib
import email

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('***', '***')

mail.list()
mail.select("inbox")

result, data = mail.search(None, "ALL")

ids = data[0]
id_list = ids.split()
latest_email_id = id_list[-1]

result, data = mail.fetch(latest_email_id, "(RFC822)")
raw_email = data[0][1]
raw_email_string = raw_email.decode()

email_message = email.message_from_string(raw_email_string)

print(email.utils.parseaddr(email_message['From']))
print(email_message['Date'])
print(email_message['Subject'])
print(email_message['Message-Id'])

Заранее спасибо.

A: Попробуйте указать политику default в message_from_string (согласно ответу)
from email import policy
...

email_message = email.message_from_string(raw_email_string, policy=policy.default)

Пример:
from email import policy
import email

raw_email_string = """\
From: aperson@dom.ain
To: bperson@dom.ain
Subject: the next line has a space on it
\x20
Date: Mon, 8 Apr 2002 15:09:19 -0400
Message-ID: spam

Here's the message body
"""

email_message = email.message_from_string(raw_email_string, policy=policy.default)
print(email.utils.parseaddr(email_message['From']))
print(email_message['Date'])
print(email_message['Subject'])
print(email_message['Message-Id'])
print(email_message.get_payload())

Результат:
('', 'aperson@dom.ain')
Mon, 08 Apr 2002 15:09:19 -0400
the next line has a space on it
spam
Here's the message body


text:
Q: NuGet restore failed JetBrains Package When I build my .NET Solution in Jenkins and try to restore NuGet packages before the actual MSBuild step I'm getting this error:
C:\Program Files\dotnet\sdk\2.1.300\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(198,5): error : Package JetBrains.Annotations, version 11.1.0 was not found. It might have been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which might have been due to maximum path length restrictions. [PATHLENGHT = 86]

I'm using MSBuild 15 and NuGet Windows x86 Commandline nuget.exe v4.7.0
Any ideas?
Cheers

A: Since this was a .Net Standard Project, i need to add this command to make it a successful build:
/t:restore


text:
Q: Lower bound of mixing times I want to prove that for any Markov Chain we have

$t_{mix}>\max_{x,A}\left(\pi(A)-\displaystyle\frac{1}{4}\right)E_x(\tau_A)$

I wanted to used that if $P_x(\tau_A\leq t)\geq \alpha $ for any $x$ in the state space then $E(\tau_x)>t_0/\alpha $. This does not work
Could anyone give a hint to solve this problem
Thanks!

A: Firstly, your lemma is false. The true lemma is if there exists some $t_0>0$ and $0<\alpha<1$ such that $\mathbb{P}_x(\tau_A \leq t_0) \geq \alpha$, then $\mathbb{E}_x(\tau_A) \leq \frac{t_0}{\alpha}$.
Your idea works. Note that $\mathbb{P}_x(\tau_A \leq t_{mix}) \geq P^{t_{mix}}(x,A)$. On the other hand $\left |{P^{t_{mix}}(x,A)-\pi(A)}\right |\leq d(t_{mix})<\frac{1}{4}$, which implies $P^{t_{mix}}(x,A)>\pi(A)-\frac{1}{4}$. Then $\mathbb{P}_x(\tau_A \leq t_{mix})>\pi(A)-\frac{1}{4}$. If $\pi(A)-\frac{1}{4}\leq 0$, the inequallity that we want to prove is obvious. If $\pi(A)-\frac{1}{4}>0$, we will use your lemma to say that $\mathbb{E}_x(\tau_A) \leq \frac{t_{mix}}{\pi(A)-\frac{1}{4}}$, which implies $t_{mix} \geq \left(\pi(A)-\frac{1}{4} \right)\mathbb{E}_x(\tau_A)$, and finally we maximize the right part over all $x \in \Omega$ and $A \subseteq \Omega$, and we finish the proof.


text:
Q: reducint the template noise from gdb I have read a number of questions regarding this issue, but the most recent answer I found was dated 2012, so I'm wondering if things have changed in the meantime.
When print output for a std container for example, the signal to noise ratio is poor for out of the box gdb.  What is the current state-of-the-art or best practices for improving the signal to noise ratio?  I'd like a low level of detail by default, but optionally be able to turn on a higher level as needed.


text:
Q: How to create array of multiple template objects I have templated class "Factory". The proto-type of factory is something as follows:
template <class T>
class Factory
{
    public:
    Factory();
    ~Factory();

    //few more functions & data-members

    private:
    //few more functions & data-members
};

In the main() I make multiple types of Factories as in --
int main()
{
    typedef Factory<int> IntFactory ;
    IntFactory A = IntFactory();

    typedef Factory<float> FloatFactory ;
    FloatFactory B = FloatFactory();

    //Complex is some user defined class
    typedef Factory<Complex> ComplexFactory ;
    ComplexFactory C = ComplexFactory();

    //Point3D is a user defined class
    typedef Factory<Point3D> Point3DFactory ;
    Point3DFactory D = Point3DFactory();

    //I may have several such initializations.

}

The question is how do I make an array of objects A,B,C,D incase I want
to iterate through them?

A: The best I think you can do, (off the top of my head and not tested) is:
class FactoryBase
{
    public:
        virtual ~FactoryBase() = 0;
};

template <class T>
class Factory : public FactoryBase
{
    //...
};

int main()
{
    std::vector<FactoryBase*> factories;
    factories.push_back(new Factory<int>);
    factories.push_back(new Factory<Complex>);
    //... Make sure you delete these. Better yet, use a smart pointer.
    return 0;
}

Note a vector of pointers, and all that push_back(new ...) stuff is very vulnerable to exceptions and leaks...

A: (An alternative if you don't want to use the base class approach)
typedef boost::variant<IntFactory, FloatFactory, ...>  FactoryType;

std::vector<FactoryType> vFactories;

Then use a visitor to execute and methods...
Linking the documentation for variant.

A: There are many ways to do what you want to... each one has the pros and cons...
In case you know all the instances during compiling time, this approach works fine:
Includes
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/container/vector.hpp>

Functor
struct do_whatever
{
    template<typename T>
    void operator()(T& t) const
    {
        ...
    }
};

Instantiation and iteration over the vector
boost::fusion::vector<IntFactory, FloatFactory, ComplexFactory, Point3DFactory> vv(A, B, C, D);
boost::fusion::for_each(vv, do_whatever());


text:
Q: Is it a good idea to use a const pointer to FILE type? Normally, C file I/O is done using FILE* as this is what the standard library functions all take.
In C, one can also have a const pointer, where the address of the pointer cannot change (but the value it points to can be).
I wondered if this could be applied to FILE*, so wrote this small program to test this:
#include <stdio.h>

int main(void) {
    FILE* const file = fopen("somefile.txt", "w");
    if (file != NULL) {
        fprintf(file, "%s\n", "So this works? That's just swell!");
    }
    return 0;
}

This compiles fine and works as intended on Ubuntu/Linux 16.04 using GCC (the file contains exactly the string I expected), but I'm not sure if this idiom is such a good idea —the FILE type is opaque by design and handling of it is implementation-specific.
Because there's no guarantee that any C library implementation won't try and change the address of the FILE pointer, is it safer to not use this approach when doing I/O in C?

A: Converting comments into an answer as requested.
You can use FILE * const sanely; you cannot use const FILE * sanely. There's a guarantee that none of the functions in the C library will modify the pointer part of the FILE * you pass to them in any way detectable by the calling code, because the pointer is always passed by value — never the address of the pointer. So there is no way for the calling code to modify your pointer — unless it goes to insanely complex steps in order to do so, and it won't because there is neither any need nor any benefit to doing so.

I'm aware of the difference between FILE * const and const FILE * (as well as why the latter doesn't make any sense). In my question I am seeking to clarify whether making the pointer const will have any negative impact on the standard library functions, as they don't take const pointers in their prototypes.
Also, for context of why I'm looking to do this — the same reasons why one might make any other pointer const: to stop an accidental re-assignment of what it points to.

It can't have any effect on the functions in the library; they are passed a copy of the value, and they won't modify the value, but won't be aware that the original value is non-modifiable anyway, and won't care. Using FILE * const fp = fopen(…); simply means you can't reuse that file pointer for anything else in the same function (or retry opening a different file name or calling a different 'open' function), and you can't reset it to NULL after you fclose() it.  Of course, if the pointer goes out of scope because it is inside a loop, it can be reused when the scope is re-entered.
Otherwise, using FILE * const has no effect. I don't think it's useful. It isn't harmful except that it does nothing beneficial (and might confuse people).  I recommend against using FILE * const.


text:
Q: devise: "Reset password token is invalid" message I'm using devise 2.0.4 and cannot find where the "Reset password token is invalid" message is defined.  I would have thought it was in the locales YAML file but it is not. I've also searched the gem source to no avail, which leads me to think that it must be constructed at run time.  In the devise_error_messages! method I see that it must be defined as one of the full_messages for the resource, but being somewhat of a rails newbie I'm not sure where to look for that.

A: Put this in your config/locales/en.yml
en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            reset_password_token:
              blank: "is not valid"
              invalid: "is not valid"

A: The "Reset password token is invalid" message is not defined anywhere.
It is generated dynamically by the full_message method in Rails Active Model Errors
The example from the docs:
    company.errors.full_message(:name, "is invalid")  # =>
      "Name is invalid"


text:
Q: Countifs using multiple dynamic arrays as criteria I have a countifs formula that seems to be letting me down.
It's using 2 different criteria and both are dynamic arrays - here represented by the cell ref and the hashtag:
COUNTIFS(A:A,B1#,C:C,D1#)

The dynamic arrays in cells B1 and D1 are working fine, and if I change the countifs so only 1 of the criteria refers to a dynamic range (removing the hashtag and selecting 1 of the results in the array) then it works fine. The problem is when I need it to use 2 (or more?) dynamic ranges.
Any thoughts?

A: if the items are independent of each other as in B1 does not directly correlate to D1 and B2 directly correlates to D2 then you need to Transpose one of the arrays.
=COUNTIFS(A:A,B1#,C:C,TRANSPOSE(D1#))

Note:
This will create a 2D array with as many rows as in B1# and as many Columns as in D1#.  So to get the total wrap it in SUM or SUMPRODUCT.
Also, The max independent arrays are two.
Also that it is an AND situation so the value in A must be equal to the a value in B and the value in C in the same row, must be equal to a value in D

If one wants more than two we need to move away from countifs and use array type formula which will require the use of ranges that encompass the most rows that would be used and not full columns.
=SUMPRODUCT(ISNUMBER(MATCH(A1:A100,B1#,0))*ISNUMBER(MATCH(C1:C100,D1#,0)))

This version is AND like the COUNTIFS where the values in A and C on the same row must exist their corresponding lists to be counted.  IF you want to count them individually then change the * to + which makes it an OR.
And the use of ISNUMBER(MATCH(A1:A100,B1#,0)) can be added as many as desired changing the ranges as necessary.

A: Edit: This will not work, see below comment by @Scott Craner
I'm unsure if COUNTIFS work well with dynamic arrays, which is what you are currently using.
A workaround can be to try use SUMPRODUCT
=SUMPRODUCT((A:A=B1#)*(C:C=D1#))


text:
Q: search for a number in another column I have a large dataset, in it, Column A has an ID, and in Column B (texts with ID). I want Column C to display if the value exists or not if exists then leave the cell blank if not then show the number which should be in the cell.

The IDs will start from the first left (as shown in the screenshot).
I used the "=REGEXMATCH(B2:B(A2:A))" but it didn't work.
Thank you

A: Try the following formula-
=MAP(A2:A4,B2:B4,LAMBDA(x,y,IF(REGEXMATCH(y,x&"")=FALSE,X,"")))

To refer full column as input to MAP() function, use-
=MAP(A2:INDEX(A2:A,COUNTA(A2:A)),B2:INDEX(B2:B,COUNTA(A2:A)),LAMBDA(x,y,IF(REGEXMATCH(y,x&"")=FALSE,X,"")))


text:
Q: is it possible to cross compile (with uclibc toolchain) a program which uses a shared library that causes 'undefined reference to printf@GLIBC_2.0' I'm cross compiling a SDK for an embedded board using pre-built mips-linux-uclibc- toolchain. While compiling a set of sources that makes use of libom_api.so library causes an error "undefined reference to `printf@GLIBC_2.0'" and 10 other symbols like getpid@GLIBC2.0. In Makefile they have passed -lom_api along with some other app specific libraries.
Is it because libom_api.so is compiled using Glibc compiler? how can I resolve this issue? SDK doesn't have sources of libom_api.so.
What I tried: I built a Glibc cross-toolchain with buildroot and passed $(LDGLIBC) to compiler after -lom_api in Makefile (LDGLIBC = -L$(ROOTDIR)/glibc-toolchain/GLIB), still causing error.

A:
is it possible to cross compile (with uclibc toolchain) a program which uses a shared library that causes 'undefined reference to printf@GLIBC_2.0'

No.

Is it because libom_api.so is compiled using Glibc compiler? how can I resolve this issue?

Yes. More precisely, libom_api.so has been compiled using GLIBC headers and linked against GLIBC implementation of the standard C library.
Your only choices are:

*

*obtain a different version of libom_api.so, one built against uClibc, or

*eliminate dependency on libom_api, or

*use GLIBC for your entire project


text:
Q: Try to kill a spawn process with shell true and detached true nodejs I am trying to write a simple node.js application in order to run selenium in a dedicate shell and then close the shell and the corresponding child process (at the moment after a timeout of 5 seconds in order to test it).
Here the code I have so far:
const spawn = require('child_process').spawn;
const seleniumHub = spawn('java', ['-jar', 'selenium-server-standalone-2.48.2.jar'], { shell: true , detached: true });

seleniumHub.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
});

seleniumHub.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
});

seleniumHub.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});

setTimeout(function () {
    // process.kill(seleniumHub.pid); no errors but shell not closed
    // seleniumHub.kill('SIGINT'); completely ignored
}, 5000);

Selenium correctly runs, but I am not able to close the opened shell.
If I try to close it through its pid, I get an error that the pid doesn't exist.
If I try to call the kill method on the child process, it completely ignores the command.Any suggestion please?
Thanks
p.s. I am on a Windows machine

A: OK I found the solution myself and I am posting it here if it can be useful for someone.
As workaround I used again spawn and called the taskkill of Windows, passing f and t as parameters:
spawn("taskkill", ["/pid", seleniumHub.pid, '/f', '/t']);


text:
Q: PHP Warning: include(/var/www/html/....../lib/Cake/Error/ErrorHandler.php): failed to open stream Error I encountered this error when trying to load my webpage.
The path that was showed on the error message was,

PHP Warning:
  include(/var/www/html/test.com/www/products/abc/lib/Cake/Error/ErrorHandler.php):
  failed to open stream:
It wasn't able to locate the Cake library directory as the path should
  be "/var/www/html/test.com/products/abc/lib/Cake/..." instead.

Any idea how I can fix this?
The error was pointing me to line 540 of the Core/App.php file which is,
if ($file = self::_mapped($className, $plugin)) {
        return include $file;   <<---- LINE 540
}
$paths = self::path($package, $plugin);

Thanks!

A: Your CakePHP is trying to include a file just like if you typed
include '/var/www/html/test.com/www/products/abc/lib/Cake/Error/ErrorHandler.php';

As mentioned in the PHP:include-Manual :

The include construct will emit a warning if it cannot find a file

The interesting thing here is that your CakePHP is missunderstanding your root directory, so an idea is that you have installed using a dependency manager such as Composer and moved your project into /var/www/html/test.com/www/ when was originally under the parent directory /var/www/html/test.com/.
In order to make sure, check the file where Cake defines its ROOT directory, which is the root index.php file. If you look inside you'll see something like this:
define('ROOT', dirname(__FILE__)); // <-- ROOT GLOBAL VARIABLE DEFINITION
define('WEBROOT_DIR', 'webroot');
define('WWW_ROOT', ROOT . DS . APP_DIR . DS . WEBROOT_DIR . DS);

It can change with the version of the framework but it should be really similar.
The line that we are looking for is the first one, that means the ROOT global variable from CakePHP is set where the index.php is located.
My theory is that you have moved, deleted or modified the ROOT or other trascendent global variables and CakePHP is not finding the correct path as you posted.
If you need further information comment and I will edit this answer. Also a little bit more of information about your error will be appreciated so I can fit more your needs.
Hope this helped you :)


text:
Q: UILabel doesn't break line I have a UILabel that is supposed to be a multiple lined label, but it isn't. Here's how I did it
[self.lblMessage setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
[self.lblMessage setCenter:self.view.center];
self.lblMessage.textAlignment = NSTextAlignmentCenter;
_lblMessage.lineBreakMode = NSLineBreakByWordWrapping;
_lblMessage.numberOfLines = 0;
[self.view addSubview:self.lblMessage];

A: your are seting
with auto layout see this pic
here i set height Relation greater than or equal 0 . and i fix the width and remember set the number of line = 0.

A: Fixed it. My UILabel height is too short that's why it doesn't display the other lines. Thanks!


text:
Q: Is there a way to launch an executable that doesn't have an executable extension? I have two separate executable files, A.exe & B.dontrun, where A.exe launches B.dontrun after doing some initialization.  The two processes then communicate to each other and A.exe exits after B.dontrun exits.  This all behaves fine using CreateProcess and passing the executable name as the first argument when B.dontrun is named B.exe but if B.dontrun is named anything else (B.ex_ or B.bin) CreateProcess doesn't return an error, but the process isn't launched either.
I'd like B.dontrun to be named something that doesn't encourage people to run it directly, when they look in the directory they see A.exe and B.dontrun and there isn't confusion of which executable that they should be running.

A: At least up till and including Windows XP, the [cmd.exe] command interpreter recognizes a PE executable as such regardless of the filename extension, and runs it.
Which is one reason why it's not a good idea to start a text document with the letters "MZ"... ;-)
And which means that it's not a good idea to try to prevent execution via filename mangling.
Instead, make the other process a DLL, and launch it via rundll32.
Cheers & hth.,

A: You need to specify the exe name in the cmd line argument rather than in the application name.
This works:
  STARTUPINFO info;
  ZeroMemory(&info, sizeof(info)); info.cb = sizeof(info);
  PROCESS_INFORMATION pi;
  ZeroMemory(&pi, sizeof(pi));
  TCHAR sz[1000]; // Note: lpCommandLine must be writable
  lstrcpy(sz,  L"c:\\users\\serge\\desktop\\notepad.dontrun");
  CreateProcess(NULL, sz, NULL, NULL, FALSE, 0, NULL, NULL, &info, &pi);
  printf("Error = %u\n", GetLastError());

This indeed gives a File not found error (2):
  STARTUPINFO info;
  ZeroMemory(&info, sizeof(info)); info.cb = sizeof(info);
  PROCESS_INFORMATION pi;
  ZeroMemory(&pi, sizeof(pi));
  CreateProcess(L"c:\\users\\serge\\desktop\\notepad.dontrun",
    NULL, NULL, NULL, FALSE, 0, NULL, NULL, &info, &pi);
  printf("Error = %u\n", GetLastError());

Note: Tested on Win7 x64

A: You should create the file as hidden.
CreateFile has an attribute you can use
FILE_ATTRIBUTE_HIDDEN 2 (0x2) The file is hidden. Do not include it in an ordinary directory listing.
Documentation here: http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx