text:
Q: Android: Drawing a Transparent Bitmap on Canvas with some color Its Becoming a headache for me , i have a transparent png image,,, i have decoded that into a bitmap and later added on to a canvas,
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), picList[0] , options);
Paint p = new Paint();
canvas.drawBitmap(mBitmap, 0, 0, p);

later on when i am saving the canvas it is showing image but showing the background as black,
to implement white color i have used some codes like
Paint p = new Paint();
p.setAlpha(color.white);
p.setColor(color.white);
canvas.drawColor(color.white);
canvas.drawPaint(p);

but yet the color is not seted white,,,
 kindly help me out ,, i want the backgroung saved image to be white. if there is any other logic i am missing.
thanx helping out.

A: you can call following on your bitmap after drawing on Canvas:
        for(int x=0;x<bitmap.getWidth();x++){
            for(int y=0;y<bitmap.getHeight();y++){
                if(bitmap.getPixel(x, y)==Color.BLACK){
                    bitmap.setPixel(x, y, Color.WHITE);
                }
            }
        }

If you want WHITE bg for your saved image, use WHITE else you can use TRANSPARENT.

A: well i have found out the correct option.
its
    canvas.drawARGB(255,30,30,39);
give the various ARGB values and get color on the canvas
enjoy :D

A: Before creating Paint object call canvas.drawColor(color.white); if this not work go with canvas.drawColor(Color.WHITE, PorterDuff.Mode.DARKEN);

A: You can try using Color.TRANSPARENT instead of Color.white..

A: good!
if your image has bad white (not really (255 255 255)), you can take tolerancy into account
for(int x=0;x<img.getWidth();x++)
{
    for(int y=0;y<img.getHeight();y++)
    {
        int cou = img.getPixel(x, y), tolerancy = 40//max 255, your image would be completely tranpsparent;

        if(Math.abs(Color.red(cou)-255)<tolerancy &&
           Math.abs(Color.green(cou)-255)<tolerancy &&
           Math.abs(Color.blue(cou)-255)<tolerancy)
            paletteFond.setPixel(x, y, Color.TRANSPARENT);
    }
}


text:
Q: How to convert a list of arrays into a 1D scalar array to subset loom file I am working with a loompy file and unfortunately the relevant metadata along which I would like to subset the loom file is located in an external metadata file.
sub_meta = []

for i in marrow_meta2['annotated_cell_identity.ontology'].unique():
    # gets the indices of marrow_meta2['annotated_cell_identity.ontology'] where i is found and assigns
    # it to q, for each i (that is, each unique value in annotated_cell_identity.ontology)
    q = np.where(marrow_meta2['annotated_cell_identity.ontology'] == i)
    # if the length of q is less than 1000, append q to sub_meta
    if len(q) < 1000:
        sub_meta.extend(q)
    elif len(q) > 1000:
        sub_meta.extend(random.sample(q, 1000))

marrow_meta2[sub_meta]

Despite my best attempts, no matter what I do, I seem to get a list of arrays, instead of a list of integers corresponding to the rows of the loom object's matrix that I would like to subset.
I have the R equivalent code to what I want to do. I am using Python because I would like to use scanpy. I am not ruling out using reticulate or simply saving the relevant objects to file and loading them into Python downstream to use scanpy, but I'd like to crack the issue first:
# only select 2k (if possible) of each cell type
sub_meta <- c()
for(c in unique(marrow_meta$annotated_cell_identity.ontology_label)){
  i <- which(marrow_meta$annotated_cell_identity.ontology_label==c)
  if(length(i) < 1000){
    sub_meta <- append(sub_meta, i)
  }
  else{
    sub_meta <- append(sub_meta, sample(i, 1000))
  }
}
sub_meta <- marrow_meta[sub_meta,]

A: .tolist() method of np.ndarray:
q = np.where(marrow_meta2['annotated_cell_identity.ontology'] == i)[0].tolist()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как вызвать метод, при изменении значения переменной Мне нужно вызывать метод, при изменении значения какой либо переменной.
Я знаю самый простой способ - через property.
private int health;
public int Health
{
    get => health;
    set
    {
        health = value;

        //И тут вызывать метод.
    }
}

Но в таком случае, нужно строго использовать объявленный property Health.
Это не очень удобно, так как можно очень легко ошибится и использовать health вместо Health. Поэтому постоянно приходиться держать в голове, что нужно использовать Health.
Я считаю, что должен быть другой способ, попроще, который я не знаю, но надеюсь, что его знаете Вы!

A: private int _health;
public int Health {
  set {
    if (value != _health) {
      _health = value;
      // call method
    }
  }
  get {
    return _health;
  }
}

A: Другой вариант с событиями
class Person
{
    internal delegate void HealthEvent();
    public event HealthEvent OnHealthChanged;
    private int _health;
    public int Health
    {
        set
        {
            if (value != _health)
            {
                _health = value;
                if (OnHealthChanged != null) OnHealthChanged();
            }
        }
        get
        {
            return _health;
        }
    }

}

после создаете экземпляр класса
Person p = new Person();

и подписываете его на ваш метод, это может быть один или несколько методов
p.OnHealthChanged += InformIfHealthChanged;

A: if(value)
{
   //do something

}

Если я правильно понял вопрос


text:
Q: firewalld-cmd remove-rule command in shell script throws error IFS=$'\n'; for i in `firewall-cmd --direct --get-all-rules`; do firewall-cmd --permanent --direct --remove-rule $i && firewall-cmd --reload; done

The above command throws error as
usage: --permanent --direct --remove-rule { ipv4 | ipv6 | eb }
After I enabled shell verbose option, I noticed that the command is as follows:
firewall-cmd --permanent --direct --remove-rule 'ipv4 filter OUTPUT 2 -o ens32 -p udp -m conntrack --ctstate NEW -j ACCEPT'

I am not really sure from where the single quotes around the rule is getting substituted and how to get rid of it.


text:
Q: Is there "a rate of convergence" for the central limit theorem? Let $X_i$ be i.i.d. with zero mean and unit variance. Then according to the central limit theorem $$\frac{1}{\sqrt{n}} \sum \limits_{i=1}^n X_i \to_D \mathcal{N}(0,1),$$
as $n \to \infty$, where $\to_D$ denotes convergence in distribution. Can you say anything about the finite sample properties of the left hand side? Ideally, I would like to say in precise way that the distribution of the LHS is "almost" the RHS.


text:
Q: Не показывается нотификация пользователю Есть приложение, которое отображает пользователю некое уведомление. Нотификация показывается лишь по нажатию на кнопку. Однако, при выполнении даного условия ничего не происходит
Код активити:
class MainActivity : AppCompatActivity() {

    private val CHANNEL_ID = "channel_one"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button_start_notification.setOnClickListener {
            sendNotification()
        }
    }

    private fun sendNotification() {
        val notificationLayout = RemoteViews(packageName, R.layout.notification_layout)
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(getString(R.string.content_title))
            .setSmallIcon(R.drawable.ic_notification_android)
            .setStyle(NotificationCompat.DecoratedCustomViewStyle())
            .setCustomContentView(notificationLayout)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(CHANNEL_ID, "Test Notification",
                NotificationManager.IMPORTANCE_HIGH).apply {
                description = "This notification is for test"
            }
            val notificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            notificationManager.createNotificationChannel(channel)
        }

        with(NotificationManagerCompat.from(this)) {
            notify(0, notification)
        }
    }
}

A: Проблема была в этой части кода:
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)

Скорее всего, кастомизация нотификаций происходит инным путем. Как именно, не известно. Поэтому для работы уведомления указаные строчки я убрал и все начало работать, как нужно.


text:
Q: Looking for a post hoc for a type 2 Anova (mixed-effects model) My question is how do I run a post hoc on a type 2 Anova (mixed-effects model)? So far I am using the glmer() from the "lme4" package, the Anova() from the "car" package, and trying to run a HSD test from the "agricolae" package.
After searching for some time this is the best that I could find, however, I receive an error message when doing so. Does anyone know how to get around this or what I am doing wrong? Or a different way of doing this?
library(lme4)
totaldiversity.model <- glmer(totaldiversity ~ focalspecies + (1|site), family = "poisson", data = data, na.action=na.fail)
library(car)
totaldiv.anova = Anova(totaldiversity.model, type = "II")
library(agricolae)
totaldiv.tukey = HSD.test(totaldiv.anova, "focalspecies", group=TRUE, console=TRUE)

Error message that comes up: Error in HSD.test(totaldiv.anova, "focalspecies", group = TRUE, console = TRUE,  : argument "MSerror" is missing, with no default
Thank you in advance!

A: I followed the link posted by Ben Bolker (Post-hoc test for glmer) which led me to use the glht() function in the multcomp package. This is what the solution looked like for a multiple comparisons analysis (Tukey) on a glmer() mixed effects model, with a type 2 Anova. Need "multcomp", "lme4", and "car" packages.
totaldiversity.model <- glmer(totaldiversity ~ focalspecies + (1|site), family = "poisson", data = data, na.action=na.fail)
summary(totaldiversity.model)
Anova(totaldiversity.model, type = "II")
summary(glht(totaldiversity.model, mcp(focalspecies="Tukey")))

Thanks everyone!

A: From the documentation for HSD.test, y is "model(aov or lm) or answer of the experimental unit". In all likelihood this means you should be sending it totaldiversity.model:
HSD.test(totaldiversity.model, "focalspecies", group=TRUE, console=TRUE)


text:
Q: dplyr and group_by: factor vs no factor (The described behaviour was a bug!)
I do not understand the effect of group_by on columns that are a factor and that are not. The following analyses both possibilities:
library(dplyr)

df <- data.frame(value=seq(1,10), height=c(rep(1,5),rep(2,5)))

# height is no factor
dfs <- df %>% group_by(height) %>% summarize(m=mean(value))
dfs$height==dfs$height[1]

# height is factor
df$height <- as.factor(df$height)
dfs <- df %>% group_by(height) %>% summarize(m=mean(value))

Here, a data frame
   value height
1      1      1
2      2      1
3      3      1
4      4      1
5      5      1
6      6      2
7      7      2
8      8      2
9      9      2
10    10      2

Is summarized by height. When df$height is not a factor, the results looks like this:
  height        m
1      1 4.500000
2      1 3.000000
3      1 2.000000
4      1 1.000000
5      2 9.000000
6      2 6.000000
7      2 8.333333

while if df$height is a factor, the result is what I want:
  height m
1      1 3
2      2 8

Why does something like this happen? My first guess was that it is a numerical issue and non-factor heights differ very slightly. However, the test above shows that all height==1 are equal:
> dfs$height==dfs$height[1]
[1]  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE

Well, ok, I could just use the factor but with that I loose the numerical character of the height. For example, I would like to sort by height or choose the highest height.

A: Based on my understanding of group_by, it works on any variable type, not just factors. Based on https://github.com/tidyverse/dplyr/issues/482 and my own attempts to reproduce, this issue should be closed.


text:
Q: Thread Safety in Jpa Entity Listener class I am using jpa entity listener and spring boot in my project . Before calling update method of spring jpa repository my @PreUpdate method is called and where  I am fetching oldEventObject object before updating the database. But after update to database my @PostUpdate method is called where I am making use of oldEventObject Object to check whether the object state have changed or not . My question is whether oldEventObject  Object is thread safe or not . If not Do i have to make my Listener class Prototype or what should i do to make it thread safe
Entity class
@Entity
@Table(name = "XYZ")
@EntityListeners({XYZPublisher.class})
public class XYZ implements Serializable {}

Listener class
    @Component
    public class XYZPublisher {

      private static final Logger log = LoggerFactory.getLogger(XYZPublisher.class);
final ThreadLocal<XYZ> oldEventThreadLocal=new ThreadLocal<>();

      @Autowired
      private EventPublisher eventPublisher;

      @Autowired
      private EntityManagerFactory entityManagerFactory;

      @Nullable
      public XYZ getOldEventObject() {
        return oldEventObject;
      }

      public void setOldEventObject(@Nullable XYZ oldEventObject) {
        this.oldEventObject= oldEventObject;
      }

      @PreUpdate
      @Transactional(propagation = Propagation.REQUIRES_NEW)
      public void preUpdateEvent(XYZ evenType) {
        if (Objects.nonNull(entityManagerFactory)) {
          EntityManager entityManager = entityManagerFactory.createEntityManager();
          Session session = entityManager.unwrap(Session.class);
          XYZ oldEvent= session.get(XYZ .class, XYZ .getId());
          oldEventThreadLocal.set(oldEvent);
        }
      }

      @PostUpdate
      public void publishUpdateEvent(XYZ newEvent) {
     XYZ oldEvent= oldEventThreadLocal.get();
     timeEventTypeThreadLocal.remove();
        if (Objects.nonNull(eventPublisher) && Objects.nonNull(oldTimeEventType)) {
          List<EntityChangedDataItem> items = new ArrayList<>();
          String newName = newEvent.getName();
          String oldName = oldEvent.getName();
          if (!(Objects.equals(newName, oldName))) {
            EntityChangedDataItem entityChangedDataItem = new EntityChangedDataItem();
            entityChangedDataItem.setAttributeName("name");
            entityChangedDataItem.setOldValue(oldName);
            entityChangedDataItem.setNewValue(newName);
            items.add(entityChangedDataItem);
          }

          if (!(Objects.equals(newEvent.getCode(), oldEvent.getCode()))) {
            EntityChangedDataItem entityChangedDataItem = new EntityChangedDataItem();
            entityChangedDataItem.setAttributeName("code");
            entityChangedDataItem.setOldValue(oldEvent.getCode());
            entityChangedDataItem.setNewValue(newEvent.getCode());
            items.add(entityChangedDataItem);
          }

          if (!(Objects.equals(newEvent.isActive(), oldEvent.isActive()))) {
            EntityChangedDataItem entityChangedDataItem = new EntityChangedDataItem();
            entityChangedDataItem.setAttributeName("active");
            entityChangedDataItem.setOldValue(Boolean.toString(oldEvent.isActive()));
            entityChangedDataItem.setNewValue(Boolean.toString(newEvent.isActive()));
            items.add(entityChangedDataItem);
          }
          publishUpdatedItemsToKafka(items);
        } else {
          log.error(PUBLISHED_ERROR);
        }
      }
    }


text:
Q: $\left |{\prod_{j=1}^{N}\frac{z-a_j}{z+a_j}}\right |\to 1$ when $|z|\to\infty$
Let $H$ be the right half-plane, $a_1,...,a_N>0$ and define $$B_N(z)=\prod_{j=1}^{N}\dfrac{z-a_j}{z+a_j}\quad (z\in H).$$ I want to prove $|B_N(z)|\to 1$ when $|z|\to\infty$.

I think that maybe each factor of $|B_N(z)|$ should tend to $1$ when $|z|\to\infty$. So, fix $j\in\{1,...,N\}$.
Taking squares $$\dfrac{|z-a_j|^2}{|z+a_j|^2}=\dfrac{(\text{Re }z-a_j)^2+(\text{Im }z)^2}{(\text{Re }z+a_j)^2+(\text{Im }z)^2}=\dfrac{(\text{Re }z)^2-2a_j\text{Re }z+a_j^2+(\text{Im }z)^2}{(\text{Re }z)^2+2a_j\text{Re }z+a_j^2+(\text{Im }z)^2}.$$
And we are supposing $(\text{Re }z)^2+(\text{Im }z)^2\to \infty$. However, I can't see why that quotient tends to $1$. Could anyone give me a hint?
Thank you.

A: Using the triangle inequality (both the direct and the converse version) you can prove that if $a>0$ and $z\neq0$ then
$$
\frac{1-a/|z|}{1+a/|z|}\leq\frac{|1-a/z|}{|1+a/z|}\leq\frac{1+a/|z|}{1-a/|z|}.
$$
Now notice that the term in the center of the inequalities is just $\frac{|z-a|}{|z+a|}$, take limits when $|z|\to+\infty$ and conclude with the squeeze theorem.


text:
Q: My git paths are prefixed with a cygdrive path even when in cmd I have git bash installed, and now in the normal Windows CMD when running a command like git clone, the target path gets prefixed with a cygdrive path. How can I fix that?
git clone https://github.com/TencentARC/GFPGAN.git 'C:\ai\gan'
fatal: Invalid path '/cygdrive/c/Users/Felix/C:\ai\gan': No such file or directory

I just realized that this is not even the git version I have installed as "git for windows" (2.29), but rather:
C:\Users\Felix>git --version
git version 2.17.0

C:\Users\Felix>which git
/usr/bin/git

How would I get back a fully normal CMD without any cygwin paths? Even printing $PATH in CMD is full of cygdrive prefixes, which are not actually in the env var.

A: Manually removing cygwin from the harddrive, all env vars, and the registry worked.


text:
Q: Transacción Insert con If Else SQL y C# Estoy desarrollando un programa donde envío un activo que puede o no estar asociado a una habitación. Si no se asocia a una habitación idHabitación = 0, si no contiene la clave primaria de esa habitación. Creé un procedimiento donde valido primero si el activo existe con el número de serie, si no existe, valido si idHabitacion es 0, si lo es hace un insert sin llenar el campo idHabitacion (null), sino si lo llena (llave primaria), pero esto no me está funcionando.
create proc procCrearNuevoActivoPagNuevoActivo
@nomActivo varchar(255),
@numSerie as varchar(255),
@idTipo  int,
@marcaActivo varchar(255),
@modeloActivo varchar(255),
@fechaCompra date,
@fechaVenceGarantia date,
@estadoActivo varchar(255),
@descripcion text,
@idUsuario int,
@idHabitacion int
as
if (not exists(select * from IH_ACTIVOS where numSerie=@numSerie))
    begin
        if (@idHabitacion=0)
        begin
            insert into IH_ACTIVOS(nomActivo, fechaCreacion, numSerie, idTipos, marcaActivo, modeloActivo,
            fechaCompra, fechaVenceGarantia,estadoActivo, descripcion, idUsuario)
            values(@nomActivo,GETDATE(),@numSerie,@idTipo,@marcaActivo, @modeloActivo,
            @fechaCompra,@fechaVenceGarantia,@estadoActivo,@descripcion,@idUsuario)
        end
            else
                begin
                    insert into IH_ACTIVOS(nomActivo, fechaCreacion, numSerie, idTipos, marcaActivo, modeloActivo,
                    fechaCompra, fechaVenceGarantia,estadoActivo, descripcion, idUsuario, idHabitacion)
                    values(@nomActivo,GETDATE(),@numSerie,@idTipo,@marcaActivo, @modeloActivo,
                    @fechaCompra,@fechaVenceGarantia,@estadoActivo,@descripcion,@idUsuario, @idHabitacion)
                end
    end

C#:
 public string procCrearNuevoActivoPagNuevoActivo(Activo objActivo)
        {
            string mensaje = "";
            cn = conexion.getConexion();

            using (SqlTransaction tr = cn.BeginTransaction(IsolationLevel.Serializable))
            {

                SqlCommand cmd = new SqlCommand("procCrearNuevoActivoPagNuevoActivo", cn, tr);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("nomActivo", SqlDbType.VarChar).Value = objActivo.nomActivo;
                cmd.Parameters.Add("numSerie", SqlDbType.VarChar).Value = objActivo.numSerie;
                cmd.Parameters.Add("idTipo", SqlDbType.Int).Value = objActivo.idTipo;
                cmd.Parameters.Add("marcaActivo", SqlDbType.VarChar).Value = objActivo.marcaActivo;
                cmd.Parameters.Add("modeloActivo", SqlDbType.VarChar).Value = objActivo.modeloActivo;
                cmd.Parameters.Add("fechaCompra", SqlDbType.Date).Value = objActivo.fechaCompra;
                cmd.Parameters.Add("fechaVenceGarantia", SqlDbType.Date).Value = objActivo.fechaVenceGarantia;
                cmd.Parameters.Add("estadoActivo", SqlDbType.VarChar).Value = objActivo.estadoActivo;
                cmd.Parameters.Add("descripcion", SqlDbType.Text).Value = objActivo.descripcion;
                cmd.Parameters.Add("idHabitacion", SqlDbType.Int).Value = objActivo.idHabitacion;
                cmd.Parameters.Add("idUsuario", SqlDbType.Int).Value = objActivo.idUsuario;

                try
                {
                    int i = cmd.ExecuteNonQuery();
                    if (i== 1)
                    {
                        mensaje = "Se ingresó " + i + " nuevo activo";
                        tr.Commit();
                    }
                    else {
                        mensaje = "El número de serie " + objActivo.numSerie + " ya existe en inventario !";
                    }

                }
                catch(Exception e)
                {
                    mensaje = "Error en el registro del activo: "+e;
                    tr.Rollback();
                }
                finally
                {
                    cn.Close();
                }
                return mensaje;
            }
        }

Diagrama:

Lo que quiero en el procedimiento almacenado es básicamente:
" SI Activo no existe entonces, si idHabitacion=0 entonces inserte todo menos idHabitación (queda null), sino entonces inserte todo (con idHabitaion = valor correspondiente).
El problema es que cuando guardo un activo con un nuevo número de serie, por ejemplo sk123, este se guarda pero me indica que "El número de serie  sk123 ya existe en inventario !" en lugar de dicirme "Se ingresó 1 nuevo activo" que sería lo correcto.
Lo que creo que pasa es que se están ejecutando ambos update y no está obedeciendo los If Else que puse para validar @idHabitacion.
A veces me pasa que aparece un mensaje de interbloqueo lo cual no debería pasar, lo que me hace pensar que se ejecutan ambos update.
Quedo atento. Gracias !

A: Dejando de lado la pésima idea de pasar toda la lógica a la "capa de negocios", te recomiendo que no confíes en el conteo de filas ya que puede tener inconsistencias en su comportamiento. De hecho, la recomendación general es deshabilitar el conteo de filas al momento de llamar los procedimientos desde la aplicación mediante el uso de SET NOCOUNT ON. Una opción que tienes, es la de generar un error desde tu procedimiento que sea capturado por el TRY de tu código en C#.
CREATE PROCEDURE procCrearNuevoActivoPagNuevoActivo(
    @nomActivo varchar(255),
    @numSerie as varchar(255),
    @idTipo  int,
    @marcaActivo varchar(255),
    @modeloActivo varchar(255),
    @fechaCompra date,
    @fechaVenceGarantia date,
    @estadoActivo varchar(255),
    @descripcion text,
    @idUsuario int,
    @idHabitacion int
)
AS
SET NOCOUNT ON;

IF (NOT EXISTS(SELECT * FROM IH_ACTIVOS WHERE numSerie = @numSerie))
BEGIN
    INSERT INTO IH_ACTIVOS(
            nomActivo,
            fechaCreacion,
            numSerie,
            idTipos,
            marcaActivo,
            modeloActivo,
            fechaCompra,
            fechaVenceGarantia,
            estadoActivo,
            descripcion,
            idUsuario,
            idHabitacion
    )
    VALUES(
            @nomActivo,
            GETDATE(),
            @numSerie,
            @idTipo,
            @marcaActivo,
            @modeloActivo,
            @fechaCompra,
            @fechaVenceGarantia,
            @estadoActivo,
            @descripcion,
            @idUsuario,
            NULLIF( @idHabitacion, 0)
    );
END
ELSE
    RAISERROR(  '¡El número de serie %s ya existe en inventario !', 11, 1, @numSerie);
GO

No tengas miedo de usar espacio suficiente para mejorar la lectura de tus procedimientos almacenados. También recuerda utiliza el principio DRY (Don't Repeat Yourself / No te repitas).
Aun mejor, sería que la tabla IH_ACTIVOS tuviera un UNIQUE CONSTRAINT en la columna numSerie para no necesitar la validación inicial y todo quedaría en un simple INSERT y capturas el error para regresar el mensaje deseado en vez del mensaje por default.
ALTER TABLE IH_ACTIVOS ADD CONSTRAINT UQ_IH_ACTIVOS_NumSerie UNIQUE ( numSerie);


text:
Q: How to give only "Add content" access permission for a particular users in drupal 7? Please help me for this question(How to give only "Add content" access permission for a particular users in drupal 7 ?)

A: Create a new User Role and give Add Content permission to that Role. Then assign particular user to that role. Now that user can able to add content only.
Steps:
Go to administration -> people
Click Permission tab.
Give Role name like "Editor" and click Add Role
After Creation, click Edit Permission against new created role and give the required permissions.


text:
Q: Matlab file concatenation I have data files that look like this
2 FP1 0 9.064
2 FP1 1 6.622
2 FP1 2 4.669
2 FP1 3 3.693
2 FP1 4 3.693
2 FP1 5 3.693
2 FP1 6 4.181
2 FP1 7 4.181
2 FP1 8 5.157
2 FP1 9 6.134
2 FP1 10 7.111
2 FP1 11 7.111
2 FP1 12 5.646
2 FP1 13 4.669
2 FP1 14 3.693
2 FP1 15 4.181

there are several of these files and I want to concatenate all the files with such data; I used the following :
d=dir('*.m');  % get the list of files
x=[];            % start w/ an empty array
for i=1:length(d)
x=[x; load(d(i).name)];   % read/concatenate into x
end
save('newfile.m',x)

However, I get the following error,
 Error using load
  Unknown text on line number 1 of ASCII file co2a0000364.rd.002.m
 "FP1".

How can I concatenate all of the data from all of the files and include the characters FP1 etc?

A: Using load() to read data from a textfile is wrong. With load() one loads saved Matlab variables. Use importdata()
https://de.mathworks.com/help/matlab/ref/importdata.html
Or check out the following options
https://de.mathworks.com/help/matlab/import_export/ways-to-import-text-files.html


text:
Q: Databinding ListView including its columns I have a list of objects where each contains an arbitary number of parameters (name,value pairs). Now I want to bind the list of objects to a listview. Each column should represent a parameter (the column header is the name of the parameter) and each row an object with the list of parameter values. How can achive that the columns including its header names are created via databinding based on the parameter names? Note that the number of parameters may differ from object to object so the the column item must be lft blank sometimes.

A: By parameters you mean properties?
If yes, then this might help:
I think the databinding engine will take the first object and use that as representant for all the others.
So your list will have all columns like properties from the first object.
To achieve your desired result, you should

*

*Create a dummy object that has all possible properties

*Insert that as first item in the list

That should work...
Use reflection, when you use c#
:-)


text:
Q: Store value of subquery in update for later use Trying to calculate % change of price. Query below works, but was hoping there was a way that I didn't have to call the same subquery first? I don't think WITH works here unless I'm mistaken.
update changes rt1
    set change = coalesce((rt1.price - (SELECT
        price
      FROM clothing_price
      WHERE changes.id = clothing_price.id AND clothing_price.timestamp > NOW() - INTERVAL '24 HOURS'
      ORDER BY timestamp ASC
      LIMIT 1) / (SELECT
        price
      FROM clothing_price
      WHERE changes.id = clothing_price.id AND clothing_price.timestamp > NOW() - INTERVAL '24 HOURS'
      ORDER BY timestamp ASC
      LIMIT 1)), 0)
where clothing_type = 1;

A: (After fixing the invalid reference) The query burns down to:
UPDATE changes rt1
SET    change = CASE WHEN (
   SELECT cp.price
   FROM   clothing_price cp
   WHERE  cp.id = rt1.id   -- fixed reference!
   AND    cp.timestamp > now() - interval '24 hours'
   ORDER  BY cp.timestamp
   LIMIT  1) IS NULL THEN 0 ELSE rt1.price - 1 END
WHERE  clothing_type = 1;

That aside, to "store" the result of a correlated suquery, would have to self join to another instance of the updated table changes in a USING clause. But that seems to be moot now ...

A: Forgive the speculation, but I'm going to try answering the question using a different strategy.
First, I think the OP was asking about a regular CTE. In PostgreSQL you can use a CTE to feed data to an UPDATE. In my answer, I'm going to find the reference price in a CTE (the "stored value", as OP called it in the question title).
Second, the OP's query is likely missing the predicate AND rt1.id = clothing_price.id in the final WHERE. As written, it will change every change field with clothing_type=1. I assume that each id in changes was supposed to have its own change field filled in.
Applying these assumptions, I wrote the following query, and accompanying fiddle with sample table definitions and data:
WITH cte AS (
    SELECT t.id,t.mints,clothing_price.price
    FROM (
       SELECT id,
          min(timestamp) FILTER (WHERE timestamp > now() - interval '24 hour') AS mints
       FROM clothing_price
       GROUP BY id
    ) t
    LEFT JOIN clothing_price
    ON (clothing_price.id=t.id and clothing_price.timestamp=t.mints)
)
UPDATE changes SET change = coalesce((changes.price - cte.price)/cte.price,0)
FROM cte
WHERE changes.clothing_type=1 AND changes.id=cte.id;

Notes:

*

*cte.price is the reference ("old") price from clothing_price and changes.price is the incoming ("new") price change.

*changes.change will be positive on price increase, negative on price decrease, and zero if prices are all the same, a price is missing, or all prices have expired.

*Used a LEFT JOIN so ids with expired prices get zeroed by COALESCE.


text:
Q: Convert TTL levels to RS232 of FTDI USB<->Serial Have this small interface FTDI FT232RL to connect a Serial device to the computer via USB.

It has been working well for most of my Serial applications, except today when I tried to use it for a Roboteq controller. While all settings are correct, characters are garbage.
The support tells me the FTDI device use TTL levels (0~3.3/5V) instead of RS232 (-9~+9V). Which seems to be unfortunately correct according to the FTDI doc.
Question

Is there a simple way to have this FTDI device consider RS232 levels, not TTL? (eg like shorting a couple of pins) The Roboteq device doesn't seem to be configurable in this regard.

A: If you want to talk over USB it would be far faster and easier to just buy one of the many USB->RS232 converter cables than to mess around making that into one. I've seen them for as low as $7 USD online.
There are even cables with the FTDI chips in them so if you've been using the D2XX library you can continue doing so.

A: Simple answer: No! You need a level converter, something like a Maxim MAX232 IC to convert from TTL (0-5V) to RS232 (+/-12V ish) signals


text:
Q: Trying to understand and translate a small bit of VB code I'm in the middle of transferring some VB code to another language, but I don't understand what's supposed to be happening here.
Dim foo(7,0) as Date

Then later in the code I get something like foo(5,3) and I believe the output to be a Date object.  There is no function written to describe foo so I'm assuming it's a multi-dimensional array.  But cast as a Date?  I'm confused, please help.

A: I don't know what's going on their either, because this:
Dim foo(7,0) as Date

declares a two dimensional array that is effectively a one dimensional array because the second dimension has an upper bound of 0...
... and then you claim that the second dimension is later indexed with 3, which is outside the bounds. foo(5, 0) would be fine, but the sixth row (if you want to think of the 5 that way) has 1 column, so retrieving the fourth is an IndexOutOfRangeException. Presumably this has been ReDim'd at some point between then and now
To have the debugger help you out, run the code, stop on it and point to foo or look in the LOCALS window:

Bounded in red is the variable analyzer as a tooltip and in the locals. It shows Date to be a 2D array. It also helpfully lists all the contents. Bounded in blue is the error you get if you try and access index 3 of an array that stops at index 0
Make that 2D array actually have an appreciable width:

And you can see it's just a block of Date


text:
Q: MemoryStream not writing data from datatable I have datatable that I'm populating with data and passing through to a method which is supposed to write the data to a memory stream and save it as an Excel spreadsheet. The datatable is correctly populated, but when the memorystream writes it, the capacity of the memorystream is 0. It's as though it just doesn't write anything. Could this be caused by some sort of memory leak? Below is my code that I use to write the workbook (populated by the datatable) using the memorystream
    public static MemoryStream Grid_Export_Excel(DataTable data)
    {
        try
        {
            var workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet();
            var headerRow = sheet.CreateRow(0);

            // Set the column names in the header row
            for (int i = 0; i < data.Columns.Count; i++)
                headerRow.CreateCell(i).SetCellValue(data.Columns[i].ColumnName);

            // Freeze the header row so that it's not scrolled
            sheet.CreateFreezePane(0, 1, 0, 1);

            for (int r = 0; r < data.Rows.Count; r++)
            {
                // Create a new row
                var row = sheet.CreateRow(r + 1);

                // Get the DataRow
                var dataRow = data.Rows[r];

                for (int c = 0; c < data.Columns.Count; c++)
                {
                    // Get the fieldname
                    var fieldname = data.Columns[c].ColumnName;

                    // Make sure that the field exists in the datarow
                    if (!dataRow.Table.Columns.Contains(fieldname))
                        continue;

                    // Create the cell in the row
                    row.CreateCell(c).SetCellValue(dataRow[fieldname].ToString());
                }
            }

            // Write the workbook to a stream and return as FileStreamResult
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            return ms;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }


text:
Q: CentOS 8 does not resolve DNS Here is the very strange issue with freshly installed CentOS 8.0
I configured static IP with nmcli which essentially using NetworkManager. So turning it of is not an option as I want to follow RedHat's standard way of managing the system.
Here is some info:
#ping google.com
ping: google.com: Name or service not known

Contents of
/etc/sysconfig/network-scripts/ifcfg-enp14s0
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=enp14s0
UUID=d64e6ca1-c30d-41ea-a4bb-49445d89aac4
DEVICE=enp14s0
ONBOOT=yes
IPADDR=18.25.16.249
GATEWAY=18.1.0.1
PREFIX=19
DNS1=18.0.70.160
DNS2=18.0.72.3

cat /etc/resolv.conf
# Generated by NetworkManager
nameserver 18.0.70.160
nameserver 18.0.72.3

ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp14s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 2c:fd:a1:c6:d6:a5 brd ff:ff:ff:ff:ff:ff
    inet 18.25.16.249/19 brd 18.25.31.255 scope global noprefixroute enp14s0
       valid_lft forever preferred_lft forever
    inet6 fe80::9864:a2af:89e8:e78d/64 scope link noprefixroute
       valid_lft forever preferred_lft forever
3: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 2c:fd:a1:c6:d6:a4 brd ff:ff:ff:ff:ff:ff

pinging any IP directly work just fine
ping 172.217.7.14
PING 172.217.7.14 (172.217.7.14) 56(84) bytes of data.
64 bytes from 172.217.7.14: icmp_seq=1 ttl=54 time=6.30 ms
64 bytes from 172.217.7.14: icmp_seq=2 ttl=54 time=6.30 ms
64 bytes from 172.217.7.14: icmp_seq=3 ttl=54 time=6.30 ms
64 bytes from 172.217.7.14: icmp_seq=4 ttl=54 time=5.82 ms

I have rebooted and stopped NetworkManger no dice here. DHCP works but I need a static IP. What is going on here?


text:
Q: Angular New files not creating So i typed ng new my_app and a dialog box comes like this.If anyone knows how to fix this problem please tell me about itenter image description here

A: You typed mg instead of ng. mg is a text-editor.


text:
Q: jsp - how can I out.println from within the head of an jsp page? I have a website that Im trying to start - but I stored all of the information in a database.  What I want to do, is create the page directly from the data in the database.
What Im struggling with is writing a database query to grab the page title from the database, and plop it into the  tag area.
Only when I open the database, and out.println the value to appear within the  tag, nothing appears on the page in the title area.  There are no page errors, I access the database successfully in the remaineder of the document...
is there something special I need to do to make this work?
thanks

A: Your result set might be returning empty title that is why you can't see otherwise, you should be able to view it or try <%=titlex %> beside println. Also, try to print the result to your log and try not to use System.out.println method because this does not all the time print to the log and instate use logger class methods like info or warning. Write a debugging line in page body too.  If this doesn't work than definitely you not properly reading from the database or not writing DB value to an object if there is any.


text:
Q: 2d Game Sprite's Position goes to -2147483648 in X and Y axis when it reaches a point So I'm starting with a really basic AI which I will expand later on but this problem is giving me a headache. The enemy is supposed to go to the top middle of the screen if the player is in the bottom, and go to the bottom middle if the player is at the top. It should then stay there while shooting at the player until destroyed. Enemies avoid collisions with each other in a jerky way but that's not really related. Here's the code:
for (n = 0; n < upgrades.size(); n++)
    {
        for (inner = 0; inner < upgrades.size(); inner++)
        {
            if (n != inner && upgrades[n]->HitTest(upgrades[inner]))
            {
                upgradeCollide = true;
                if (upgrades[n]->GetX() < upgrades[inner]->GetX())  upgrades[n]->SetPosition(upgrades[n]->GetX() - 10, upgrades[n]->GetY());
                else if (upgrades[n]->GetX() > upgrades[inner]->GetX()) upgrades[n]->SetPosition(upgrades[n]->GetX() + 10, upgrades[n]->GetY());
                else if (upgrades[n]->GetY() < upgrades[inner]->GetY()) upgrades[n]->SetPosition(upgrades[n]->GetX(), upgrades[n]->GetY() - 10);
                else if (upgrades[n]->GetY() > upgrades[inner]->GetY()) upgrades[n]->SetPosition(upgrades[n]->GetX(), upgrades[n]->GetY() + 10);
                upgradeCollide = false;
            }
        }
        upgradeVX = 400 - upgrades[n]->GetX();
        if (player.GetY() >= 300) upgradeVY = 150 -  upgrades[n]->GetY();
        else if (player.GetY() < 300)  upgradeVY = 450 -  upgrades[n]->GetY();
        //Above 3 lines is the enemy seeking the position
        upgradeLength = sqrt(upgradeVX * upgradeVX + upgradeVY * upgradeVY);
        upgradeVX = upgradeVX / upgradeLength * 100;
        upgradeVY = upgradeVY / upgradeLength * 100;
        //Above is normalization of the velocity vector (VX, VY)
        enemy_rotation = atan2(upgrades[n]->GetY() - player.GetY(), upgrades[n]->GetX() - player.GetX()) * (180/3.14159);
        upgrades[n]->SetRotation(enemy_rotation-90);
        if (!upgradeCollide) upgrades[n]->SetVelocity(upgradeVX, upgradeVY);
}

So it should be seeking two different points depending on where the player is. Strange thing is that it works just fine if I don't normalize the velocity vector, but of course it must be normalized otherwise it would look weird and be unfair.
Keep in mind when an enemy reaches the target and collides because another enemy is already there, it will just push it to the left or right and make enough space (That is only if I don't normalize because otherwise they travel a million pixels - with normalization)
So does anyone know why they are traveling an insane amount of pixels when they hit one of the two targets? I just want them to stop at the target and shoot the player.


text:
Q: How can I combine these two regex expressions? (Words with and without apostrophes) I am trying to build a regex to capture every word in a string (including apostrophe) such as the following:
Despite trying and trying I haven't found a regex to capture all these words

I do however want it to ignore words like ''', and read word from words', and cause from 'cause; i.e. the apostrophe must be within the text.
I have the following two expressions:
[a-z]+'[a-z]+
[a-z]+

I am assuming they can be joined by a simple operator, but I can't find out what that operator might be.

A: In Python you can use this alternation based regex to match all words with single quote inside and ignore 'word1 word2' words:
s = r"Despite trying and trying I haven't found a regex to capture all these words 'but not capturing these'"

print filter(None, re.findall(r"'[^']*'|(\b\w+(?:'\w+)?\b)", s))
//=> ['Despite', 'trying', 'and', 'trying', 'I', "haven't", 'found', 'a', 'regex', 'to', 'capture', 'all', 'these', 'words']

RegEx Demo

A: Try this:
(\w+'\w+)|(\w+)

The above still includes words' and 'cause but without the apostrophe.

A: This regex will catch all words that can optionally contain (even multiple) ' inside them, but not starting or ending with '
(\w[\w']+\w|\w+)

See a demo here

A: Using a group and "?" is elegant and should be the fastest implementation.  The following expression is not limited to python but works in any tool that accepts Extended Regular Expressions.  I am also not sure what you want to do with numbers (another reason "\w" is not used in the answer):
[A-Za-z]+('[A-Za-z]+)?
$ str="Despite trying and trying I haven't found a regex to capture all these words... 'cause"
$ echo "$str" | sed -r "s/[A-Za-z]+('[A-Za-z]+)?/MATCH/g"
MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH... 'MATCH
$ echo "$str" | awk "{ gsub(/[A-Za-z]+('[A-Za-z]+)?/,\"MATCH\") } 1"
MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH MATCH... 'MATCH

Here is the nice diagram from www.debuggex.com ...

Debuggex Demo
The Basic Regular Expression adds a couple \'s:
[A-Za-z]\+\('[A-Za-z]\+\)\?
If you have POSIX character classes:
EXTENDED:
[[:alpha:]]+('[[:alpha:]]+)?
BASIC:
[[:alpha:]]\+\('[[:alpha:]]\+\)\?


text:
Q: How can I create a pivot table from a resampled column? Suppose I have event data like:
ts,uid
2016-02-13 20:18:03.000001 UTC,5236965070
2016-02-13 23:05:08 UTC,2834437228
2016-02-13 23:13:00.000032 UTC,2206245130
2016-02-13 22:45:07.000004 UTC,1539535012
2016-02-13 23:47:44 UTC,3431025028
2016-02-13 16:42:16.000001 UTC,810825324
2016-02-13 22:37:14 UTC,2625355144
2016-02-14 00:31:52.000009 UTC,24815453
2016-02-12 06:43:40.000007 UTC,3895095040
2016-02-14 00:09:04 UTC,715095136
...

How can I create a pivot table of the uid to the event count in the hour? I tried doing

DF.groupby(['uid', pandas.TimeGrouper(key='ts', freq='h')], sort=False).count()

but I got ValueError: items in new_categories are not the same as in old categories. How can I get it to work? Is using pivot or pivot_table a better approach?

A: It's better to access the hour from the timestamp using dt.hour (if your column isn't datetime already, convert it using pd.to_datetime):
In [90]: df.groupby([df.uid,df.ts.dt.hour]).count()
Out[90]:
               ts
uid        ts
24815453   0    1
715095136  0    1
810825324  16   1
1539535012 22   1
2206245130 23   1
2625355144 22   1
2834437228 23   1
3431025028 23   1
3895095040 6    1
5236965070 20   1

Note that the groupby "consumes" the uid column; if you want to avoid this you can use as_index = False.


text:
Q: Define symbol to linked Swift framework While writing iOS apps in Xcode, we may need to break down the project into smaller modules/frameworks that build independently, but within the same Xcode workspace.
Now, we have multiple targets, like QA, Staging and Prod, which have defined symbols, like QATarget, and StagingTarget to enable us to conditionally compile the code in the main target.
However, I am not aware of a good approach to pass those symbols down to the linked frameworks? I understand that we need to add a compiler flag to define those symbols, but is there a way to automatically inherit those flags in the sub-projects without dealing with build configuration ugliness (target based instead)?


text:
Q: Shell script to compare file names(without extension) in a directory My requirement is I will have xml and pdf files like pairs.(e.g.,file1.xml, file1.pdf and file2.xml,file2.pdf) in same folder.
I need to check for xml files which are not having pdf pair and move them to different folder.(e.g., if file3.xml doesn't have file3.pdf, I need to move it to different folder).
Please answer me the shell script to do get this functionality done.

A: You can remove the extension using parameter expansion:
#! /bin/bash
for file in *.xml ; do
    if [[ ! -f ${file%.xml}.pdf ]] ; then
        mv "$file" folder/
    fi
done


text:
Q: Meteor UglifyJS error when trying to compile in production Trying to upload to Galaxy causes the error so I am debugging with the following:
meteor --settings settings-dev.json --production
While minifying app code:
  eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:1545:18: SyntaxError: Unexpected token: punc ())
  at new JS_Parse_Error (eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:1545:18)
  at js_error (eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:1553:11)
  at croak (eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:2089:9)
  at token_error (eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:2097:9)
  at unexpected (eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:2103:9)
  at expr_atom (eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:2618:13)
  at maybe_unary (eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:2792:19)
  at expr_ops (eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:2827:24)
  at maybe_conditional (eval at <anonymous>
  (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1),
  <anonymous>:2832:20)

  * Many more lines of same kind of stuff*

=> Your application has errors. Waiting for file change.

Which really gives me no starting point as to what's causing the problem. There is a running issue on GitHub but no progress so far.
I tried to dig deeper and did the following in my Terminal
alias uglifyjs=~/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/bin/uglifyjs
find lib client -type f -name \*.js|while read file;do uglifyjs -o /dev/null $file;done

Which comes back with
  Parse error at client/main.js:1,7
  SyntaxError: Unexpected token: string (/imports/startup/client)
  Error
   at new JS_Parse_Error (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:1545:18)
   at js_error (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:1553:11)
   at croak (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2089:9)
   at token_error (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2097:9)
   at unexpected (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2103:9)
   at semicolon (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2123:56)
   at simple_statement (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2314:73)
   at eval (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2183:19)
   at eval (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2136:24)
   at eval (eval at <anonymous> (/Users/sergiy/.meteor/packages/standard-minifier-js/.1.2.1.1ldi2wj++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/minifier-js/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2904:23)

My main.js file looks like this:
import '/imports/startup/client';
Still can't figure out what the issue is since that is the syntax Meteor suggests in their docs. Removing the standard-minifier-js packages fixes the problem but that's not the best way to go around it so I was hoping there was a fix!

A: There is no harmony support on UglifyJS stable yet as of 2.7.5.
On https://github.com/mishoo/UglifyJS2 there is a harmony and a harmony-v2.7.5 branch though. Support for modules there isn't fully implemented yet as of today and harmony support is still experimental although many features have been implemented already.

A: Turns out there was an issue with an NPM package (ClipboardJS) I was importing in one of my components. Removing it and adding the script to my <head></head> fixed the issue. I'd rather have a minified app with an external src than a non-minified app.


text:
Q: How to use safearea at the Appbar? So I was trying to make an appbar that has an image and text, but the image got cropped because I use the safe area widget. Anyone know the solution? i have tried to use

bottom:false

at the safe area widget

here is the code:
 title: SafeArea(
          bottom: false,
          child: Row(
            children: [
              Container(
                height: deviceData.height * 0.05,
                width: deviceData.width * 0.10,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(100),
                    image: DecorationImage(
                        image: NetworkImage(
                          "https://cdn.popbela.com/content-images/post/20190314/cover-526b71db133e78000df9ead475e858f1_750x500.png",
                        ),
                        fit: BoxFit.cover)),
              ),
              SizedBox(width: 10),
              Container(
                height: deviceData.height * 0.05,
                width: deviceData.width * 0.3,
                child: Text("Nadine Amizah",
                    style: GoogleFonts.poppins(
                        color: Colors.black,
                        fontSize: 15,
                        fontWeight: FontWeight.w500)),
              )
            ],
          ),
        )),

A: I found the solution by using toolbarheight at the appbar


text:
Q: C++ dynamic_cast - polymorphic requirement and downcasting In the following code, while constructing obj in case 1, we construct a derived class object too, but its member functions are just inaccessible to obj. So while downcasting (i.e., in case 2), using obj as source, we have the constructed derived in it already. Why would obj need to be polymorphic?
If I confused you with my above description, why doesn't obj need to be polymorphic when upcasting, but while downcasting it does need to be polymorphic while using dynamic_cast?
class base
{
public:
    base()
    {
        cout<< " \n base constructor \n";
    }
};

class derived : public base
{
public:
    derived()
    {
        cout << " \n derived constructor \n";
    }
};

base *obj = dynamic_cast<base*> (new derived); // case 1: explicitly upcasting
derived *OBJ = dynamic_cast<derived*> (obj);   // case 2: error

A: From 5.2.7/1 [expr.dynamic.cast] :

The result of the expression dynamic_cast<T>(v) is the result of converting the expression v to type
  T.
[...]
If T is "pointer to cv1 B" and v has type "pointer to cv2 D" such that B is a base class of D, the result is a
  pointer to the unique B sub-object of the D object pointed to by v.
[...]
Otherwise, v shall be a pointer to or an lvalue of a polymorphic type.

The standard even provides the following example which illustrates that the polymorphic type requirement does not stand for derived to base conversion :
struct B {};
struct D : B {};
void foo(D* dp)
{
    B* bp = dynamic_cast<B*>(dp); // equivalent to B* bp = dp;
}

A: In order for dynamic_cast to work the object needs to be polymorphic. The reason for this is that dynamic_cast needs somewhere to store the type information that is will use to perform the cast, and it does this by storing the information alongside the vtable for the class. In order for there to be a vtable you need to make at least one of your methods virtual.
The easiest way around this is to flag the base class destructor as virtual.
Upcasting (ie derived to base) doesn't needs a cast as the compiler is able to check that the cast would work at compile time. However, the same isn't true when downcasting.

A: Dynamic_cast

*

*It is used to cast a base pointer
into a derived pointer. If the base
pointer doesn't point to an object of
the type of the derived, it returns

*It is used to cast a base reference
into a derived reference. If the
reference isn't pointing to an object
of the derived, it throws
std::bad_cast.

*It can be considered the checked cast
equivalent to static_cast, in that it
checks whether the object pointed to
really is of the derived type.

You must read more about Dynamic_cast (with example) there.

A: B* b = new D();
D* d = dynamic_cast<D*>(b);

In the above example most compilers would implement dynamic cast by checking whether the vtable pointer of b points to the vtable of the derived class D or not.
If yes, it simply returns the address of b as the return value otherwise it returns a nullptr.
This is what possibly goes on behind the scenes when a dynamic cast executes :-
class car
{
    public:
    virtual void drive()
    {
         std::cout <<"car"<<std::endl;
    }
};
class toyota: public car
{
    public:
    virtual void drive()
    {
        std::cout <<"toyota"<<std::endl;
    }
};

class honda: public car
{
    public:
        virtual void drive()
    {
        std::cout <<"honda"<<std::endl;
    }
};

template <typename Tderived>
Tderived* dynamicCast(void* pBase)
{
    //compare the vptr of the class pointed by pBase with a temporary Tderived class.
    //If vptr of pBase and vptr of Tderived() are pointing to the same vtable
    //then it can be safely deduced that pBase is indeed pointing to an instance of Tderived
    if (*(int**)pBase == *(int**)&Tderived())
    {
        return (Tderived*)pBase;
    }
    else
    {
        return nullptr;
    }
}

int main()
{
    car* pCar;
    honda hondaCar;
    toyota toyotaCar;

    pCar = &toyotaCar;

    honda* pHonda = dynamicCast<honda>(pCar);
    if (nullptr != pHonda)
    {
        pHonda->drive();
    }
    else
    {
        toyota* pToyota = dynamicCast<toyota>(pCar);
        if (nullptr != pToyota)
        {
            pToyota->drive();
        }
    }
}

Now, if the class is not polymorphic, there is no way for the compiler to find whether pCar is pointing to honda or toyota car. Note that this is just one of the ways to implement dynamic_cast as the C++ standard does not talk anything about vtables.


text:
Q: Embeddable overlay chat for websites I want to create embeddable HTML/JS code that would add a chat feature to a website.
Preferably, the chat should be "overlaid" over the rest of the website (like facebook/google hangouts chatboxes).
I know of QuickBlox: it provides a chat feature in javascript but I will have to write the UI code by hand.
Even some pointers on how to get it done is greatly appreciated.
EDIT:
I found services like: zopim, zoho chat and others. It seems pretty common. Is there a library (like on github) for such services?
EDIT:
I want to implement multiple chat boxes. I cannot find a out of the box solution to this, but I am thinking of combining the backend of QuickBlox with some javascript (jQuery probably) front-end to communicate with the QuickBlox library. Are any of these useful? Or anything else I could follow to make one myself.

A: Considering the fact that this is very easy doable with CSS and that you probably want to style the box anyways, I would not recommend using somthing external here. You just need to set the div which contains to position: fixed and then you can control where it appears with bottom: 0 and right: 0 to put it in the bottom right corner for example. Then give it a z-index: 100 for example and you are done with a basic overlay.


text:
Q: Dynamicaly pick the change from drool file at runtime | without maven I am very very new to Drool, please forgive me if I have made any foolish mistake below. I am currently working on an application which is Ant based (migrating to maven is a high risk). I am trying to upgrade the drool version from 4.0.7 to 6.5.0. I want to dynamically get the updated version of the .drl file at runtime of java code so that I don't need to build the java files every time. Here is my below code.
DroolsPoc.java
package com.test;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.kie.api.KieServices;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;

public class DroolsPoc {

    private static AtomicBoolean isRulesChangeScanerStarted = new AtomicBoolean(
            false);

    public static void main(String[] args) throws InterruptedException {

        Map<String, Object> input = new HashMap<String, Object>();

        input.put("input", new Dto());

        KieServices ks = KieServices.Factory.get();

        KieFileSystem kfs = ks.newKieFileSystem();
        kfs.write(ResourceFactory.newFileResource(new File("C:/Users/workspace1/Drools_POC/src/poc.drl")));
        ks.newKieBuilder(kfs).buildAll();

        KieContainer kieContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId());

        KieSession kieSession = kieContainer.newKieSession();
        kieSession.insert(input);
        System.out.println("Fired all rules 1");
        kieSession.fireAllRules();

        System.out.println(((Dto) input.get("input")).getName());

        Thread.currentThread().sleep(20000);

        /*The updated rule should get printed by below code*/
        KieSession kieSession1 = kieContainer.newKieSession();
        kieSession1.insert(input);
        System.out.println("Fired all rules 2");
        kieSession1.fireAllRules();

        System.out.println(((Dto) input.get("input")).getName());

    }

}

Dto.java
package com.test;

public class Dto {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

poc.drl
import java.util.Map;
import java.util.HashMap;
import com.test.Dto;

function Boolean checkIfNull(Map input){

  Dto dto = (Dto)input.get("input");

  if (null == dto.getName()){
      return true;
  }

      return false;

}

function void setName(Map input){

  Dto dto = (Dto)input.get("input");

  dto.setName("The moon is out");

}

rule "PopulateNameInDto"
dialect "mvel"
when
    map : HashMap() eval
    (
    checkIfNull(map)
    )
then
    setName(map);
end

The code is running fine, the only problem is, when the thread sleeps for 20 seconds, in DroolsPoc.java file at line Thread.currentThread().sleep(20000);, then I am updating the poc.drl file from "The moon is out" to "The sun is out". So I am expecting this change to reflect when the program again runs after sleep.
Any help would be appreciated, Many Thanks in advance.

A: I fear you have to redo more than just the KieSession if you want the change to show up.
After sleep(..) you probably need to redo everything from line
ks.newKieBuilder(kfs).buildAll();

A: It seems I had to recreate the service object and again import the file.
worked but this way is not optimal.
Thread.currentThread().sleep(20000);
Map<String, Object> input1 = new HashMap<String, Object>();
input1.put("input", new Dto());
KieServices ks1 = KieServices.Factory.get();
KieFileSystem kfs1 = ks1.newKieFileSystem();

kfs1.write(ResourceFactory.newFileResource(new File(
        "C:/Users/workspace1/Drools_POC/src/poc.drl")));
ks1.newKieBuilder(kfs1).buildAll();
KieContainer kieContainer1 = ks.newKieContainer(ks.getRepository()
        .getDefaultReleaseId());

KieSession kieSession1 = kieContainer1.newKieSession();
kieSession1.insert(input1);
System.out.println("Fired all rules 1");

kieSession1.fireAllRules();
System.out.println(((Dto) input1.get("input")).getName());


text:
Q: Set height and width of two div element hardcore and display: inline-block also given same margin I have set height and width of two div element hardcore having class dices and also set display to inline-block and given same margin. I have put 6 div inside in one of them, having class dots which having fixed height and width, but that div moved slightly downwards why it is happening as it should remain in its position. And I also remove default margin.
<!DOCTYPE html> -->

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="dicegame.css">

    <title>Document</title>

        Referesh Me

Player 1

Player 2

A: The problem seems to lie with the way inline-block is interpreted.
Making the parent element dice use a flex wrap aligns the two dices elements vertically:

<!DOCTYPE html> -->

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="dicegame.css">

  <title>Document</title>

    Referesh Me

Player 1

Player 2


text:
Q: Difference between array types - PHP Is there a difference between this syntax of array?
coming from a dd()
$array:3 = [
  0 => "email"
  1 => " email"
  2 => " email"
]

vs
$array = ['email', 'email', 'email']
I am doing this:
$email->bcc($bccEmailsArray); which is the 1st code snippet, and it doesn't work. If I put in the 2nd code snippet, it works.

A: Like what others are saying your problem is just syntax. because of dd() it appears? dd() var_dump() etc are for debugging.
$array:3 = [     // :3 is not valid
  0 => "email"   //no commas
  1 => " email"  //no commas + extra spaces in emails
  2 => " email"  //no commas + extra spaces in emails
]

Correct it to :
$array = [
  0 => "email",
  1 => "email",
  2 => "email",
]

or to either of these :
$array = [0=>"email",1 => "email",2 => "email"];
$array = array(0=>"email", 1=>"email", 2=>"email");

or just to:
$array = array("email","email","email");

as this will just produce default keys:
array(3) {
  [0]=>
  string(5) "email"
  [1]=>
  string(5) "email"
  [2]=>
  string(5) "email"
}

Hence there is no difference between the two if the syntax is correct.
More information:

*

*https://www.w3schools.com/php/php_arrays_multi.asp
https://www.w3schools.com/php/php_arrays.asp
https://www.tutorialspoint.com/php/php_arrays.htm

*https://laraveldaily.com/echoing-dd-vs-var_dump-vs-print_r/

A: The main difference if fact that first sample is not valid PHP code.
Part array:3 makes it invalid.
Valid examples would be
$array = [
  0 => "email",
  1 => "email",
  2 => "email"
];

and
$array = ['email', 'email', 'email'];

Beside the fact that in first example some "emails" start with space both arrays are equals. If you don't provide keys explicitly, elements will be numbered starting from 0.
For more info you can refer to documentation.


text:
Q: Express that, for a given property value, a property with the same name should exist using json schema? I'm trying to validate json files which have an element that has a property which contains a value that should exist in another part of the json. I'm using jsonschema Draft 07.
This is a simple little example that shows the scenario I'm trying to validate in my data.
{
  "objects": {
    "object1": {
      "colorKey": "orange"
    }
  },
  "colors": {
      "orange": {
          "red": "FF",
          "green": "AF",
          "blue": "00"
      }
  }
}

How can I validate that the 'value' of colorKey (in this case 'orange') actually exists as a property of the 'colors' object? The data isn't stored in arrays, just defined properties.

A: For official JSON Schema...
You cannot check that a key in the data is the same as a value of the data.
You cannot extract the value of data from your JSON instance to use in your JSON Schema.
That being said, ajv, the most popular validator, implements some unofficial extensions. One of which is $data.
Example taken from: https://github.com/epoberezkin/ajv#data-reference
var ajv = new Ajv({$data: true});

var schema = {
  "properties": {
    "smaller": {
      "type": "number",
      "maximum": { "$data": "1/larger" }
    },
    "larger": { "type": "number" }
  }
};

var validData = {
  smaller: 5,
  larger: 7
};

ajv.validate(schema, validData); // true

This would not work for anyone else using your schemas.


text:
Q: If no user input (in C) I am thinking, I want to write a code where if no user input then do something else. i.e when I ask for the input and the user doesn't input anything he presses enter then the code does something else..
I have tried several ways in C but can't seem to work, it keeps waiting for the user input even after pressing enter.. I will appreciate a little help
Here is what I have tried so far:
int input[2];
int i=0;

while(i<2){
    scanf("%d", &input[i]);
    if (input[0] == NULL){
        break;
    }
    i++;

}

On the null part I have tried several other stuffs like '\0' '\n' nothing works... What am I forgetting or misunderstanding?

A: As suggested by other people, input a line of text (getline or fgets) and parse it (sscanf). This might be a better practice in the general case too (when the user must enter data), because it always reads the whole line of input, while scanf reads only a part of the line, leaving the rest in the input buffer.
int input[2];
char* line = NULL;
size_t size = 0;

...

getline(&line, &size, stdin);
if (sscanf(line, "%d%d", &input[0], &input[1]) == 2)
{
    // do what you need with the input
}
else
{
    // user didn't supply data - do something else
}

Note that getline allocates some memory dynamically; if you use it, you should free the memory correctly.
char* line = NULL;
size_t size = 0;

...

getline(&line, &size, stdin);

...

free(line);

Using dynamic memory allocation is not trivial; you might want to ask a separate question if you're not sure you did it right. The code examples above are a bit lazy (don't check for EOF and NULL) and can be improved.


text:
Q: Is there a way to get dplyr's bind_cols to expand number of rows like in cbind? From ?dplyr::bind_cols:

This is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one

However, with example data:
tmp_df1 <- data.frame(a = 1)
tmp_df2 <- data.frame(b = c(-2, 2))
tmp_df3 <- data.frame(c = runif(10))

The command do.call(cbind, list(tmp_df1, tmp_df2, tmp_df3)) produces:
   a  b         c
1  1 -2 0.8473307
2  1  2 0.8031552
3  1 -2 0.3057430
4  1  2 0.6344999
5  1 -2 0.7870753
6  1  2 0.9453199
7  1 -2 0.6642231
8  1  2 0.9708049
9  1 -2 0.7189576
10 1  2 0.9217087

That is, rows of tmp_df1 and tmp_df2 are recycled to match the number of rows in tmp_df3.
In dplyr:
> bind_cols(tmp_df1, tmp_df2, tmp_df3)
Error in eval(substitute(expr), envir, enclos) :
  incompatible number of rows (2, expecting 1)

The reason why I want to do something like this is because I am in a situation similar to below:
df_normal_param <- df(mu = rnorm(10), sigma = runif(10))

df_normal_sample_list <- lapply(1:10, function(i)
                         with(df_normal_param,
                              data.frame(sam = rnorm(100, mu[i], sigma[i]))

and I wish to attach the arguments used to create each entry of df_normal_sample_list to the outputs, e.g.
df_normal_sample_list <- lapply(1:10, function(i)
                         cbind(df_normal_param[i,], df_normal_sample_list[[i]]))

A: You argue in a comment that this behavior is safe, I strongly disagree. It seems safe, for this very particular case, but it is likely to cause you problems somewhere down the road. Which is why I believe that the answer to your stated question ("Is there a way to get dplyr's bind_cols to expand number of rows like in cbind?") is a simple: no, and they probably built it that way intentionally.
Instead, I would suggest that you be more explicit in your approach, and just add the columns you want right as you build the data you are creating. For example, you could include that step right in your call (here using apply to clarify what is going where)
df <- data.frame(mu = rnorm(3), sigma = runif(3))

df_normal_sample_list <- apply(df, 1, function(x){
  data.frame(
    mu = x["mu"]
    , sigma = x["sigma"]
    , sam = rnorm(3, x["mu"], x["sigma"])
  )
})

Returns
[[1]]
          mu     sigma       sam
1 -0.6982395 0.1690402 -0.592286
2 -0.6982395 0.1690402 -0.516948
3 -0.6982395 0.1690402 -0.804366

[[2]]
         mu     sigma       sam
1 -1.698747 0.2597186 -1.830950
2 -1.698747 0.2597186 -2.087393
3 -1.698747 0.2597186 -1.961376

[[3]]
         mu     sigma       sam
1 0.9913492 0.3069877 0.9629801
2 0.9913492 0.3069877 1.2279697
3 0.9913492 0.3069877 1.1222780

Then, instead of binding the columns, then the rows, you can just bind the rows at the end (also from dplyr)
bind_rows(df_normal_sample_list)


text:
Q: devexpress RowSeparatorHeight with merge cell I want a RowSeparatorHeight after the merged rows only
this image for problem

A: To use RowSeparatorHeight you simply have to do following:
GridView1.RowSeparatorHeight = INTEGERVALUE, so in case you would like to set height of 10 between rows you should do following:
GridView1.RowSeparatorHeight = 10


text:
Q: Brazil 2002 first problem neater result? Brazil's 2002 first problem basically asks to prove that for any positive integer n, there are n integers $m_1,m_2\dots m_n$ where $1\leq m_i\leq9$ such that $m_1^2+m_2^2+\ldots+m_n^2=a^2$ for some integer $a$. Can we find a non-constructive proof of this?
A constructive answer can be found at the following link: http://www.artofproblemsolving.com/Forum/viewtopic.php?p=2477647&sid=bb5c5686f0ea79b2dc13977706ffc9bd#p2477647

A: I'm not sure if this is non-constructive or valid, but for large enough $n$, you can take the square of any number 1 through 9, call it $a$, and find a sum of squares with digits $b_i$ (1 through 9) so $b_1^2 + b_2^2 + ... b_n^2 = a^2$. Then your number is $aaaa...(b_1 b_2 ... b_n) ...$ so that the number of $a$'s + groups of $b_1 b_2 ... b_n$ = a square number.


text:
Q: Getting custom code out of CGI.pm We have a custom site written in Perl that uses a slightly modified version of CGI.pm. During server updates, CGI.pm may be overwritten when it is updated. My goal is to be able to update the server without affecting the site - i.e. change the code that relies on the modified CGI.pm. Unfortunately I am not very familiar with Perl syntax or best practice.
Here is a diff of the modified CGI.pmn (line numbers are off from the most recent version of CGI.pm):
--- CGI.pm.orig Tue Nov  7 12:14:09 2006
+++ CGI.pm      Tue Nov  7 12:13:29 2006
@@ -3386,7 +3386,7 @@ sub read_multipart {
               if (defined $self->{'.upload_hook'})
                {
                   $totalbytes += length($data);
-                   &{$self->{'.upload_hook'}}($filename ,$data, $totalbytes, $self->{'.upload_data'});
+                   &{$self->{'.upload_hook'}}($filename ,$data, $totalbytes, $self->{'.upload_data'}, $param, $header{'Content-Type'});
               }
               print $filehandle $data if ($self->{'use_tempfile'});
           }

The code that relies on this diff follows:
my %file_hash = ();
my $page = new CGI(\&file_reader, \%file_hash, 0);

my $session = &get_session($page);

foreach my $param_name (keys %file_hash) {
        my $notes_param = $param_name . "_notes";
        &store_file($file_hash{$param_name}, $page->param($notes_param),
                    &get_session_name($session));
}

Without the diff, when the file is stored, the $param_name variable appears to be empty.
What is the best way to handle this? As I said before, my main goal is to simplify updates to the server; is there some way to either
a) (preferably) get %file_hash to work properly without a modified version of CGI.pm
b) prevent updates to CGI.pm (and is this a bad idea)

A: Have you tried submitting this to the CGI RT as a desired improvement? It seems reasonable to pass $param and \%header (rather than $header{'Content-Type'}) to the callback.
To answer your question, you could install CGI in a local directory. The directories in the PERL5LIB env var are searched first, so your CGI version would be found instead of the one installed by the Ubuntu.

A: I'm the CGI.pm maintainer. I think there is a better option than using a local copy of CGI.pm. Instead, create a sub-class, and use the my subclass in your application. It would look like this:
package My::CGI;
use parent 'CGI';

sub my_sub_that_modified {
  ...
}

1;

So, you just need to copy in the subroutine that you modified. Then, when you upgrade CGI.pm, you likely don't need to touch your application, unless your modified subroutine changes.
With the "local lib" option, you would still need to manually merge in security updates and other changes you might want to into your local copy. The sub-class route minimizes that.
An example of this approach is Bugzilla::CGI which makes several changes in their sub-class.


text:
Q: Print result to webpage via Flask (Python) I hope someone can give me a hand with this. I'm trying to print the output of a calculation result onto a webpage and it's just not showing - I really don't understand how the exact same function is working perfectly for another result, but not anything else.
from flask import Flask, render_template

app = Flask(__name__)

stackList = []
latestNumber = 0

@app.route('/')
@app.route('/calc/')
@app.route('/calc/peek')
def calcPeek():
    return render_template('peek.html', stackList=stackList)

@app.route('/calc/push/<number>')
def pushNumber(number):
    stackList.append(number)
    latestNumber = number
    print(stackList)
    return render_template('push.html', number=number, latestNumber=latestNumber)

@app.route('/calc/pop')
def calcPop():
    stackList.pop()
    return render_template('pop.html', stackList=stackList)

@app.route('/calc/add')
def calcAdd():
    numOne = stackList[-1]
    numTwo = stackList[-2]
    addResult = int(numOne) + int(numTwo)
    stackList.pop()
    stackList.pop()
    stackList.append(addResult)
    print(addResult)
    return render_template('add.html', stackList=stackList, addResult=addResult)

@app.route('/calc/subtract')
def calcSubtract():
    numOne = stackList[-1]
    numTwo = stackList[-2]
    minusResult = int(numOne) - int(numTwo)
    stackList.pop()
    stackList.pop()
    stackList.append(minusResult)
    print(minusResult)
    return render_template('add.html', stackList=stackList, minusResult=minusResult)

And here's the add.html file.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add</title>
</head>
<body>
    <p>Result: {{addResult}} </p>
</body>
</html>

The peek, push/number and add functions all work fine and give me the result I need. However, if I try the same function with divide/multiply/subtract it doesn't actually show anything on the webpage - No error or anything. The result prints to the console but doesn't generate any output for the webpage. Subtract.html below
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subtract</title>
</head>
<body>
    <p> {{minusResult}} </p>
</body>
</html>

Is there anything I'm missing thats completely obvious here? Thanks for any help with this in advance

A: Return statement on your calcSubtract function should be return render_template('subtract.html', minusResult=minusResult). There is no need to pass stacklist.
Code Snippet:
@app.route('/calc/subtract')
def calcSubtract():
    numOne = stackList[-1]
    numTwo = stackList[-2]
    minusResult = int(numOne) - int(numTwo)
    stackList.pop()
    stackList.pop()
    stackList.append(minusResult)
    print(minusResult)
    return render_template('subtract.html', minusResult=minusResult)


text:
Q: How to map part of aspnet_Users table using Fluent NHibernate I'm trying to get Fluent NHibernate 1.0 RTM to map a User entity for me so that I have access to UserId and UserName inside my ASP.NET MVC application via NHibernate.
I have:
public class User
{
    public virtual Guid UserId { get; protected set; }
    public virtual string UserName { get; protected set; }
}

It represents the aspnet_Users table with only the relevant columns to be mapped. This is the only entity that is not being automapped. Here is my mapping:
public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x => x.UserId);
        Map(x => x.UserName);
        WithTable("aspnet_Users");
    }
}

Everything else is getting automapped with conventions.
Here are my PrimaryKeyConvention and TableNameConvention:
public class PrimaryKeyConvention : IIdConvention
{
    public void Apply(IIdentityInstance instance)
    {
        instance.Column(instance.Property.ReflectedType.Name + "Id");
        instance.UnsavedValue(System.Guid.Empty.ToString());
        instance.GeneratedBy.GuidComb();
    }
}

public class TableNameConvention : IClassConvention
{
    public void Apply(IClassInstance instance)
    {
        instance.Table(Inflector.Net.Inflector.Pluralize(instance.EntityType.Name));
    }
}

The Mapping process fails right after executing the ClassMap code (which comes before all automapping), followed by the TableNameConvention code, followed by the PrimaryKeyConvention code. The failure is in PrimaryKeyConvention because instance.Property is null. I tried to do an if(instance.Property != null) but that
terminates the mapping process early with a "the required attribute 'class' is missing" error. I also had an if (instance.EntityType != typeof(User)) in the TableNameConvention, but took out when it was making no difference.
What is going on here? First of all, why is the AutoMapping processes calling the conventions for the ClassMap? Second, why is the PrimaryKenConvention getting passed an instance.Property == null? How can I get this to work so that the mapping process moves on and maps the rest of my entities using AutoMapping + conventions?
Note, I had this all working for months under an earlier version of FNH prior to the refactor for 1.0 RTM.

A: I've figured out the answer to this.
public UserMap()
{
    Id(x => x.UserId);
    Map(x => x.UserName);
    Table("aspnet_Users");
}

public class PrimaryKeyConvention : IIdConvention
{
    public void Apply(IIdentityInstance instance)
    {
        instance.Column(instance.EntityType.Name + "Id");
        instance.UnsavedValue(System.Guid.Empty.ToString());
        instance.GeneratedBy.GuidComb();
    }
}

public class TableNameConvention : IClassConvention
{
    public void Apply(IClassInstance instance)
    {
        instance.Table(Inflector.Net.Inflector.Pluralize(instance.EntityType.Name));
    }
}

Note that the PrimaryKeyConvention sets the Column name using instance.EntityName rather that instance.Property. The latter was null for the UserMap, so it would crash.
This approach is better than using a conditional statement on (null != instance.Property) and keeping the instance.Property.ReflectedType.Name line, but both work. If you choose to go that route, you have to explicitly set the Column names in the UserMap:
public UserMap()
{
    Id(x => x.UserId).Column("UserId")
                     .GeneratedBy.Assigned();
    Map(x => x.UserName).Column("UserName");
    Table("aspnet_Users");
}

A: I don't use the auto-mapping myself, but I think you need to map User by implementing IAutoMappingOverride. Something like:
public class UserMap : IAutoMappingOverride<User>
{
    public void Override(AutoMapping<User> mapping)
    {
        mapping.Id(x => x.UserId);
        mapping.Map(x => x.UserName);
        mapping.WithTable("aspnet_Users");
    }
}


text:
Q: implicit declaration of function 'mygets' [-Wimplicit-function-declaration] mygets(str1); [I've been looking at other questions and none of the solutions have worked so I'll ask my own question.
I'm working on a Ubuntu Kylin16.04(China version) and having trouble compiling my code, here are my gets function, the error received by the compiler]1

A: Implicit declaration of function means that you don't have function reference somewhere in header file normally.
Or maybe you have it, but the file where your function is called does not see this.
//Declaration, must always be before first function call
void myfunc(void);

//Function usage somewhere in the code
int main(void) {
   //Call it here, compiler see the reference and knows what type
   //of func it is and what parameters should be used to func
   myfunc();
}

//Definition, write function content here
//This part will be compiled in separate way, linked will put everything together
void myfunc(void) {
   //Write function content here
}


text:
Q: Not all kafka consumers are getting assigned to partitions I have 10 consumers and 10 partitions.
I take the number of partitions
int partitionCount = getPartitionCount(kafkaUrl);

and I create the same number of consumers with the same group.id.
    public void listen() {
        try {
            String kafkaUrl = getKafkaUrl();
            int partitionCount = getPartitionCount(kafkaUrl);
            Stream.iterate(0, i -> i + 1)
                    .limit(partitionCount)
                    .forEach(index -> executorService.execute(() ->
                            consumerTask.invokeKafkaConsumerTask(prepareConsumerConfig(index, kafkaUrl), INPUT_TOPIC)));
        } catch (Exception exception) {
            logger.error("Cannot receive event from kafka ", exception);
        }

    public void invokeKafkaConsumerTask(Properties properties, String topicName) {
        try(KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties)) {
            consumer.subscribe(Collections.singletonList(topicName));
            logger.info("[KAFKA] consumer created");
            invokeKafkaConsumer(consumer);
        } catch (IllegalArgumentException exception) {
            logger.error("Cannot create kafka consumer ", exception);
        }
    }

    private void invokeKafkaConsumer(KafkaConsumer<String, String> consumer) {
        try {
            while (true) {
                ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(4));
                if (consumerRecords.count() > 0) {
                    consumeRecords(consumerRecords);
                    consumer.commitSync();
                }
            }
        } catch (Exception e) {
            logger.error("Error while receiving records ", e);
        }
    }

method getPartitionCount
return 10 partitions so it's working right
config looks like this
Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUrl);
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_CLIENT_ID);
properties.put(ConsumerConfig.CLIENT_ID_CONFIG, CONSUMER_CLIENT_ID + index);
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "300000");
properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, "10000");
properties.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, String.valueOf(Integer.MAX_VALUE));
properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.RoundRobinAssignor");

what I see after assigning consumers to the partition
TOPIC      PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CLIENT-ID
topicName  1          89391           89391           0               consumer0
topicName  3          88777           88777           0               consumer1
topicName  5          89280           89280           0               consumer2
topicName  4          88776           88776           0               consumer2
topicName  0          4670991         4670991         0               consumer0
topicName  9          23307           89343           66036           consumer4
topicName  7          89610           89610           0               consumer3
topicName  8          88167           88167           0               consumer4
topicName  2          89138           89138           0               consumer1
topicName  6          88967           88967           0               consumer3

only half of the consumers have been assigned to the partitions
why did this happen? There should be one consumer per partition acording to documentation. Am I doing something wrong? kafka version 2.1.1.
I also find few this logs ->
Setting newly assigned partitions:[empty]

A: [solution] interesting case I changed group.id and partition.assignment.strategy, added auto.offset.reset=earliest and it looks like it works...

A: Are you subscribing to a collection of topic name or java Pattern?
  If you are subscribing to a Pattern , change partition.assignment.strategy to RoundRobinAssignor or StickyAssignor.


text:
Q: Magento 2 How to get customer collection from website id? I want to get collection for customer website wise. I have a website id, and now I want all the customers which belong to that particular website id.
I am trying here:
using \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerFactory

$customers = $this->_customerFactory->create();

foreach($customers as $customer)
{
    $this->dataHelper->assignLocationToCustomer($location,$customer);
}

How can I get collection website wise?

A: We can get collection website wise using below code:
protected $_customerFactory;

\Magento\Customer\Model\CustomerFactory $customerFactory

$this->_customerFactory = $customerFactory;

$customers = $this->_customerFactory->create()->getCollection()
                  ->addAttributeToSelect("*")
                  ->addAttributeToFilter("website_id", array("eq" => $websiteId));

foreach($customers as $customer)
{
    print_r($customer->getData());
}