text:
Q: IF/Then formula producing error "refers to a column that does not exist" I tried to follow the instructions I found on the site to get the CY month number associated with the 3 letter month column.
IF([Month]=JAN,"1",IF([Month]=FEB,"2",IF([Month]=MAR,"3",IF([Month]=APR,"4",IF([Month]=MAY,"5",IF([Month]=JUN,"6",IF([Month]=JUL,"7",IF([Month]=AUG,"8",IF([Month]=SEP,"9",IF([Month]=OCT,"10",IF([Month]=NOV,"11",IF([Month]=DEC,"12",0))))))))))))
The error is:
The formula refers to a column that does not exist.  Check the formula for spelling mistakes or change the non-existing column to an existing column.

A: Assuming you have a column named "Month", you will need to add quotes around each month name. (They are just text.)
=IF([Month]="JAN","1",
  IF([Month]="FEB","2",
  IF([Month]="MAR","3",
  IF([Month]="APR","4",
  IF([Month]="MAY","5",
  IF([Month]="JUN","6",
  IF([Month]="JUL","7",
  IF([Month]="AUG","8",
  IF([Month]="SEP","9",
  IF([Month]="OCT","10",
  IF([Month]="NOV","11",
  IF([Month]="DEC","12",
  ""
  ))))))))))))

If you want the result as a number, then remove the quotes from the numbers:
=IF([Month]="JAN",1,
  IF([Month]="FEB",2,
  IF([Month]="MAR",3,
  IF([Month]="APR",4,
  IF([Month]="MAY",5,
  IF([Month]="JUN",6,
  IF([Month]="JUL",7,
  IF([Month]="AUG",8,
  IF([Month]="SEP",9,
  IF([Month]="OCT",10,
  IF([Month]="NOV",11,
  IF([Month]="DEC",12,
  0
  ))))))))))))

Here's a much short formula that does the same thing:
=(FIND(UPPER(D2),"   ,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC")-1)/4

(There are three spaces between the quote and the first comma.)
And here's one that will work with any three to nine letter month name:
=(FIND(UPPER(Month),"         ,JANUARY  ,FEBRUARY ,MARCH    ,APRIL    ,MAY      ,JUNE     ,JULY     ,AUGUST   ,SEPTEMBER,OCTOBER  ,NOVEMBER ,DECEMBER ")-1)/10

(All of the spaces are important!)


text:
Q: Autofac register with folder I use Autofac. I have a lot of classes here and I have to add each one individually. Besides, all my classes are not in a single file. Can I directly save the classes in that file by giving the file path?
        ContainerBuilder builder = new ContainerBuilder();

        builder.RegisterControllers(Assembly.GetExecutingAssembly());

        builder.RegisterType<CommonBusinessLayer.MyCommonMethods.MailController>().SingleInstance();
        ..........
        ..........
        ..........
        builder.RegisterType<Mvc.MyMethods.Concrete.CacheCategory>().SingleInstance();

        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Can you help with the "CommonBusinessLayer.MyCommonMethods.MailController" and "Mvc.MyMethods.Concrete.CacheCategory" classes in the example?
So I write over and over again to register each class.
builder.RegisterType<CommonBusinessLayer.MyCommonMethods.AController>().SingleInstance();
builder.RegisterType<CommonBusinessLayer.MyCommonMethods.BController>().SingleInstance();
builder.RegisterType<CommonBusinessLayer.MyCommonMethods.CController>().SingleInstance();
builder.RegisterType<CommonBusinessLayer.MyCommonMethods.DController>().SingleInstance();

Can we register instead by giving a direct file path?
builder.RegisterType<CommonBusinessLayer.MyCommonMethods..cs*>().SingleInstance();
I want this because I have too many class. All of them are in different files.
CommonBusinessLayer.MyCommonMethods
|->AController,BController,CController,DController,EController,FController,....
Mvc.MyMethods.Concrete
|->XController,YController,ZController,....
and I write each one to register them.
builder.RegisterType<CommonBusinessLayer.MyCommonMethods.AController>().SingleInstance();
builder.RegisterType<CommonBusinessLayer.MyCommonMethods.AController>().SingleInstance();
builder.RegisterType<CommonBusinessLayer.MyCommonMethods.AController>().SingleInstance();
builder.RegisterType<CommonBusinessLayer.MyCommonMethods.AController>().SingleInstance();
builder.RegisterType<CommonBusinessLayer.MyCommonMethods.AController>().SingleInstance();

builder.RegisterType<Mvc.MyMethods.Concrete.XController>().SingleInstance();
builder.RegisterType<Mvc.MyMethods.Concrete.YController>().SingleInstance();
builder.RegisterType<Mvc.MyMethods.Concrete.ZController>().SingleInstance();

Can we register the controllers for the file instead?
example:
 builder.RegisterType<CommonBusinessLayer.MyCommonMethods.*.cs>().SingleInstance();
 builder.RegisterType<Mvc.MyMethods.Concrete.*.cs>().SingleInstance();

Ben denedim, böyle;
    ContainerBuilder builder = new ContainerBuilder();

    builder.RegisterControllers(Assembly.GetExecutingAssembly());

    var dataAccess = Assembly.GetExecutingAssembly();

    builder.RegisterAssemblyTypes(dataAccess)
           .Where(t => t.Name.StartsWith("Repository"))
           .SingleInstance();

    //builder.RegisterType<RepositoryUser>().SingleInstance();
    //builder.RegisterType<RepositoryCategory>().SingleInstance();
    //builder.RegisterType<RepositoryProvince>().SingleInstance();
    //..........
    //builder.RegisterType<RepositoryDistrict>().SingleInstance();

    IContainer container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

and result;
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Mvc.Controllers.KonumController' can be invoked with the available services and parameters:
Cannot resolve parameter 'CommonBusinessLayer.Repository.RepositoryDistrict repoDistrict' of constructor 'Void .ctor(CommonBusinessLayer.Repository.RepositoryDistrict, CommonBusinessLayer.Repository.RepositoryUser)'.

A: Its work.
My repository is inheriting from repositoryBase. With the help of RepositoryBase, I introduced the file path and recorded what started with Repository in it.
 builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(RepositoryBase))).Where(p => p.Name.StartsWith("Repository")).SingleInstance();

redpajama_set_name: RedPajamaStackExchange


text:
Q: DeepZoom white images - Imagemagick Vips Cocoa i have a little cocoa osXa app that uses Vips DZSAVE and imagemagick to create the DeepZoom Tile from a big psb file.
the problem is that it works fine just till a undefined size. i'm managing correctly files about 60.000px X 50.000px 27Gb size but whit bigger files the app is generating a tile made by white images.
No data are written...
i have to manage images around 170.000px X 170.000px between 60 and 80 Gb.
i have tried Environment Variables to increase imagemagick cache limits but, no results...
someone has some ideas about the white output?

A: I'm the vips maintainer. Try at the command-line, something like:
vips dzsave huge.psb output_name --tile-size 256 --overlap 0 --vips-progress --vips-leak

and see what happens. If you run "top" at the same time you can watch memory use.
vips uses libMagick to load the psb files and my guess would be that this is hitting a memory limit somewhere inside ImageMagick.
Do you have to use psb? If you can use a format that vips can process directly it should work much better. Big TIFF or Openslide (if these are slide images) are both good choices. I regularly process 200,000 x 200,000 images with dzsave on a very modest laptop.


text:
Q: Checking a matrix for distinct rows I am computing some combinatorial parameter associated with the complex simple Lie algebras of type $A_n$ using sage and the output will be a rectangular integer matrix.
All I need to prove to solve my research problem is to prove that this matrix has distinct rows.
I thought I shall prove the matrix is of full rank. But clearly, it is an over-expectation and turns out to be false.
I have some understanding of the matrix entries and I am looking for an algebraic method to employ on this matrix to detect the distinctness of rows.
I hope checking by hand is not the only way to do it as the matrix size grows very fast with $n$. If techniques like Jordan form, row echelon form or something like them can be used, then it will be good.
Kindly help me with this. Thank you.

A: The obvious "algebraic" condition is that the left null space of your matrix contains no vector of the form $e_i - e_j$.  Does that help?


text:
Q: FLASK - Send custom HTML tag from FORM to backend I have some custom tags into some inputs :
<input autocomplete="off" required="" name="facturationInfo_invoiceNumber" id="invoiceNumber" type="text" class="form-control" onfocusout="ocrOnFly(true, this, true); removeRectangle()" onfocusin="ocrOnFly(false, this, true)" x1_original="" y1_original="" x2_original="" y2_original="" value="FR24333489" page="1" x1="593" y1="426" x2="673" y2="456">

I am wondering if I have any chance to get the x1, y1, x2, y2 etc.. on the flask backend ?
Thanks

A: No (Actually not a complete no, but simply no).
But if you make changes like,
<input autocomplete="off"
       required=""
       name="facturationInfo_invoiceNumber"
       id="invoiceNumber" type="text"
       class="form-control"
       onfocusout="ocrOnFly(true, this, true); removeRectangle()"
       onfocusin="ocrOnFly(false, this, true)"
       value="FR24333489">

<input type="hidden" name="x1_original" value="">
<input type="hidden" name="x2_original" value="">
<input type="hidden" name="y1_original" value="">
<input type="hidden" name="y2_original" value="">

Then you can access x1_original, x2_original etc. from request object.


text:
Q: Why can't I use (String arg, arg2) instead of (String arg, String arg2) for my method? I can pass two values to a method using this code in the Subclass:
try
{
    echo(args[0], args[1]);
}
catch (Exception e)
{
    System.out.println("Argument required");
}

and this code in the Superclass:
public static void echo(String arg, String arg2)
{
    try
    {
        System.out.println("You entered: " + arg + " and " + arg2);
    }
    catch (Exception e)
    {
        System.out.println("Argument required");
    }

My question is why must I declare the string variables arg and arg2 by typing String twice? They are both of type String so couldn't I just write (String arg, arg2)?

A: You just can't. That's how the language was designed.
A choice was made that method signatures should work in the way they do. It could have been designed differently to support this (for example, golang does).
But this is how Java is, and it seems vastly unlikely that it would ever be changed to support it.

A: This is a Java design requirement.
As Java is a strong typed language , you have to define type of every variable.
When you declare a String (or something else), you can set multiple variable with only one type declaration.
String a,b;

But in a method, arguments can be differently-typed
void myFunction(String a, Integer b, [etc...])

So you have to specifiy each type for arguments.

There is an exception for functions with variable number of arguments
void myFunction(String... args) {
    for (String arg : args) {
        System.out.println(arg);
    }
}

A: You can't use it in the way you want.
You can use Variable Arguments (Varargs) - (should be declared last in arguments of your method )
Example:
public static void echo(String... args) {
    System.out.println("You entered: " + args[0] + " and " + args[1]);
}


text:
Q: R- How to return named list without printing to console I want to return a named list from a function, f.
For example, calling f(args) gives me a named list of variables named x and y.
I use return(list(x=x,y=y)) at the end of my function.
$x
[1] 1 2

$y
[1] 12

The problem is that the output above always prints  the values of entire list to the console. I want to avoid this because $x may take the value of a very large matrix. Is there a way for me to define model<-f(args) and surpress the print out of the $x values when I type model into the console. Instead, I just want to access x by model$x.

A: Use invisible:
f <- function(x, y) {
    invisible(list(x, y))
}

f(rnorm(1e4), rnorm(1e4))
## (nothing)

str(f(rnorm(1e4), rnorm(1e4)))
# List of 2
#  $ : num [1:10000] 2.402 0.51 -1.117 0.415 0.849 ...
#  $ : num [1:10000] -0.642 0.967 -0.328 -0.33 -0.914 ...

A: To be honest, I am in a search for a similar solution. Just like the comment above, a way of avoiding output in the console, is to assign the output of a function that returns a list, to a variable. I do understand that this may not be the solution for all cases however.
f<-function(x=1,y=1){
   return(list(x=x,y=y))
}

result<-f()


text:
Q: ibeacon collections in android is less than ios I collect ibeacon with beacon in android. But in same environment and same time. the collections is less than in ios. In 2 minutes. I can collect 1000+ ibeacon info but only 400 in oppo reno and 150 in huawei p40.
Is there any diffrences between android and ios?
below is my code
package org.altbeacon.beaconreference;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.Manifest;
import android.app.Activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import org.altbeacon.beacon.AltBeacon;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;

class BeaconLocationData {

    public  Map<String, Map<String, String>> locations =new HashMap<>();

    public BeaconLocationData() {
        initLocationData();
    }

    private void initLocationData() {
        Map<String, String> minorLocations = new HashMap<>();
        minorLocations.put("16101", "a-6");
        minorLocations.put("10101", "A-1");
        locations.put("10001", minorLocations);
    }

    public String getLocationMsg(String major, String minor) {
        String location;
//        location = locations.get(major).get(minor);
        Map<String,String> minorMap = locations.get(major);
        if (minorMap == null || minorMap.size() == 0) {
            return "no location";
        }
        location = minorMap.get(minor);
        if (location == null || location.equals("")) {
            return "no location";
        }
        return location;
    }

}

public class RangingActivity extends Activity implements BeaconConsumer {
    protected static final String TAG = "RangingActivity";
    private static final long DEFAULT_FOREGROUND_SCAN_PERIOD = 1000L;
    private static final long DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD = 0;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

    private BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
    public static final String IBEACON_FORMAT = "m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24";
    public static final String FILTER_UUID = "fda50693-a4e2-4fb1-afcf-c6eb07647825";
    public BeaconLocationData beaconLocationData;

    private TextView textView;
    private void initBeacon() {
        beaconManager = BeaconManager.getInstanceForApplication(this);
        beaconManager.setForegroundBetweenScanPeriod(DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD);
        beaconManager.setForegroundScanPeriod(DEFAULT_FOREGROUND_SCAN_PERIOD);
        beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(IBEACON_FORMAT));
        beaconManager.bind(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ranging);
        requestLocationPermissions();
        initBeacon();
        initData();
        textView = findViewById(R.id.textView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        beaconManager.unbind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        beaconManager.getBeaconParsers().add(new BeaconParser().
//                setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
//        beaconManager.bind(this);

    }

    private void requestLocationPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // Android M Permission check

            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs location access");
                builder.setMessage("Please grant location access so this app can detect beacons.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                    }
                });
                builder.show();
            }

        }
    }

    private int count = 0;

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "coarse location permission granted");
                } else {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Functionality limited");
                    builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }

                    });
                    builder.show();
                }
                return;
            }
        }
    }

    private void initData() {
        beaconLocationData = new BeaconLocationData();
    }

    @Override
    public void onBeaconServiceConnect() {
        Log.i(TAG, "onBeaconServiceConnect: ");
        beaconManager.addRangeNotifier(new RangeNotifier() {
            @Override
            public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
                Log.i(TAG, "didRangeBeaconsInRegion: "+collection.size());
//                updateTextViewMsg("进入didRangeBeaconsInRegion方法");
                if (collection.size() > 0) {

                    List<Beacon> beacons = new ArrayList<>();
                    for (Beacon beacon : collection) {

                        if (beacon.getId1().toString().equalsIgnoreCase(FILTER_UUID)){

                            Log.i(TAG, "FIND UUID: " + FILTER_UUID);
                            Log.i(TAG, "MAJOR: " + beacon.getId2().toString());
                            Log.i(TAG, "MINOR: " + beacon.getId3().toString());
                            count++;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    textView.setText("beacon:"+count);
                                }
                            });
                            beacons.add(beacon);
                        }
                    }

                    if (beacons.size() > 0) {
                        Collections.sort(beacons, new Comparator<Beacon>() {
                            public int compare(Beacon arg0, Beacon arg1) {
                                return arg1.getRssi()-arg0.getRssi();
                            }
                        });

                        Beacon nearBeacon = beacons.get(0);
                        String major = nearBeacon.getId2().toString();
                        String minor = nearBeacon.getId3().toString();
                        String location = beaconLocationData.getLocationMsg(major, minor);
                        Log.i(TAG, "didRangeBeaconsInRegion: "+ beacons.toString() );

                    }
                }
            }

        });
        try {
            beaconManager.startRangingBeaconsInRegion(new Region(FILTER_UUID, null, null, null));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

}

the code init beacon and collect beacon. didRangeBeaconsInRegion is the beacon callback.

A: Both Android and iOS phones have large variations in receiver sensitivity which greatly affect the number of devices detected, especially at far distances.
Receiver sensitivity typically varies by up to 6dB (some devices have receivers 10dB weaker) which has a huge effect.  I was shocked when I tested my Huawei P9 Lite a few years ago, and found it unable to detect a beacon more than 10 meters away.  Most phones can detect beacons 40 meters away or more.
Documenting these variations has earned new interest in the era of using bluetooth  signal levels for pandemic contact tracing.  Google has documented variations on a set of over 300 devices.  As you can see, Huawei devices are typically 3dB weaker receivers compared with, say, the iPhone SE.  (To be fair, some iOS devices like the iPhone 6 are also weak receivers).


text:
Q: More than one DbContext in the same project I have a WebAPI project and in this project I have to use more than one DbContext but I do not know how to do that.
There are 3 or 4 databases and with code first I will create a new table in each of them and give relation to the table that is found in each database
How can I do this in a generic way?

A: to have multiple databases. they should be added to the services.
example :
var connectionString1 = builder.Configuration.GetConnectionString("Db1Connection");
builder.Services.AddDbContext<DbfirstDbContext>(options =>
     options. UseSqlServer(connectionString));

var connectionString2 = builder.Configuration.GetConnectionString("Db2Connection");
builder.Services.AddDbContext<DbtwoDbContext>(options =>
     options. UseSqlServer(connectionString2));


text:
Q: recorrer una lista en python como puedo recorrer esta lista generada por numeros random y luego verificar si dos numeros seguidos son iguales. Aca hice un codigo, pero no me ha servido.
import random

numero = int(input("Ingrese numero de dados:"))
if numero <= 0:
    print("ERROR.")
else:
    dados1 = []

for i in range(1,numero+1):
    dados1.append(random.randrange(1,7))
for n in dados1:
    if n == n+1:
        print("Iguales")

print(f"Jugador 1:{dados1}")

A: En realidad, casi lo tienes:
import random

numero = int(input("Ingrese numero de dados:"))
if numero <= 0:
    print("ERROR.")
else:
    dados1 = []

for i in range(1, numero + 1):
    dados1.append(random.randrange(1, 7))
for n in range(len(dados1) - 1):
    if dados1[n] == dados1[n + 1]:
        print("Iguales")

print(f"Jugador 1:{dados1}")

Ahora, vamos a analizar tu código y que falla:
asumamos que has ejecutado el código con 8 dados,
resultado Jugador 1:[2, 1, 3, 3, 2, 2, 6, 2]
Ahora el código que comprueba la serie
for n in dados1:
    if n == n+1:
        print("Iguales")

Iteración 1 -> n = 2, n+1 = 3 por tanto 2 y 3 NO son iguales
se pretendía comparar 2 con 1 que son DISTINTOS
Iteración 2 -> n = 1, n+1 = 2 por tanto 1 y 2 NO son iguales
se pretendía comparar 1 con 3 que son DISTINTOS
Iteración 3 -> n = 3, n+1 = 4 por tanto 3 y 4 NO son iguales
se pretendía comparar 3 con 3 que son IGUALES
Iteración 4 -> n = 3, n+1 = 4 por tanto 3 y 4 NO son iguales
se pretendía comparar 3 con 2 que son DISTINTOS
Iteración 5 -> n = 2, n+1 = 3 por tanto 2 y 3 NO son iguales
se pretendía comparar 2 con 2 que son IGUALES
Iteración 6 -> n = 2, n+1 = 3 por tanto 2 y 3 NO son iguales
se pretendía comparar 2 con 6 que son DISTINTOS
Iteración 7 -> n = 6, n+1 = 7 por tanto 6 y 7 NO son iguales
se pretendía comparar 6 con 2 que son DISTINTOS
Te pongo para que puedas ver lo que pasa el código con el que he generado el texto anterior:
import random
numero = int(input("Ingrese numero de dados:"))
if numero <= 0:
    print("ERROR.")
else:
    dados1 = []

for i in range(1, numero + 1):
    dados1.append(random.randrange(1, 7))
# for n in range(len(dados1) - 1):
#     if dados1[n] == dados1[n + 1]:
#         print("Iguales")
#
print(f"Jugador 1:{dados1}")
vuelta = 0
for n in dados1:
    valor = dados1[vuelta] # tomo el valor actual de la serie
    vuelta += 1 # paso al siguiente número que será el mismo que en la siguiente vuelta
    if vuelta == len(dados1): # Si hemos alcanzado el final de la serie, salimos del bucle
        break
    valor2 = dados1[vuelta] # el valor del dado siguiente
    text = 'DISTINTOS'
    if valor == valor2: # comparamos ambos valores
        text = 'IGUALES'
    # imprimimos resultados
    print(f"Iteración {vuelta} -> n = {n}, n+1 = {n+1} por tanto {n} y {n+1} NO son iguales ")
    print(f"Se pretendía comparar {valor} con {valor2} que son {text}\n")

A: Como ya se ha comentado, cuando iteras con un for - in sobre un iterable, el ciclo va obteniendo a través de la variable asociada un referencia a cada item del iterable. Es decir, en tu caso, n será cada entero almacenado en la lista, por lo que n + 1 simplemente suma uno al item, no obtiene el item que le sucede en la lista. La opción obvia es usar range e indizar, pero normalmente es más lento que iterar con un for.
Una forma más eficiente que usar  range + indizado para ir comparando un elemento con el siguiente en un iterable cualquiera es usar un iterador:
dados = [4, 2, 6, 6, 3, 2, 2, 2, 5, 3, 3, 4]

dados_iter = iter(dados)
last = next(dados_iter) # primer item de la lista
for i, new in enumerate(dados_iter):
    if last == new:
        print(f"Encontrados dos {new} consecutivos en posición {i} y {i + 1}")
    last = new

Encontrados dos 6 consecutivos en posición 2 y 3
  Encontrados dos 2 consecutivos en posición 5 y 6
  Encontrados dos 2 consecutivos en posición 6 y 7
  Encontrados dos 3 consecutivos en posición 9 y 10

Si no necesitas conocer los índices dónde se producen las repeticiones, puedes hacer simplemente:
dados_iter = iter(dados)
last = next(dados_iter) # primer item de la lista
for new in dados_iter:
    if last == new:
        print(f"Encontrados dos {new} consecutivos")
    last = new

Hay que tener en cuenta que si aplicamos lo anterior sobre una lista vacía tendremos una excepción, pero es algo que podemos solucionar con un simple condicional por ejemplo:
if dados:
    dados_iter = iter(dados)
    ...

o manejando la excepción:
dados_iter = iter(dados)
try:
    last = next(dados_iter) # primer item de la lista
except StopIteration:
    print("Iterable vacío")
else:
    for i, new in enumerate(dados_iter):
        if last == new:
            print(f"Encontrados dos {new} consecutivos en posición {i} y {i + 1}")
        last = new

ejemplo de comparación de tiempos de ejecución para lista de 10000 elementos:
%%timeit
for i in range(len(dados) - 1):
    if dados[i] == dados[i + 1]:
        pass

1.39 ms ± 29.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
dados_iter = iter(dados)
last = next(dados_iter)
for i, new in enumerate(dados_iter):
    if last == new:
        pass
    last = new

625 µs ± 8.12 µs per loop (mean ± std. dev. of 7 runs, 1000 loops
  each)


text:
Q: ¿Cómo puedo convertir números con decimales a fracciones en Python? Me gustaría imprimir valores numéricos con decimales en su forma de fracción:

0.5 a 1/2
0.75 a 3/4
4.5 a 9/2

¿Existe alguna librería nativa para realizar la conversión? ¿Cómo se realiza dicha conversión?

A: Puedes utilizar la clase Fraction del módulo fractions:
>>> from fractions import Fraction
>>> a = Fraction('0.5')
>>> b = Fraction('0.75')
>>> c = Fraction('4.5')
>>> print(a)
1/2
>>> print(b)
3/4
>>> print(c)
9/2

Si tienes los números guardados como reales, entonces puedes hacer la conversión explícita utilizando str y luego pasar eso la clase Fraction.

A: Puedes hacer una función recursiva que entrega valores para el numerador y denominador de la fracción, sin importar si está simplificado o no. Luego, simplificas o factorizas con el algoritmo de Euclides.
Te dejo el código para el algoritmo.
def mcd(a,b):
    assert type(a) == int and type(b) == int and a>0 and b>0
    if a%b != 0:
        return mcd(b,a%b)
    else:
        return b

Luego haces algo así como numerador=numerador/mcd(numerador,denominador) y denominador=denominador/mcd(numerador,denominador) y lo imprimes como string:
print(str(numerador)+'/'+str(denominador)).

A: Utilizando la clase Fraction del módulo fractions no se retorna el valor de la fracción cuando esta tiene infinitos números decimales, por lo tanto es necesario agregar .limit_denominator() después de emplear la clase.
from fractions import Fraction
a = 2/9
b=Fraction(str(a))
print('Valor de b: ',b)

c=Fraction(str(a)).limit_denominator()
print('Valor de c: ',c)

Y como resultado:
Valor de b:  1111111111111111/5000000000000000
Valor de c:  2/9


text:
Q: all images tabs jump and appear on page when refresh i am having a problem first this is the code that i am working on

Products

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
 et dolore magna aliqua. Ut enim ad minim veniam

All Works

Creative

Photography

Web Development

Business theme

There are many variations of passages of Lorem Ipsum available, but the majority

                                 View

Business theme

There are many variations of passages of Lorem Ipsum available, but the majority

                                 View

Business theme

There are many variations of passages of Lorem Ipsum available, but the majority

                                 View

Business theme

There are many variations of passages of Lorem Ipsum available, but the majority

                                 View

Business theme

There are many variations of passages of Lorem Ipsum available, but the majority

                                 View

Business theme

There are many variations of passages of Lorem Ipsum available, but the majority

                                 View

Business theme

There are many variations of passages of Lorem Ipsum available, but the majority

                                 View

Business theme

There are many variations of passages of Lorem Ipsum available, but the majority

                                 View

as u can see it's a portfolio page and it's has random images and as u click on of the data-filter it will show u the images of that section ,but i am having a problem that when i reload the page ,all the images jump into the page and how many images i put all of them will appear ,and that's not good ,what i want to do is that for example if i reload the page only and automatically the "Creative images" tab images only appear ,i am strugling on how to do that this is my javascript code
// portfolio filter
$(window).load(function(){'use strict';
    var $portfolio_selectors = $('.portfolio-filter >li>a');
    var $portfolio = $('.portfolio-items');
    $portfolio.isotope({
        itemSelector : '.portfolio-item',
        layoutMode : 'fitRows'
    });

    $portfolio_selectors.on('click', function(){
        $portfolio_selectors.removeClass('active');
        $(this).addClass('active');
        var selector = $(this).attr('data-filter');
        $portfolio.isotope({ filter: selector });
        return false;
    });
});

any reply it will be very helpful thanks in advance.

A: Demo
filter: '.bootstrap' in the initialization will hide all other div's. filter option can be used while initializing isotope.
// portfolio filter
var $portfolio_selectors = $('.portfolio-filter >li>a');
var $portfolio = $('.portfolio-items');
$portfolio.isotope({
    itemSelector: '.portfolio-item',
    layoutMode: 'fitRows',
    filter: '.bootstrap'
});

$portfolio_selectors.on('click', function () {
    $portfolio_selectors.removeClass('active');
    $(this).addClass('active');
    var selector = $(this).attr('data-filter');
    $portfolio.isotope({
        filter: selector
    });
    return false;
});


text:
Q: disabled works in IE but not in firefox this is my javascript code. on load function i have to disable btndelete ..it works correct in iE but in firefox, buton is not dsabled..i dont know is this a css issue or what?
Javascript
 window.onload = body_Onload;

            function body_Onload()
            {
                    var btnDelete = document.getElementById('<%=btnDelete.ClientID%>');
                btnDelete.disabled = true;
            }

HTML
<asp:Button ID="btnDelete" runat="server" CssClass="cssbutton" Text="Delete" Width="60px" OnClick="btnDelete_Click" />

CSS
.cssbutton
{
    font-weight: bold;
    border-right: #3C8FD1 1px solid;
    border-top: #3C8FD1 1px solid;
    border-left: #3C8FD1 1px solid;
    border-bottom: #3C8FD1 1px solid;
    font-size: 10px;
    color: #045FA7;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    background-image: url(../App_Images/cssbuttonbg.gif);
    line-height: 14px;
}

HTML Generated Code
<input type="submit" name="pageMain$contentPlaceHolderMain$btnDelete"
    value="Delete" onclick="return btnDelete_Click();"
    id="contentPlaceHolderMain_btnDelete" class="cssbutton" style="width:60px;"/>

A: Here is an example page I made, based on your question and the information in the comments:
This works in both IE and FireFox. The difference is, in IE the button is greyed out when disabled. In FireFox, the button looks the same, but is disabled.  So you may want to assign a class to it and style that greyed out for FireFox.
<!DOCTYPE html>
<html>
<head>

<script>
function body_Onload()
{
    var btnDelete = document.getElementById('contentPlaceHolderMain_btnDelete');
        btnDelete.disabled = true;
        btnDelete.className += ' btndisabled';
}
</script>
<style>
.cssbutton
{
    font-weight: bold;
    border-right: #3C8FD1 1px solid;
    border-top: #3C8FD1 1px solid;
    border-left: #3C8FD1 1px solid;
    border-bottom: #3C8FD1 1px solid;
    font-size: 10px;
    color: #045FA7;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    background-image: url(../App_Images/cssbuttonbg.gif);
    line-height: 14px;
}
.btndisabled
{
    background-color: rgb(236,233,216);
    color: #CCC;
    font-style:normal;
}
</style>
</head>
<body onload="body_Onload();">
<form>
<input type="submit" name="pageMain$contentPlaceHolderMain$btnDelete"
    value="Delete" onclick="return btnDelete_Click();"
    id="contentPlaceHolderMain_btnDelete" class="cssbutton" style="width:60px;"/>
</form>
</body>
</html>


text:
Q: Django-модель User создает поле user_ptr_id Пытаюсь обновить Django c 2 на 3.2.
У меня своя модель User-а:
class Agent(User):

    objects = AgentManager()

    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        editable=False,
        related_name='agent',
        on_delete=models.CASCADE,
        parent_link=True,
    )

Django-модель User-а делает его swappable:
class User(AbstractUser):
    """
    Users within the Django authentication system are represented by this
    model.

    Username and password are required. Other fields are optional.
    """
    class Meta(AbstractUser.Meta):
        swappable = 'AUTH_USER_MODEL'

Запускаю тесты с пустой базой и получаю ошибку:
django.db.utils.IntegrityError: null value in column "user_ptr_id" of relation "staff_agent" violates not-null constraint
DETAIL:  Failing row contains (null, null, 1, null, null, null, null, null, null).

На этапе миграций создается поле user_ptr_id, которое не создавалось на Django 2, и далее оно не заполняется, потому и выдает ошибку.
Вопрос состоит в следующем: как отключить создание этого поля или где Django его создает.

A: Я разобрался сам. Если Django не находит onetoone-поле к User с параметром parent_link=True, то он решает создать свое поле. Потом я увидел, что, хоть в поле и проставлен parent_link=True, в миграции его нет, видимо кто-то проставил тут и забыл пересоздать миграции.
Проставил для миграции это поле и всё, Django перестал создавать свое поле.


text:
Q: Symfony2 generate crud for third party bundle It is possible to generate a basic admin interface using the CRUD generator for my Entities.
i.e. php app/console generate:doctrine:crud
The question is, can this also be done for an entity bundled by a vendor? I get errors about not finding the entity I want.
Thank you

A: It seems that you want to add extra functionality to the vendor bundle so you might need to extend it.
Symfony2 Inhertiance


text:
Q: Solving a Rubik's cube in 20 moves or less Most "cubers" solve a Rubik's cube in about 60 moves, using special algorithms and quick fingers. But any Rubik's cube can be solved in 20 moves or less (cube20.org). Is it possible that there is a way (without computers) to look at a cube and solve it in 20 moves or less, without trying to memorize several sextillion different positions?

A: Simple answer is that there is no known algorithm that can solve the Rubiks Cube in 20 moves maximum for an arbitrary starting position. Nevertheless, it is known that all positions are solvable in 20 moves, thus some algorithm must exist. Whether or not this algorithm requires less work than memorizing all the possible moves is currently somewhat open. (not comoletely.... We have used patterns and some group theory to reduce the number of solutions we needed to check to prove the number 20.) If we ever do find a simpler algorithm the proof will be much easier!


text:
Q: How to work directly in a cell of objects (in Matlab)? C is a mxn cell of objects of class A. Class A have the method f(). Then, I have these lines of code
sum=0;
for i=1:m
    for j=1:n
        a=C{i,j};
        sum=sum +a.f();
    end
end

It seems that using the for loop will make the code run slowly. Is there any way, like using some kinds of matrix of objects, or something like that, for the better performance of this code?

A: What about using cellfun ?
http://www.mathworks.com/help/techdoc/ref/cellfun.html


text:
Q: raspberry pi : Auto run GUI on boot I want to run a python script which executes a  GUI on startup(as pi boots up). But I don't see any GUI on screen but when I open terminal my program executes automatically and GUI appears. Also, my program requires an internet connection on execution but pi connects to wifi later and my script executes first and ends with not connecting to the internet.
Is there any way my python script executes after pi boots up properly and pi connected with internet

A: Without knowing you Pi setup it's a bit difficult. But with the assumption you're running raspbian with its default "desktop" mode:

*

*Open a terminal on your Pi, either by sshing to it or connecting a monitor/keyboard.

*First we need to allow you to login automatically, so sudo nano /etc/inittab to open the inittab for editing.

*Find the line 1:2345:respawn:/sbin/getty 115200 tty1 and change it to #1:2345:respawn:/sbin/getty 115200 tty1

*Under that line, add 1:2345:respawn:/bin/login -f pi tty1 </dev/tty1 >/dev/tty1 2>&1. Type Ctrl+O and then Ctrl+X to save and exit

*Next, we can edit the rc.local. sudo nano /etc/rc.local

*Add a line su -l pi -c startx (replacing pi with the username you want to launch as) above the exit 0 line. This will launch X on startup, which allows other applications to use graphical interfaces.

*Add the command you'd like to run below the previous line (e.g python /path/to/mycoolscript.py &), but still above the exit 0 line.
Note the & included here. This "forks" the process, allowing other commands to run even if your script hasn't exited yet. Ctrl+O and Ctrl+X again to save and exit.

Now when you power on your Pi, it'll automatically log in, start X, and then launch the python script you've written!

Also, my program requires an internet connection on execution but pi connects to wifi later and my script executes first and ends with not connecting to the internet.

This should be solved in the script itself. Create a simple while loop that checks for internet access, waits, and repeats until the wifi connects.

A: Two steps on Raspian:

*

*Make sure you boot into GUI (can setup via sudo raspi-config)

*Edit ~/.config/lxsession/LXDE-pi/autostart and add your python script to the path: e.g. @python /home/pi/your_script.py
It depends on the version of raspian if the path is
~/.config/lxsession/LXDE-pi/autostart

or
~/.config/lxsession/LXDE/autostart

I recommend trying one at a time.
(Older version might use this path /etc/xdg/lxsession/LXDE-pi/autostart (ref))
This should run the script after the UI initialises but you don't have any guarantee WiFi is connected though. I recommend ammending your python script to check if it's connected first and if not retry after a few seconds until it is, then execute the rest as expected.


text:
Q: Approximated Laplace transform of a non-linear system Assume a system with dynamics:
$\dot{\omega}(t) = \alpha \omega^2(t) + \beta i(t)$,
where $\dot{\omega}(t), \omega(t)$ are system's states and $i(t)$ is the system's input. I'd like to approximate the system's transfer function $P(s) = \frac{\omega(s)}{I(s)}$ around some operating point $\xi_0 = \{\omega_0, i_0\}$.
I assumed I could achieve this by linearizing as follows:
$\alpha_0 = \ddot{\omega}(\omega_0) = 2 \alpha \omega_0$
giving:
$\dot{\omega}(t) \approx \alpha_0 \omega(t) + \beta i(t) = 2 \alpha \omega_0 \omega(t) + \beta i(t)$,
hence the transfer function would be:
$\omega(s)(s - 2 \alpha \omega_0) = \beta I(s)$
$P(s) = \frac{\omega(s)}{I(s)} = \frac{\beta}{s - 2 \alpha \omega_0}$.
I tried to simulate step response of the system, but the effects are not as I expected. So there are two solutions: either I made a mistake programming, or the whole thought-process is wrong. Now, which one is it? And why?
Any hints appreciated.
EDIT: The real coefficient and operating point values are given below.
$\alpha = -2182.5$
$\beta = 358.8825$
$\omega_0 = 517.8056$
$i_0 = 6.0814$
EDIT2: I already figured out, what I did is actually a Taylor expansion of the function $\dot{\omega}(t)$. A Taylor expansion also includes the constant term, ie:
$\dot{\omega}(t) = 2 \alpha \omega_0 \omega(t) + \beta i(t) - 2 \alpha \omega^2_0 - \beta i_0$
As @copper.hat commented below, $I(s)$ in the transfer function $P(s)$ reflects perturbations around $i_0$. I already tried testing the transfer function's behaviour in Matlab. I defined a system using:
motor = tf(beta, [1 -2*alpha*omega_0])

To obtain correct amplitude of the step response I had to issue a command
step(motor+i_0)

Is there a way to include the constant term in the transfer function $P(s)$? What does adding $i_0$ really mean in terms of Laplace transform?
What $P(s)$ really is is a model of a BLDC motor with propeller and the non-linear term reflects aerodynamic drag ($\omega$ is shaft angular velocity and $i$ is applied current). I'd like to include the motor in a bigger, linear, model and apply PID control for the whole system. Is it possible?

A: You did some mistake when linearizing. The equation is already linear in $i(t)$. Thus, you should obtain
$$\dot{\omega}(t) \approx  2 \alpha \omega_0 \omega(t) + \beta i(t).$$ The transfer function reads
$$ P(s) = \frac{\beta}{s - 2 \alpha \omega_0}.$$

A: Just solve the problem directly. This is a Riccati equation, so using the variable $v = \omega^{-1}$, one obtains $v'(t) + \alpha + \beta i(t)v(t) = 0$. This can be solved explicitly, using separation of variables.


text:
Q: Relation between roots of $f$ and roots of $f'$ I am trying to prove that if $f$ is a polynomial where all of its roots are real, then all of the roots of $f'$ are also real. I know that the result holds immediately from Rolle's Theorem, however I cannot use it because it is a result of Calculus. This exercise was spent in an Algebra course. I tried to prove by induction in the degree of $f$, but I was unable to complete the induction step. Can anyone give me a tip?

A: Suppose for contradiction that all the roots of $f$ are real but there is a root $\alpha$ of $f'$ which is not real. Let $x_1,\dots,x_n$ be the roots of $f$. We have
$$
\begin{align*}
\frac{f'(x)}{f(x)}  &= \sum_{i=1}^{n} \frac{1}{x-x_i} \\
0 = \frac{f'(\alpha)}{f(\alpha)} &= \sum_{i=1}^{n} \frac{1}{\alpha-x_i} \\
&= \sum_{i=1}^{n} \frac{\overline{\alpha}-x_i}{|\alpha-x_i|^2} \\
&=\sum_{i=1}^n \frac{\overline{\alpha}}{|\alpha-x_i|^2} - \sum_{i=1}^n \frac{x_i}{|\alpha-x_i|^2}
\end{align*}
$$
Solving for $\overline{\alpha}$, we have
$$
\overline{\alpha} = \frac{\sum_{i=1}^n \frac{x_i}{|\alpha-x_i|^2}}{\sum_{i=1}^n \frac{1}{|\alpha-x_i|^2}},
$$
which is real. Contradiction

A: The roots of f'(x) lies in the convex hull of the roots of f(x). Since the roots of f(x) are real, the convex hull turns out to be a subset of the real line and hence the roots of f'(x) are real.


text:
Q: Как правильно переопределить размер модального окна в Bootstrap 2.3.2? Есть правило для модального окна, где указана его ширина в 560px, если поменять это свойство в большую сторону, то размер модального окна изменится но оно будет не по центру, а расширится вправо. Каким образом задать новый размер окна и так чтобы ничего не сломалось?
div.modal {
  position: fixed;
  top: 10%;
  left: 50%;
  z-index: 1050;
  width: 560px;
  margin-left: -280px;
  background-color: #ffffff;
  border: 1px solid #999;
  border: 1px solid rgba(0, 0, 0, 0.3);
  *border: 1px solid #999;
  -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
  -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
  box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
  -webkit-background-clip: padding-box;
  -moz-background-clip: padding-box;
  background-clip: padding-box;
  outline: none;
}

UPDATE
Вижу зависимость правил:
width: 560px;
margin-left: -280px;

Если например поменять так:
width: 700px;
margin-left: -350px;

То для десктопной версии все ок, а вот при респонсиве до мобильной версии, все плохо, ломается и съезжает теперь влево и пропадает контент и часть модального окна.
UPDATE
Оказалось что проблема воспроизводится в браузере Google Chrome, в других браузерах вроде как нету проблемы...

A: Приблизительно так
Fiddle

@import url('https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css');

.modal {
  width: 700px;
  margin-left: -350px;
}

@media (max-width:767px) {
  .modal {
    top: 20px; left: 20px; right: 20px;
    width: auto;
    margin: 0;
  }
}

demo modal

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

    Modal body

A: В моем случае проблема решилась следующим кодом.
div.modal {
  width: 80%;
  margin-left: -40%;
}

@media (max-width:767px) {
  div.modal {
    width: 80%;
    margin: auto;
  }
}


text:
Q: What is the best way to overfit a model with accuracy? I need to overfit a model to specific data.(These data have been created from simulation of complex multidimensional models.)
The final goal is to extract coefficients (betas) to retrieve with accuracy the results of the database, without any complication, any assumptions, any need for extrapolation, just math.
I thought about a regression that try to maximize the adjusted R-squared, as it represents "the proportion of the variance for a dependent variable that's explained by a regression model".
But it may exist some other method, maybe machine learning method, that are more relevant and easy to apply ?
An important point is that the method have to be easily replicable on a non professionnal software like Excel , that why regressions (that contains coefficients) interest me.
Thank you a lot !

A: My thought is that knowing the generating distribution implies one may be able to use something like factor analysis to derive the sets of variables/factors that account for nearly all of the variability, where such factors are related to the parameters of the generating distribution model which also encompasses a randomness component.
Use this set of factors to derive the regression model.
Put differently, fit as close as possible to the extent of the underlying noise model.
An interpolation model would be a correct approach if there is no (or very little) randomness and a poor choice in the presence of significant random noise.


text:
Q: How to show capture image in QLabel I am trying to display live camera image to Qlabel.. When I start code it does not give any error and my camera light goes to blue which means working. However ui does not start. After I debug my code I see that in while(true) it always looping but ui->lblProcessedVideo->setPixmap..... command does not shows any ui.
Could you please kindly show me my mistake..
Here is my partial code:
void MainWindow::getImageFromVideo()
{
    CvCapture* capture;
    cv::Mat frame;
    cv::Mat gray_frame;

    capture = cvCaptureFromCAM( 0 );

    if( capture )
    {
        while( true )
        {
            frame = cvQueryFrame( capture );

            if( !frame.empty() )
            {
                cvtColor( frame, gray_frame, CV_BGR2GRAY);

                equalizeHist( gray_frame, gray_frame );

                ui->lblProcessedVideo->setPixmap( QPixmap::fromImage( Mat2QImage( frame )));
            }
        }
    }
}

EDIT: Mat2QImage() is a function which convert Mat to QImage

A: Like Ezee said you need to delegate capturing image from camera to separate thread, next send image to GUI thread. heres sample code:
//timer.h
class Timer : public QThread
{
    Q_OBJECT
public:
    explicit Timer(QObject *parent = 0);
    void run();
signals:
    void updFrame(QPixmap);
public slots:

};

//timer.cpp
Timer::Timer(QObject *parent) :
    QThread(parent)
{
}

void Timer::run()  {
    VideoCapture cap(0); // open the default camera
    for(;;){
        Mat frame;
        cap.read(frame);
        QPixmap pix = QPixmap::fromImage(IMUtils::Mat2QImage(frame));
        emit updFrame(pix);
        if( waitKey (30) >= 0){
            break;
        }
    }
}

//videoviewer.h
class VideoViewer : public QLabel
{
    Q_OBJECT
public:
    explicit VideoViewer(QObject *parent = 0);

signals:

public slots:
    void updateImage(QPixmap pix);
};

//videoviever.cpp
VideoViewer::VideoViewer(QObject *parent) :
    QLabel()
{
    Timer* timer = new Timer();
    connect(timer,SIGNAL(updFrame(QPixmap)),this,SLOT(updateImage(QPixmap)));
    timer->start();
}

void VideoViewer::updateImage(QPixmap pix){
    this->setPixmap(pix);
}


text:
Q: Add new path to an existing map in D3 I have created a World Map using D3. I am using D3 library and topojson library for it's creation.
Now, I want to draw a path of a county named "Turkana" in "Kenya".For that I am appending a new path retrieved from the geoJSON data of "Turkana" county to the existing Path of the WorldMap.
Like below
g.selectAll("path")
  .data(countries)
  .enter().append("path")
  .attr("d", path)
  .attr("class", "feature")
  .on("click", clicked);

g.selectAll("path")
  .data(geoJSONKenyaTurkana.features)
  .enter().append("path")
  .attr("d",path)
  .attr("class", "feature");

But nothing seems to be happening. I mean path of Turkana county is not drawn. Any help would be appreciated.
I have created a plunker for my current working code.

A: Your problem is that you are not using the enter method correctly. When you add the countries, you use a selection:
g.selectAll("path")
As there are no paths yet, this is an empty selection. In general, when you assign data to a selection and use the enter() selection, the enter selection holds all the features that need to be created. In this case, as you have no features in your initial selection; therefore, using .enter().append() will create one feature for each item in the data array. This works great the first time when appending countries.
The second time you use the same selection (when trying to add the county), but this time that selection is not empty - you are selecting all the paths you just made (one for each country). The enter selection will be empty, no new features need to be made, you are just updating the data for the first path that was created.
This is visible if you comment two lines in your code:
g.selectAll("path")
    .data(geoJSONKenyaTurkana.features)
    //.enter().append("path")
    .attr("d",path)
    //.attr("class", "feature");

Shown in this example using your map, you can see that the county data just replaced the datum for Canada (you can't see the new datum for Canada(now Turkana) because it is behind Kenya since it was appended before Kenya in the initial append).
To make your approach work you need to use a null selection, you could use d3.selectAll(null) or d3.selectAll(".ClassDoesNotExistYet") (the latter option is slightly slower) etc. If the selection is empty, all items in the data array that need to be appended will be in the enter selection. See this plunker of your code as intended (I removed the mesh as it reduced visibility of the county for this demo).


text:
Q: Pie Chart por linha de código c# Preciso criar gráficos em tempo de execução, conforme o usuário pede. Achei um código no site TI4Fun
nele o cara consegue alterar as propriedades do chart do jeito que eu quero. O problema é que preciso criar um novo, quando uso:
var cht_MacroOndas = new System.Windows.Forms.DataVisualization.Charting.Chart();
this.Controls.Add(cht_MacroOndas);

Consigo criar o chart, mas não posso editá-lo. Alguém sabe como posso fazer isso?

A: Olá, eu sei que já faz um tempo que você postou e me avisou via face mas só agora eu pude realmente olhar isso.
Neste seu exemplo você está criando um novo gráfico e adicionando na coleção, você poderia verificar se já existe uma instância da classe na coleção Controls e pegá-la mas tentei fazer algumas experiências e é muito chato então minha sugestão é a seguinte.
Um objeto que você adiciona na coleção mantem sua referência desde que o escopo em que ele foi criado ainda esteja ativo, o que você pode fazer é o seguinte.

*

*Declarar a variável no escopo do formulário
public partial class Form1 : Form
{
    System.Windows.Forms.DataVisualization.Charting.Chart cht_MacroOndas;

*Verificar no momento da atualização do gráfico se a variável já não foi instanciada e só criar uma nova caso precise
private void button1_Click(object sender, EventArgs e)
{
        if (cht_MacroOndas == null)
        {
                cht_MacroOndas = new Chart();
                this.Controls.Add(cht_MacroOndas);
        }

        ConfigurarChat(cht_MacroOndas);
}

Lembre-se de limpar as coleções ao usar o objeto chart anterior, eu coloquei esse método ConfigurarChat apenas para deixar claro que nesse ponto você configuraria o gráfico, nele você teria que zeras as coleções Series, Legends, ChartAreas ou qualquer outra que você adiciona ao preencher os dados.


text:
Q: Excel VBA: How to find max/min of a range while ignoring error cells How can I use VBA in Excel to determine the max/min of a range that contains error cells such as #N/A or empty cells?  I know this is a fairly easy task to conquer with Excel array formulas using something like
=MIN(IF(A1:A10="#N/A"))
but I would very much like to accomplish this using VBA.
I'm dealing with several thousand lines of data so the speediest solution would be preferred.
Thank you so much!

A: You can use Evaluate or the shortcut [] to return the VBA equivalent of a formula
So the Excel array formula
=MIN(IF(NOT(ISNA(A1:A10)),A1:A10))
can be used in code like
Sub Test()
MsgBox [MIN(IF(NOT(ISNA(A1:A10)),A1:A10))]
End Sub


text:
Q: Receiving values from channels in Go Why doesn't the last result returned from go sum(s[len(s)/2:], c)(the second one) be assigned to x?
The two <-cs confuse me.
This code is from A Tour of Go - [Channels].
package main

import "fmt"

func sum(s []int, c chan int) {   // int is the return value type
  sum := 0
  for _, v := range s {
    sum += v
  }
  c <- sum // Sends sum to c
}

func main() {
  s := []int{7, 2, 8, -9, 4, 0}

  c := make(chan int)
  go sum(s[:len(s)/2], c)
  go sum(s[len(s)/2:], c)

  x, y := <-c, <-c                 // receive from c

  fmt.Println(x, y, x+y)
}

A: Do you mean this line?
x, y := <-c, <-c

That's a "tuple assignment".
In this case, it would be equivalent to doing:
x := <-c
y := <-c

So the second value read from c would be assigned to y.
You can read more about it here:
https://golang.org/ref/spec#Assignments
About the order in which the values are actually written to c, since two independent goroutines are being triggered here:
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)

The order in which they end up processing and writing to c is not "guaranteed", so you can expect either one of the values be assigned to x and y in different runs.
Since the values are being added to calculate the final result, this is not a problem in this case.


text:
Q: How do you securely erase remapped bad sectors on HDD in Linux? I have run badblocks on my HDD in Linux. No badblocks were found. However some bad sectors may have been previously detected and remapped; if this is the case, the badblocks test would not have found anything. Is it possible for me to securely erase those bad sectors, if there are any?

A: You can check if there were sectors reallocated with smartctl (look at Reallocated_Sector_Count, the last column is the raw value).
If your harddisk supports the security feature set, you can issue a SECURITY ERASE UNIT command in enhanced erase mode, which will also erase reallocated user data (see p. 215). However, this command will also erase all other data.
The tool hdparm can be used to perform such an erase.
I'm not aware of any standardized protocol to get a list of reallocated sectors from a harddisk, or to access the reallocated sectors directly (after all, they are reallocated, so they don't have any LBN associated with them anymore).


text:
Q: Ruby: how to generate HTML from Markdown like GitHub's or BitBucket's? On the main page of every repository in GitHub or BitBucket it shows the Readme.md in a very pretty format.
Is there a way to make the same thing with ruby? I have already found some gems like Redcarpet, but it never looks pretty. I've followed this instructions for Redcarpet.
Edit:
After I tried Github's markup ruby gem, the same thing is happening.
What is shown is this:

And what I want is this:

And I'm sure it's not only css missing, because after 3 backquotes (```) I write the syntax like json or bash and in the first image it is written.
Edit2:
This code here:
  renderer = Redcarpet::Render::HTML.new(prettify: true)
  markdown = Redcarpet::Markdown.new(renderer, fenced_code_blocks: true)
  html = markdown.render(source_text)
  '<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>'+html

Generated this:

A: Github provides its own ruby gem to do so: https://github.com/github/markup.
You just need to install the right dependencies and you're good to go.

A: You need to enable a few nonstandard features.
Fenced code blocks
Fenced code blocks are nonstandard and are not enabled by default on most Markdown parsers (some older ones don't support them at all). According to Redcarpet's docs, you want to enable the fenced_code_blocks extension:

*

*:fenced_code_blocks: parse fenced code blocks, PHP-Markdown style. Blocks delimited with 3 or more ~ or backticks will be considered as code, without the need to be indented. An optional language name may be added at the end of the opening fence for the code block.

Syntax Highlighting
Most Markdown parsers to not do syntax highlighting of code blocks. And those that do always do it as an option. Even then, you will still need to provide your own CSS styles to have the code blocks styled properly. As it turns out, Redcarpet does include support for a prettify option to the HTML renderer:

*

*:prettify: add prettyprint classes to <code> tags for google-code-prettify.

You will need to get the Javascript and CSS from the google-code-prettify project to include in your pages.
Solution
In the end you'll need something like this:
renderer = Redcarpet::Render::HTML.new(prettify: true)
markdown = Redcarpet::Markdown.new(renderer, fenced_code_blocks: true)
html = markdown.render(source_text)

A: As @yoones said Github shares their way to do it but to be more precise they use the gem "commonmarker" for markdown. Though as far as I can tell this thing does not give the full formatted HTML file but only a piece that you insert into <body>. So you can do it like I did:
require "commonmarker"

puts <<~HEREDOC
  <!DOCTYPE html>
  <html>
    <head>
      <style>#{File.read "markdown.css"}</style>
    </head>
    <body class="markdown-body Box-body">
      #{CommonMarker.render_html ARGF.read, %i{ DEFAULT UNSAFE }, %i{ table }}
    </body>
  </html>
HEREDOC

Where did I get the markdown.css? I just stole the CSS files from an arbitrary Github page with README rendered and applied UNCSS to it -- resulted in a 26kb file, you can find it in the same repo I just linked.
Why the table and UNSAFE? I need this to render an index.html for Github Pages because their markdown renderer can't newlines within table cells, etc. so instead of asking it to render my README.md I make the index.html myself.


text:
Q: Why do mathematicians understand structure preservation in a such a way? This question is about homomorphism and it's definition, which still feels kind of weird and unreliable to me.
To be more obvious, let's take graph $G = (Vertices(G), Edges(G))$. Then homomorphism of $G$ to somewhat graph $G'$ consists of two independent functions: $vrt : Vertices(G) \mapsto Vertices(G')$, $edg : Edges(G) \mapsto Edges(G')$. As such, in this particular case, homomorphism itself becomes a complicated object: it can be decomposed into some simpler primitives and thus one has to define certain rule how to apply those primitives to $G$ in order to get $G'$. Formally it looks somewhat like:
$$(\forall v_G \in Vertices(G) : vrt(v_G) \in Vertices(G')) \land (\forall e_G \in Edges(G) : edg(e_G) \in Edges(G')) \tag{1}$$
Observation #1: I can't see how it follows from the homomorphism's definition. There is no $(\circ)$ given explicitly; what kind of operation is it? Which are the elements of that operation? Can someone show me why $(vrt, edg)$ definitions follow from that?
Observation #2: I see homomorphism cares not to degrade existing structure, at the same time saying literally nothing about upgrading it? Since homomorphism is complicated object on it's own right, it can preserve existing structure and add something, which does not exist in the original one. And (1) requirement from the above would hold indeed. In order to ensure no upgrading took place, one should extend (1) to:
$$\text{vertices of the G did not degrade}
\land
\text{edges of the G did not degrade}
\land
\text{all the vertices of the G' came from the G}
\land
\text{all the edges of the G' came from the the G} \tag{2}$$
where:

*

*vertices of the G did not degrade = $(\forall v_G \in Vertices(G) :
   vrt(v_G) \in Vertices(G'))$;

*edges of the G did not degrade = $(\forall e_G \in Edges(G) : edg(e_G) \in Edges(G'))$

*all the vertices of the G' came from the G = $\not \exists v_{G'} \in vrt(G') : \forall v_G \in vrt(G) : vrt(v_G) \not = v_{G'}$

*all the edges of the G' came from the G = $\not \exists e_{G'} \in edg(G') : \forall e_G \in edg(G) : edg(e_G) \not = e_{G'}$

As a conclusion. I don't have any teacher to learn math, I do it only with help of the books published online and this platform. And for me it feels like homomorphism is both: 1) extraordinary important, 2) poorly defined idea. At the first sight it seems rigorous, but the deeper one dig, the sloppier it becomes. It feels like mathematicians just don't bother to redefine loosed things: whenever it comes down to somewhat specific structures, like graphs or monoid, or whatever else, homomorphism emerges not as direct consequence of the $F(g \circ f) = F(g) \bullet F(f)$, but as something intuitive, something like "we all understand that to preserve such-and-such particular structure, one has to fulfill following requirements". And yet I haven't seen "no-upgrade" requirement (observation #2), which seems quite valuable.
So, please, help me get deeper into math. What's wrong with my understanding?

A: Perhaps this is only a partial answer, but it seems to me that your misunderstanding might be that the term 'homomorphism' depends on what category you're talking about. For example, graph homomorphisms refer to morphisms in the category of graphs, where as group homomorphisms refer to morphisms in the category of groups. If you could define a group structure on your graph then you could view your graph as an object in the category of groups, and then speak of group homomorphisms from your graph to other groups. But without a group structure, the term 'group homomorphism' doesn't make sense when speaking of graphs, just as the term 'group homomorphism' doesn't make sense when speaking of a general set without a group structure. The definition of morphism depends on the ambient category.

A: The definition of homomorphism from your other question that you linked to is not the general definition of homomorphism. It is instead the definition of homomorphism in a very, very specific context namely: the context of a set equipped with a binary operation.
That definition DOES work for groups, because a group is a set equipped with a binary operation satisfying three basic laws: associativity, identity, and inverse. There are also other types of mathematical structures which that definition works for, for example a monoid which is a set equipped with a binary operation satisfying two laws: associativity and identity.
However, that definition DOES NOT work for graphs, because a graph is not a set equipped with a binary operation. There is no "$\circ$" nor "$\bullet$" nor any other kind of binary operator in the definition of graphs.
Your question did not include the full definition of a graph, so I'll add what's missing (which has nothing to do with binary operators): a graph $G$ is a pair of subsets $(\text{Vertices}(G),\text{Edges}(G))$ equipped with a pair of functions $i_G : \text{Edges}(G) \to \text{Vertices}(G)$ and $t_G : \text{Edges}(G) \to \text{Vertices}(G)$. Intuitively, for each $E \in \text{Edges}(G)$, the notation $i_G(E) \in \text{Vertices}(E)$ stands for the initial vertex of the edge $E$, and $t_G(E) \in \text{Vertices}(E)$ stands for the terminal vertex of the edge $E$.
If you want to define homomorphisms between graphs, then you need to define them using the natural structures of graphs, not the structures from some unrelated category of mathematics such as sets equipped with a binary operation. Here's the proper definition:
Given graphs $G,G'$,  a homomorphism from $G$ to $G'$ consists of two functions $vrt : \text{Vertices}(G) \to \text{Vertices}(G')$ and $edg: \text{Edges}(G) \to \text{Edges}(G')$, which satisfy the following properties:

*

*For each $e \in \text{Edges}(G)$,
$$i_{G'}(edg(e)) = vrt(i_{G}(e))
$$
and
$$t_{G'}(edg(e)) = ver(t_G(e))
$$

In words, this says the initial vertex in $G'$ of the image of each edge $e$ of $G$ must equal the image of the initial vertex in $G$ of $e$, and the terminal vertex in $G'$ of the image of $e$ must equal the image of the terminal vertex in $G$ of $e$.
To summarize, the two functions $vrt$ and $edg$ in the definition of a graph homomorphism are not independent from each other, as your question indicates. They are constrained to preserve the existing structure of a graph. That structure has nothing to do with binary operators. Instead that structure, in a graph $G$, consists of the "initial endpoint function" $i_T(E)$ and the "terminal endpoint function" $t_G(E)$.

A: In general, perhaps the best advice is to be skeptical but open minded.  Observe what the standard notion of morphism does for you in each mathematical context, and observe the analogies between them.  In fact, the analogies are so strong that eventually people invented whole subjects to deal with them, category theory, universal algebra.  But these general abstract theories are definitely not the place to start learning mathematics.
I think if you just take the examples of theories that seem to concern you at the moment, you can identify two rather different sorts: There are algebraic structures like groups, rings, modules, etc.  and there are relational structures such as graphs and partially ordered sets.  Perhaps it would help you to make this distinction.
For the algebraic examples, a morphism is always a map, not necessarily injective or surjective, that preserves the algebraic operation or operations.  For example, for rings there are two operations $\cdot$ and $+$, and  the requirement is $\phi(x\cdot y) = \phi(x)\cdot \phi(y)$ and  $\phi(x + y) = \phi(x) + \phi(y)$.  (Frequently, one works with rings with multiplicative identity, and requires in addition that $\phi$ take the identity of one ring to the identity of the other.  You already see from this that there are choices to be made; there are  different theories depending on these choices.)
For graphs, there are also many slightly different flavors: graphs with only single edges allowed, graphs with multiple edges allowed, directed graphs, and more.  Each of these would require a slightly different notion of structure preserving map.  The simplest flavor would be graphs with only single edges between vertices (and possibly loops).  This is the flavor treated in the wikipedia article https://en.wikipedia.org/wiki/Graph_homomorphism.  In this case the graph consists of the vertex set and a relation $e(x,y)$ which is symmetric but neither transitive nor reflexive.  Namely $e(x, y)$ holds if there is an edge connecting vertices $x$ and $y$.  Now a graph homomorphism is a map on vertices which preserves the relation:  $e(x, y)$ implies $e(\phi(x), \phi(y))$.
As soon as one allows more complicated setups, say graphs with multiple edges, then one has to invent a more complicated way both to describe what a graph is and what a morphism is.  But the idea should still be that edges get mapped to edges.  You could just start with this intuitive idea yourself and work out how to formalize this.
Now if you really want to make an effort, you could bring the algebraic examples and the relational examples under one roof, e.g by viewing an operation as a relation,  $R(x, y, z)$ holds if $x\cdot y = z$.  Now the homomorphism property would translate to $R(x, y, z)$ implies $R(\phi(x), \phi(y), \phi(z))$.  For me, this does absolutely nothing to help me understand groups or rings.


text:
Q: calculate probability without having to draw out all possible combinations How do you calculate: "If you roll two fair six-sided dice, what is the probability that the sum is 5 or lower?" Without having to draw a large table like so:
img
Does an equation of some sort exist?

A: Without constructing a table, we can define a random variable $X$: sum of values of two dices. Then we are looking for
$$P(X \le 5) = P(X = 2) + P(X = 3) + P(X = 4) + P(X = 5)$$
$$= \frac{1}{36}+\frac{2}{36}+\frac{3}{36}+\frac{4}{36} = \frac{5}{18}$$
because $P(X = 2)$ has one possible combination: $(1,1)$;
$P(X = 3)$ has two: $(1,2)$ or $(2,1)$;
$P(X = 4)$ has three: $(1,3)$, $(3,1)$ or $(2,2)$;
$P(X = 5)$ has four $(1,4)$, $(4,1)$, $(2,3)$ or $(3,2)$.

A: The answer is the sum of natural numbers form $1$ to $4$, which is $4(5)/2 =10.$ divided by the total number of outcomes which is $36$
That makes it $\frac {10}{36}=0.2777$
Note that if the first die is $1$, we have $4$ possible outcome for the second one.
Similarly for the first one being $2$ we have $3$ possibilities for  the second one and so forth.


text:
Q: How do I read a video from Minoru 3d webcam in OpenCV Python? I am working on opencv python installed on Windows 10 (64 bit)
I am using Minoru 3D webcam.I wrote a code on reading a video from 2 lens camera.I am here with the following error:
Traceback (most recent call last):
  File "C:/Python27/pythoncode/reading a video from two lens", line 6, in <module>
    if(cap & cap1):
TypeError: unsupported operand type(s) for &: 'cv2.VideoCapture' and 'cv2.VideoCapture'

Code:
import numpy as np
import cv2
import matplotlib.pyplot as plt
cap = cv2.VideoCapture(0)
cap1 = cv2.VideoCapture(1)
if(cap & cap1):
    while(true):
        ret, frame=cap.read()
        cv2.imshow('bgr image',frame)
        print ret
        ret1, frame1=cap1.read()
        cv2.imshow('image1',frame1)
        print ret1
        if cv2.waitKey(30)>=0:
            break
        cap.release()
        cap1.release()
        cv2.destroyAllWindows()

A: Your code and error messages were incredibly hard to read; please put four spaces before every line of code, or select all of the code and press Ctrl+K, turning
Traceback (most recent call last): File "C:/Python27/pythoncode/reading a video from two lens", line 6, in if(cap & cap1): TypeError: unsupported operand type(s) for &: 'cv2.VideoCapture' and 'cv2.VideoCapture' import numpy as np import cv2 import matplotlib.pyplot as plt cap = cv2.VideoCapture(0) cap1 = cv2.VideoCapture(1) if(cap & cap1): while(true): ret, frame=cap.read() cv2.imshow('bgr image',frame) print ret ret1, frame1=cap1.read() cv2.imshow('image1',frame1) print ret1 if cv2.waitKey(30)>=0: break cap.release() cap1.release() cv2.destroyAllWindows()
into
Traceback (most recent call last):
  File "C:/Python27/pythoncode/reading a video from two lens", line 6, in <module>
    if(cap & cap1):
TypeError: unsupported operand type(s) for &: 'cv2.VideoCapture' and 'cv2.VideoCapture'

    import numpy as np
    import cv2
    import matplotlib.pyplot as plt
    cap = cv2.VideoCapture(0)
    cap1 = cv2.VideoCapture(1)
    if(cap & cap1):
        while(true):
            ret, frame=cap.read()
            cv2.imshow('bgr image',frame)
            print ret
            ret1, frame1=cap1.read()
            cv2.imshow('image1',frame1)
            print ret1
            if cv2.waitKey(30)>=0:
                break
        cap.release()
        cap1.release()
    cv2.destroyAllWindows()

According to the error message, the error is in the line if(cap & cap1): and it occurred because you cannot use the operator & (bitwise AND) on two cv2.VideoCapture objects.
I assume you are trying to make sure neither variable is None, and the way to do this is to change the line to:
if (cap != None) and (cap1 != None):


text:
Q: Using .NET Authentication for whole site and internal sites I have a site that has certain areas that are password protected with .NET membership.  I need to make a staging site that encapsulates the whole site in another password protected area controlled by admins.
Can I use 2 membership databases in one application?
Is there a better way to do this?
I am using web forms still and forms authentication.


text:
Q: Exceptions in .gitignore do not exclude files in subfolders When I run git status it seems that it's only tracking files that have been modified but not new files in subfolders.
This is pretty much my .gitignore:
# Ignore everything
*

# But this files that i want to track
!.config/
!.fonts/
!.bashrc
!.gitignore
!.profile
!.Xresources
!.vimrc
!.zshrc

!README.md

It is in my $HOME.
If I create a new file in directories .fonts/ or .config/ it seems like git is ignoring them. But it does track files like .vimrc or .zshrc
I tried to open this repo with GitKraken and it works how I'm expecting.
I only have this error when I run git status in command line

A: You could prefix these patterns with two asterisks (**) to match these files in any directory:
!**/.config/
!**/.fonts/
!**/.bashrc
!**/.gitignore
!**/.profile
!**/.Xresources
!**/.vimrc
!**/.zshrc

!**/README.md


text:
Q: Programatically create a Popup with a Child element initialised by Caliburn Micro Windows.Media.Captures has a handy CameraCaptureUI class that can be instantiated as follows to show a dialog to the user to capture photos or videos:
// Create dialog to Capture Video
CameraCaptureUI dialog = new CameraCaptureUI();
dialog.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4;

StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Video);
if (file != null)
{
   // Do something with file...
}

I would like to create my own custom audio capture class that works in a very similar way:
// Create dialog to Capture Audio
AudioCaptureUI dialog = new AudioCaptureUI();

StorageFile file = await dialog.CaptureFileAsync();
if (file != null)
{
   // Do something with file...
}

To do the above, I created the following three files:

*

*AudioCaptureUI - The class that a user instantiates to show the audio capture dialog

*AudioCaptureView - UI View for the audio capture experience

*AudioCaptureViewModel - ViewModel that contains all the audio capture logic

To create a full screen audio capture dialog, I have figured out that the best way is to use a Popup and set its child to the AudioCaptureView. The problem I have with this approach is that it is pushing me use a View-First pattern. Since I am using Caliburn Micro, I wanted to be able to use CM to instantiate a View by creating the ViewModel first.
What I currently have is something on the following lines:
public class AudioCaptureUI
{
    private Popup _popup;
    private TaskCompletionSource<StorageFile> _taskCompletionSource;

    public IAsyncOperation<StorageFile> CaptureFileAsync()
    {
        // Force my View to be full screen
        AudioCaptureView audioCaptureView = new AudioCaptureView
        {
            Width = Window.Current.Bounds.Width,
            Height = Window.Current.Bounds.Height
        };

        // Creating View, instead of a ViewModel. Renders Caliburn Micro useless!
        _popup = new Popup { Child = audioCaptureView };

        if (_popup.Child != null)
        {
            SubscribeEvents();
            _popup.IsOpen = true;
        }

        return AsyncInfo.Run(WaitForInput);
    }

    ...
}

The above pattern works. However, I am forced to wire all my actions manually and cannot leverage Caliburn Micro's MVVM goodness.
How else should I instantiate a ViewModel programatically from my AudioCaptureUI class?
It is also important to highlight that I am working on a Windows Store app and using the WinRT CM port.

A: You might have some success with the Caliburn.Micro WindowManager. There isn't a great deal about it in the official documentation (you're best off searching Google and the CM discussions). I've used it in one of my applications where I needed to host a particular ViewModel in a new window, and wanted to utilise all of the Caliburn.Micro goodness (and my existing Views).
Have a look at the Caliburn.Micro.IWindowManager interface, you'll see some handy methods that you can call from a WindowManager instance (depending on the popup type you're after).
public interface IWindowManager
{
    bool? ShowDialog(object rootModel, object context = null, IDictionary<string, object> settings = null);
    void ShowPopup(object rootModel, object context = null, IDictionary<string, object> settings = null);
    void ShowWindow(object rootModel, object context = null, IDictionary<string, object> settings = null);
}

In my application, to pop up my a Window with my ViewModel of choice, I did something along these lines (your names inserted):
// Some basic Window settings.
dynamic settings = new ExpandoObject();
settings.Title = "Test Window";
settings.WindowStartupLocation = WindowStartupLocation.Manual;
settings.SizeToContent = SizeToContent.Manual;
settings.Width = 450;
settings.Height = 300;

var localAudioCaptureViewModel new AudioCaptureViewModel ();
WindowManagerFactory.WindowManager.ShowWindow(localAudioCaptureViewModel, null, settings); // I didn't require context (null)

Caliburn.Micro should resolve your Views to the correct ViewModels, and you're good to go.

A: You could always port the WindowManager to WinRT in your own project. Looking at the source I don't think too much will need to change.  https://caliburnmicro.codeplex.com/SourceControl/latest#src/Caliburn.Micro.Platform/net40/WindowManager.cs
You could bring over the Interface as well and use DI but for the sake of time here is the stand alone class. The main part for Model first binding is the ViewLocator.LocateForModel which returns the View from the ViewModel (aka the magic)
using System;
using System.Collections.Generic;
using Windows.UI.Xaml.Controls.Primitives;

namespace Caliburn.Micro
{
    public class WindowManager
    {
        public virtual void ShowPopup(object rootModel, object context = null, IDictionary<string, object> settings = null)
        {
            var popup = CreatePopup(rootModel, settings);
            var view = ViewLocator.LocateForModel(rootModel, popup, context);

            popup.Child = view;
            //popup.SetValue(View.IsGeneratedProperty, true);

            ViewModelBinder.Bind(rootModel, popup, null);
            Caliburn.Micro.Action.SetTargetWithoutContext(view, rootModel);

            var activatable = rootModel as IActivate;
            if (activatable != null)
            {
                activatable.Activate();
            }

            var deactivator = rootModel as IDeactivate;
            if (deactivator != null)
            {
                popup.Closed += delegate { deactivator.Deactivate(true); };
            }

            popup.IsOpen = true;
            //popup.CaptureMouse();
        }

        protected virtual Popup CreatePopup(object rootModel, IDictionary<string, object> settings)
        {
            var popup = new Popup();

            ApplySettings(popup, settings);

            return popup;
        }

        bool ApplySettings(object target, IEnumerable<KeyValuePair<string, object>> settings)
        {
            if (settings != null)
            {
                var type = target.GetType();

                foreach (var pair in settings)
                {
                    var propertyInfo = type.GetPropertyCaseInsensitive(pair.Key);

                    if (propertyInfo != null)
                    {
                        propertyInfo.SetValue(target, pair.Value, null);
                    }
                }

                return true;
            }

            return false;
        }
    }
}

Then all you need to do is create an instance and give it a ViewModel:
var windowManager = new WindowManager();
windowManager.ShowPopup(new MyPopupThingViewModel());

Note: I've only used this in an 8.1 app so not 100% sure if it will completely work with 8.0


text:
Q: Changing HTML form layout based on select option selected using Thymeleaf Is it possible to set a variable in thymeleaf and then change it depending on an option in a select element and then display a specific div based on the selection? Here's what I mean.
I have three options in select:
1) DESKTOP_PC
2) LAPTOP_PC
3) TABLET_PC

When the user selects DESKTOP_PC, I would like to show the div with the related inputs for it. Likewise if it's LAPTOP_PC or TABLET_PC.
Only problem is, I'm not sure how I would go about doing this.
The other thing, is that I have the following:
In my entry class I have an enum class:
public static enum Type {
    DESKTOP_PC,
    LAPTOP_PC,
    TABLET_PC
}

In my Thymeleaf form, I have the following to access and display this enum:

Type

    <select name="type" th:field="$*{type}">
        <option th:each="type : ${T(com.project.entities.Entry.Type).values()}" th:value="${type}" th:text="${type}" ></option>
    </select>

Any help would be much appreciated!

Thanks

A: it is very possible, but has very little to do with Java or Thymeleaf, even though you could do it with them too (not recommended)
All you need to do is create basic JavaScript function that onClick to different options makes different divs visible (through adding/removing classes with css defined in them like display: none;).
Of course you could implement it on backend, through each click being a separate request sent to a controller that then saves the option into a for example boolean variable and based on this variable returns a different thymeleaf view but that is an awkward looking solution for such simple case that doesn't really require backend processing.
Any simple book on JS will show you how to do this, I can recommend A smarter way to learn JS for this scenario

A: To achieve what you want we need to to take help of Javascript or jQuery.

*

*Write an onchange function on select tag.

*Get the value of option selected inside the function.

*Show/hide div depending on value

Vote if it helps you


text:
Q: classpath error on running xerces java's dom.Writer() program I understand this question couldn't be more beginner, but I am having a hard time to grasp why it is not working. The Apache Xerces-J comes with a binary distribution that I am sure many of us uses. Within it, there are all the library jars and sample jars dom.Writer being one of it I am trying to run:
LICENSE                         NOTICE                      resolver.jar
LICENSE-SAX.html                NOTICE.resolver.txt         samples/
LICENSE.DOM-documentation.html  NOTICE.serializer.txt       serializer.jar
LICENSE.DOM-software.html       Readme.html                 xercesImpl.jar
LICENSE.resolver.txt            data/                       xercesSamples.jar
LICENSE.serializer.txt          docs/                       xml-apis.jar

My understanding is that Java's default class path will search current direcotry first, so if I run
java dom.Writer
in that directory, then it should work ... shouldn't it? but no, and then I tried a bunch of different ways of giving the classpath, including java6's wildcard, nothing works.
so I know xercesSamples.jar contains dom.Writer, but I couldn't figure out how to run it .. silly, huh? Someone please enlighten me.
The error message is like:
Exception in thread "main" java.lang.NoClassDefFoundError: dom/Writer
Caused by: java.lang.ClassNotFoundException: dom.Writer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

Thanks
Oliver

A: Include xercesSamples.jar in your classpath. Jars have to explicitly specified in classpath.
java -cp xercesSamples.jar:. dom.Writer

A: What @Kal said is the correct answer.  however, the meta-answer, is why are you using xerces in the first place?  any recent jvm comes with an xml DOM api implementation built in.  unless you need some specific xerces feature, stick to the builtin implementations.


text:
Q: PostgreSQL select now()::timestamp differs from default now()::timestamp In my program every table has a column last_modified:
last_modified int8 DEFAULT (date_part('epoch'::text, now()::timestamp) * (1000)::double precision) NOT NULL

For update I added a trigger:
CREATE OR REPLACE FUNCTION sync_lastmodified() RETURNS trigger AS $$
BEGIN
  NEW.last_modified := (date_part('epoch'::text, now()::timestamp) * (1000)::double precision);

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER
  sync_lastmodified
BEFORE UPDATE ON
  ourtable
FOR EACH ROW EXECUTE PROCEDURE
  sync_lastmodified();

They should write current time as a long value into the last_modified column on update/insert.
However, it is not working as I expected.
To reproduce the issue, I did update and got the following:
last_modified value equals 1543576224455 (Friday November 30, 2018 16:10:24 (pm) in time zone Asia/Tashkent (+05))

Almost at the same time I run the function now from pgAdmin:
SELECT now()

and got the result:
2018-11-30 11:10:36.891426+05

To check system time within a few seconds I run timedatectl status from terminal and got the following result:

The question is why the function now() gives a time with 5 hours
  difference when I run it from trigger or as a default value when
  insert?

A: epoch will give you the number of seconds since the epoch. As the documentation says:

epoch
For timestamp with time zone values, the number of seconds since 1970-01-01 00:00:00 UTC (can be negative)

Since you are offset by 5 hours from UTC, that explains the difference.


text:
Q: How to add Custom JS in admin side? I want to add custom JS on product edit page in admin side. After doing some R&D, i found a solution but that didn't work. What I have done so far,
app/code/Vendor/Module/view/adminhtml/layout/catalog_product_bundling_tags.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="Vendor_Module::js/catalog_product_bundling_tags.js"/>
    </head>
</page>

app/code/Vendor/Module/view/adminhtml/web/js/catalog_product_bundling_tags.js
require([
    'jquery'
], function ($) {
    'use strict';
    $(document).ready(function () {
        alert("Hey");
        console.log("Hi I am coming from sonybundling");
        let bundlingTags =  $('input[name="product[bundling]"]').click(function() {
            console.log("bundlingTags ===> ", bundlingTags);
        });
    });
});

But when i load the page it couldn't reflect.
Kindly guide me where I am doing mistake ?

A: You can create following file:

app/code/Vendor/Module/view/adminhtml/layout/catalog_product_edit.xml

with following content:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="Vendor_Module::js/catalog_product_bundling_tags.js"/>
    </head>
</page>

create js file at:

app/code/Vendor/Module/view/adminhtml/web/js/catalog_product_bundling_tags.js


text:
Q: Magento 2: Static images returns 404 after refresh This is driving me crazy.
I added a couple of images to my theme. They are on my theme_name/web/images folder.
The images are returning a 404.
I delete the folder pub/static/frontend/vendor/theme_name/en_US and on the first access they load. As soon as I try to load the images again they return 404 again.
The images are in the correct path.
Any ideas on what could be causing this? Permissions?

A: Well, after days of looking into this problem I realised it had nothing to do with magento at all.
Our designer was uploading the images trough Mega (client), and for some reason after I downloaded the images that problem occurred.
After sending me the same images another the problem was solved.

A: I had the same case with facebook logo (svg). I assume the logo is in a compressed format. To fix the 404, I made a copy of the logo with inskape and replace the original image with the new file. After this process the image is four time bigger (600b for 2.2kb).

A: Call Media Images in PHTML Files
<img src="<?php echo $mediaUrl.'wysiwyg/demo.jpg'; ?>" />

Call Web Images in PHTML File
<img src="<?php echo $this->getViewFileUrl('images/demo.png'); ?>" />

Call Web Images in Static block and CMS page

Call Media Images in Static block and CMS page
" />


text:
Q: Confused by converting WHNF to NF in Haskell In a simple example, converting WHNF to NF by printing works fine
Prelude> let x = 1 + 2 :: Int
Prelude> :sprint x
x = _
Prelude> x
3
Prelude> :sprint x
x = 3

But in a case, the type is not declared it doesn't work.
Prelude> let x = 1 + 2
Prelude> :sprint x
x = _
Prelude> x
3
Prelude> :sprint x
x = _

Can you explain in some details why conversion doesn't work in the last case?

A: Since in GHCi the monomoprhism restriction is disabled, the last x is a polymorphic value of type x :: Num a => a. So it is not a simple integer, but a kind-of function DictNum a -> a which is ready to create a value in any numeric type.
Indeed, x :: Int, x :: Float, x :: Double will run and produce  different values. These values are numerically the same, but computationally different, since they are representations in different types.
Since x is, essentially, "multiple values, generated on demand", there is no single WHNF or NF here.
Note that if we compute (x :: Int) + (x :: Int), then x is being recomputed twice: GHC in general will not "cache" the WHNF at type Int for successive computations. This is similar to f 3 + f 3, where f 3 is not cached (memoized).
This duplicate computation is precisely what the monomorphism restriction tries to avoid.


text:
Q: How to assign one same label for multiple value in non-queried available values in ssrs 2005 report? Parameters - Multiple Values For One Label - Possible?
Sorry my modified Question.....
I have question to ask,...
Is it possible to have multiple values for ONE label in non-queried available values in SSRS 2005? i want to join fields value in a single row like,
Works: (But this bring a long list in drop down menu - which i donot want)

Label                Value
---------------------------
Site-1                 150
Site-1                 151
Site-2                 152
Site-2                 153

Required result (Which i want - in one line)

Label                Value
---------------------------
Site-1                 150,151
Site-2                 152,153
(which will bring one label and related multi-value in drop down or combo box.
But the problem is that ColumnName IN (@Site) does not work with multi-value.)

More description of the problem:
Let say, I have a field/column
 Name = Site
 Value = C150,C151, C152, C153

I want drop down menu on report with
 C150,C151(as Site-1) & C152,C153(as Site-2)

So I created parameter i.e. @getSite and set values as
multi-value in the report as
 Label                       Value
 ---------------------------------------------
 Site-1                      (150,151)
 Site-2                      (152,153)

And set my parameter as @getSite:= Parameters!@getSite.Value
And Query i wrote as,
SELECT  * FROM ..
WHERE Site IN (@getDisease)

But after all these, my report result is empty,literally no result.
It seems like if i select only one value as Site-1 = 150, then it works
but not two or more values in one line,
why it is not possible?? if yes then how?
Please help!!!

A: Yes just Right Click on your parameter in your Report Data window under Parameters folder and select the check box for allow multiple values as follows

this is what I said before you need to put your column name inside a set of paranthesis something like this
SELECT  * FROM ..
       WHERE (Site IN (@getDisease))

A: I have been working on this problem for a while and I think I have finally figured it out...
Basically you need to use a backwards case statement in your SELECT statement, put that in a derived query and then reference it in the outer WHERE clause..
SQL:
SELECT * FROM
(
SELECT
Label
, value
, CASE WHEN [value] IN (150,151) THEN 'site-1' WHEN [value] IN (152,153) THEN 'site-2' END AS [grouped_values]
)
WHERE grouped_values IN (@getSite);

*Note: This answer only works on values that are mutually exclusive, if both sets had the same value included then it would be problematic..
--
Hopefully this can put you in the right direction. I am finding a lot of the reporting services tricks require reverse engineering or at least some reverse thinking.
cheers,
Michael


text:
Q: Add a vectorusing Latex as legends in Matlab In example:Add a vector as legends in Matlab posted Mar 2 '15 at 13:45
I want to use the Latex $\mathcal{n}$
By modifying the line
LegendString{k} = sprintf('n = %i',n(k));

by
LegendString{k} = sprintf('\mathcal{n}= %i',n(k),'Interpreter','latex');

But it does not work.Thanks

A: You are mixing up a few things. sprintf only generates a string or actually a vector of characters. Therefore, there is no interpreter for sprintf.
The interpreter can only be specified for the function rendering the string. Therefore, your example has to be changed to
LegendString{k} = sprintf('$\\mathcal{n}= %i$',n(k));

...

legend(LegendString, 'Interpreter', 'Latex');

legend is the function interpreting the string, therefore Latex has to be specified there. Further, using Latex requires $ around your string to be interpreted in the mathematical environment.
Also, you need to have \\ rather than \ since sprintf should not use it as a escape character but just keep it in the string.


text:
Q: Sprint webflux WebClientResponseException response body contains the array of string the WebClientResponseException response return the res.getResponseBodyAsString() as a value as
"[\"Name is invalid.\",\"RegisterationNumber is invalid.\"]"

but I want to convert this and return to the caller as below
"Name is invalid. , RegisterationNumber is invalid."

code
.onErrorResume(throwable -> {
                    if (throwable instanceof WebClientResponseException) {
                        WebClientResponseException res = ((WebClientResponseException) throwable);
                        if (res.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
                            return createValidation(res.getResponseBodyAsString());
                        }
                    }