text:
Q: VisualStateManager fails to start animation on UserControl I'm trying to start a animation on a UserControl using the VisualStateManager in a Windows Phone 7 Silverlight project but it won't work. GoToState just keep returning false.
The code consists of a VisualState-behaviour which is running the GoToState when a State-property on the datacontext is changed, which happens when the button in the UI is clicked:
What am I doing wrong?
XAML:
    <Grid>
        <UserControl x:Name="_testSubject" l:VisualStates.CurrentState="{Binding State}" />
        <Button VerticalAlignment="Bottom" Content="Change state" Click="Button_Click" />
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup>
                <VisualState x:Name="State2">
                    <Storyboard>
                        <ColorAnimation From="Red" To="Green" Duration="0:0:10" Storyboard.TargetProperty="Background" Storyboard.TargetName="_testSubject" />
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>

C#:
public class Test : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); }
    string _state;
    public string State { get { return _state; } set { _state = value; OnPropertyChanged("State"); } }
}

public static class VisualStates
{
    public static readonly DependencyProperty CurrentStateProperty =
        DependencyProperty.RegisterAttached("CurrentState", typeof(String), typeof(VisualStates), new PropertyMetadata(TransitionToState));

    public static string GetCurrentState(DependencyObject obj)
    {
        return (string)obj.GetValue(CurrentStateProperty);
    }

    public static void SetCurrentState(DependencyObject obj, string value)
    {
        obj.SetValue(CurrentStateProperty, value);
    }

    private static void TransitionToState(object sender, DependencyPropertyChangedEventArgs args)
    {
        Control c = sender as Control;
        if (c != null)
        {
            bool b = VisualStateManager.GoToState(c, (string)args.NewValue, false);
        }
        else
        {
            throw new ArgumentException("CurrentState is only supported on the Control type");
        }
    }

public partial class MainPage : PhoneApplicationPage
{
    public MainPage() { InitializeComponent(); }

    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
        _testSubject.DataContext = new Test();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ((Test)_testSubject.DataContext).State = "State2";
    }
}

A: just a wild guess, but could it be that it is being executed in the wrong thread? You might want to use the dispatcher to execute it on the correct (UI) thread.
Does the GoToState work in the Button_Click function ?
private void Button_Click(object sender, RoutedEventArgs e)
{
    bool b = VisualStateManager.GoToState(this, "State2", false);
}

And is TransitionToState being called when you execute your code.
This would rule out any other problems.
UPDATE
The following works for me. I came accross some problems with setting the Background. First of all this doesn't have any effect on a UserControl and second it is not possible to change the background using a Color animation that's why I change the opacity.
MainPage.xaml
<Grid x:Name="ContentPanel"
      Grid.Row="1"
      Margin="12,0,12,0">
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <l:TestControl x:Name="_testSubject"
                   Grid.Row="0"
                   l:VisualStates.CurrentState="{Binding State}" />

    <UserControl x:Name="_test2Subject"
                 Height="100"
                 Grid.Row="1"
                 l:VisualStates.CurrentState="{Binding State}">
        <Grid x:Name="aLayoutRoot"
              Background="Wheat">
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="State2">
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetName="aLayoutRoot"
                                             Storyboard.TargetProperty="Opacity"
                                             From="1"
                                             To="0"
                                             Duration="0:0:2"
                                             AutoReverse="True" />
                        </Storyboard>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
        </Grid>
    </UserControl>

    <Button Click="Button_Click"
            Content="Click"
            Grid.Row="2" />

</Grid>

TestControl.xaml
<UserControl x:Class="PhoneApp1.TestControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="480" d:DesignWidth="480">

    <Grid x:Name="LayoutRoot" Background="Wheat">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="State2">
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="LayoutRoot"
                                         Storyboard.TargetProperty="Opacity"
                                         From="1"
                                         To="0"
                                         Duration="0:0:2"
                                         AutoReverse="True" />
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>
</UserControl>

Test.cs / TransitionToState method
private static void TransitionToState(object sender, DependencyPropertyChangedEventArgs args)
{
    UserControl c = sender as UserControl;
    if (c != null && args.NewValue != null)
    {
        bool b = VisualStateManager.GoToState(c, (string)args.NewValue, true);
        var a = b;
    }
}

MainPage.cs
public MainPage()
{
    InitializeComponent();

    _testSubject.DataContext = new Test();
    _test2Subject.DataContext = new Test();

}

private void Button_Click(object sender, RoutedEventArgs e)
{
    ((Test)_testSubject.DataContext).State = "State2";
    ((Test)_test2Subject.DataContext).State = "State2";
}

I would also recommend using ControlTemplates to assign VisualStates instead of defining them directly on the control. This will give you more flexibility, better maintenance, etc..
Hope this helps.

A: I had a similar issue I found a solution that helped me and may be someone find it useful
if the usercontrol is hosted in layoutawarepage
<my:usercontrole Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates" />

otherwise you will have to de the follow (example can be found in the layout aware page)

*

*make event handler on sizechanged

*in the event handler check the viewstate with ApplicationView.Value

*move to that state with VisualStateManager.GoToState
Edit: Sorry for misunderstanding I thought that it is winRT App


text:
Q: R: How to replace several different values in a more efficient way? Given this dataset, I would like to know if there is a way to solve this in a more efficient and less repetitive way.
The dataset is made up of a series of courses where some are repeated and written differently (all in capital letters or with extra spaces, etc.)
To solve this problem I use the following method:
# Load dataset
courses <- read.csv('courses.csv')

courses$x[courses$x == 'KOE'] <- 'Koe'
courses$x[courses$x == 'koe'] <- 'Koe'
courses$x[courses$x == 'BENL'] <- 'Benl'
courses$x[courses$x == 'engin'] <- 'Engine'
courses$x[courses$x == 'Fiqh'] <- 'Fiqh Fatwa'
courses$x[courses$x == 'Fiqh fatwa '] <- 'Fiqh Fatwa'
courses$x[courses$x == 'Islamic education'] <- 'Islamic Education'
courses$x[courses$x == 'KIRKHS'] <- 'Kirkhs'
courses$x[courses$x == 'Laws'] <- 'Law'
courses$x[courses$x == 'Pendidikan islam'] <- 'Pendidikan Islam'
courses$x[courses$x == 'Pendidikan Islam '] <- 'Pendidikan Islam'
courses$x[courses$x == 'psychology'] <- 'Psychology'

What other more efficient and less repetitive way exists to solve this problem?

A: You could do:
courses$x <- tools::toTitleCase(tolower(courses$x))

courses
                   x
1                Koe
2                Koe
3               Benl
4              Engin
5               Fiqh
6         Fiqh Fatwa
7  Islamic Education
8             Kirkhs
9               Laws
10  Pendidikan Islam
11  Pendidikan Islam
12        Psychology

Data:
courses <- data.frame(x = c("KOE", "koe", "BENL", "engin", "Fiqh", "Fiqh fatwa",
                             "Islamic education", "KIRKHS", "Laws", "Pendidikan islam",
                             "Pendidikan Islam", "psychology"))

A: How about
apply(courses, 2, (function(x) paste(toupper(substr(x, 1, 1)), tolower(substr(x, 2, nchar(x))), sep="")))
The anonymous function converts the first char to upper and the rest to lower. apply, applies to all elements
Something like
courses$y = sapply(courses$x, (function(x) paste(toupper(substr(x, 1, 1)), tolower(substr(x, 2, nchar(x))), sep="")))

would be nice too if you have other columns.
If you can install packages it's always better to use package, stringr has a lot function including str_to_title
str_to_title(courses$x)

will do what you seem to want.

redpajama_set_name: RedPajamaStackExchange


text: Q: Pods are grayed out in Target -> Linked Frameworks Problems with pods and frameworks not being found seem to be numerous on Stackoverflow and I have read many threads and tried many things (probably to the point of really messing up my project.) But I'm pretty sure that the grayed out framework means Xcode can't find the files and that is probably because a path variable isn't pointing Xcode to the correct directory. There seem to be many path variables to set and they can be set to search recursively and/or they can be $(inherited) from somewhere else. (This $(inherited) thing is also some kind of flag that pod update seems to complain about now and I'm not sure if I'm supposed to do something about that.) So, could someone tell me exactly which path variable points Xcode to the pod frameworks?


text:
Q: Error al refrescar tabla en XHTML (Primefaces JavaWeb) Tengo un problema al cargar una tabla desde una base de datos en MySQL. La tabla está en PrimeFaces y carga los datos de la base de datos cuando despliego la aplicación. Pero cuando modifico un dato, a pesar de que lo carga en la base de datos no lo muestra en la tabla.
Editado
Aquí algo del codigo.. no me funciona con la propiedad refrescar por medio del commandbutton ..

<p:panel id="tabla" style="width: 100% ; font-size: small; text-align: left ; border : none ;"  >
    <p:dataTable style="border : none ;"
                 id="tablePro" var="programacion" value="#{mantenimientoTvista.listaProgramaciontodo}" rows="10"
                 paginator="true"
                 paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                 rowsPerPageTemplate="5,10,15"
                 filteredValue="#{mantenimientoTvista.listaProgramaciontodo}"
                 emptyMessage="No se encontraron resultados"
                 selectionMode="single"
                 rowKey="#{programacion.idprogramacion}"
                 selection="#{mantenimientoTvista.programacionSeleccionado}"
                 >
        <p:ajax event="rowSelect" listener="#{mantenimientoTvista.funcionSeleccionarProd}" update="forma:growl ,:forma:campos" />

        <p:column headerText="nombre tecnico" width="30" filterBy="#{programacion.documentotecnico.personal.nombrepersonal}">
            <h:outputText value="#{programacion.documentotecnico.personal.nombrepersonal}"/>
        <p:column headerText="Tipo mant" width="5" filterBy="#{programacion.idclase.clasenombre}" filterMatchMode="contains">
            <h:outputText value="#{programacion.idclase.clasenombre}"/>
        </p:column>
    </p:dataTable>

</p:panel>

y este es el boton dejo el codigo aqui aparte ----------------------------------------

y aqui el codigo del value de listaidtecnicos (omiti muchas columnas para no pegar un codigo demasiado extenso solo necesito que se refresque el nombre del tecnico cuando lo cambio en la tabla).
Esto es de clase entidad apartir de base de datos ..
@Entity
@Table(name = "personal")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Personal.findAll", query = "SELECT p FROM Personal p"),
    @NamedQuery(name = "Personal.findByDocumentopersonal", query = "SELECT p FROM Personal p WHERE p.documentopersonal = :documentopersonal"),
    @NamedQuery(name = "Personal.findByApellidopersonal", query = "SELECT p FROM Personal p WHERE p.apellidopersonal = :apellidopersonal"),
    @NamedQuery(name = "Personal.findByClavepersonal", query = "SELECT p FROM Personal p WHERE p.clavepersonal = :clavepersonal"),
    @NamedQuery(name = "Personal.findByNombrepersonal", query = "SELECT p FROM Personal p WHERE p.nombrepersonal = :nombrepersonal")})
public class Personal implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "documentopersonal")
    private Long documentopersonal;
    @Size(max = 255)
    @Column(name = "apellidopersonal")
    private String apellidopersonal;
    @Size(max = 255)
    @Column(name = "clavepersonal")
    private String clavepersonal;
    @Size(max = 255)
    @Column(name = "nombrepersonal")
    private String nombrepersonal;
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "personal")
    private Administrador administrador;
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "personal")
    private Tecnicos tecnicos;

    public Personal() {
    }

    public Personal(Long documentopersonal) {
        this.documentopersonal = documentopersonal;
    }

    public Long getDocumentopersonal() {
        return documentopersonal;
    }

    public void setDocumentopersonal(Long documentopersonal) {
        this.documentopersonal = documentopersonal;
    }

    public String getApellidopersonal() {
        return apellidopersonal;
    }

    public void setApellidopersonal(String apellidopersonal) {
        this.apellidopersonal = apellidopersonal;
    }

    public String getClavepersonal() {
        return clavepersonal;
    }

    public void setClavepersonal(String clavepersonal) {
        this.clavepersonal = clavepersonal;
    }

    public String getNombrepersonal() {
        return nombrepersonal;
    }

    public void setNombrepersonal(String nombrepersonal) {
        this.nombrepersonal = nombrepersonal;
    }

    public Administrador getAdministrador() {
        return administrador;
    }

    public void setAdministrador(Administrador administrador) {
        this.administrador = administrador;
    }

    public Tecnicos getTecnicos() {
        return tecnicos;
    }

    public void setTecnicos(Tecnicos tecnicos) {
        this.tecnicos = tecnicos;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (documentopersonal != null ? documentopersonal.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Personal)) {
            return false;
        }
        Personal other = (Personal) object;
        if ((this.documentopersonal == null && other.documentopersonal != null) || (this.documentopersonal != null && !this.documentopersonal.equals(other.documentopersonal))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.simap.modelo.Personal[ documentopersonal=" + documentopersonal + " ]";
    }

}

A: Es un problema bastante frecuenta y molesto. Esto se llama stale data. Por lo general, ocurre cuando no estás operando dentro de una transacción y el EntityManager usa a una versión cacheada de la consulta. Tienes varias opciones.
EntityManager#refresh
Llamando al método refresh de EntityManager refrescas el estado de la entidad, obligando a que se obtenga siempre la última versión del mismo.
em.refresh(objeto);

EntityManagerFactory#getCache#evictAll
Otra opción es llamar al método getCache() del EntityManagerFactory y limpiar la cache mediante evictAll(), antes de obtener registros.
em.getEntityManagerFactory().getCache().evictAll();

Usar una transacción
Esto es lo más recomendado. No comentas si tienes un servidor full profile  o solo un contenedor de servlets como Tomcat o Jetty. Sin embargo, con ambos puedes realizar tus consultas en transacciones.
Jetty o Tomcat
EntityTransaction tx = null;
try {
    tx = em.getTransaction();
    tx.begin(); // empiezas la transacción
    // tu lógica aquí
    tx.commit(); // finalizas la transacción
} catch (PersistenceException e) {
    // si algo sale mal, hacemos rollback para revertir cambios
    if(tx != null && tx.isActive()) {
       tx.rollback();
    }
} finally {
    em.close();
}

WildFly, GlassFish, etc.
En este tipo de servidores no necesitas lo anterior porque ya lo manejan ellos mediante JTA. Por ejemplo, tus servicios pueden ser EJB's que son transaccionales para hacer tu lógica.
@Stateless
@LocalBean
public class UsuarioService implements Serializable {

   @PersistenceContext
   private EntityManager em;

   public List<Usuario> listar() {
       TypedQuery<Usuario> query = em.createNamedQuery(Usuario.FIND_ALL, Usuario.class);
       return query.getResultList();
   }
}

También puedes desactivar el caché de tu proveedor en el persistence.xml:
<shared-cache-mode>NONE</share-cache-mode>

Por el contrario, si lo que tienes es un problema de refrescar datos, fíjate que en el atributo update del commandButton estás poniendo un id válido. Recuerda que si el elemento a actualizar está fuera del formulario, debes de anteponer : al id. Por ejemplo:
<p:commandButton actionListener="#{tuBean.metodo()}" update=":tabla" />

Actualización
No he visto por ningún lado tu commandButton, lo que veo es un listener para selección de filas. En este listener tienes una coma (,) lo que no debería ir en versiones recientes de JSF. Puedes renderizar tantos elementos desees solo separándolos por espacios.

A: Si utilizas un command button puedes asignarle la propiedad update al boton para que refresque la tabla de datos.
Ejemplo.
<p:commandButton actionListener="#{controlador.accion()}"
                                                     update=":dataTableId"
                                                     icon="ui-icon-arrowrefresh-1-s"
                                                     title="Cargar Datos">
                                        <f:param name="parametro1" value="valor1"/>
                                        <f:param name="parametro2" value="valor2"/>
</p:commandButton>

A: Yo lo que hago en estos casos es que cuando hago un cambio del dato, vuelvo a cargar la lista, y al listado resultante lo refresco con un método que agregué en el archivo AbstractFacade (yo trabajo con NetBeans y este lo crea automáticamente cuando se agregan los bean de sesión para las entidades), el código del método es el siguiente:
/**
 * Actualiza el listado cuando se ha hecho un cambio y no se refleja
 * @param entityCollection
 * @return
 */
public List<T> refreshCollection(List<T> entityCollection) {
    List<T> result = new ArrayList<>();
    if (entityCollection != null && !entityCollection.isEmpty()) {
        getEntityManager().getEntityManagerFactory().getCache().evict(entityCollection.get(0).getClass());
        T mergedEntity;
        for (T entity : entityCollection) {
            mergedEntity = getEntityManager().merge(entity);
            getEntityManager().refresh(mergedEntity);
            result.add(mergedEntity);
        }
    }
    return result;
}

Entonces luego que cargo el listado, llamo ese método:
public List<Entidad> cargarDatos() {
    Query q = em.createQuery("SELECT E FROM Entidad E");
    return refreshCollection(q.getResultList());
}

No hay que olvidar hacer un update al datatable para que se reflejen los cambios luego de haber actualizado la lista.
En general de esa forma soluciono ese problema.
Saludos.

A: Pues la solución que encontre ... no se por que , fue cambiar un campo de la tabla en la base de datos (En mi caso un AI ) para que me refrescara los datos en el xhtml aun no se por que, sigo buscando una solución mas practica y eficiente .


text:
Q: Changing how output is printed to the console When I print something directly to the console (type some variable name, such as x, rather than using the print function print(x)), I'd like it to print differently from the way that it normally prints. My idea is that the printing is done by some function. If that's the case, all I have to do is replace that function with a function of my own. However, I cannot figure out what the internal function that does the printing is.
Here is what I've tried so far.
.real_cat = cat
cat = function(x) .real_cat("*** cat ***", x, "\n")

cat(2345)
2345    # no

Printing to console is not done via cat. What about print?
.real_print = print
print = function(x) .real_cat("*** print ***", x, "\n")
print(2345)
2345    # no
"hello" # no
I(2345) # yes

Some classes, like AsIs, are printed to console via print, but others, like numeric or character are not. :-(
c("print.numeric", "print.character", "print.AsIs", "print.default") %in% methods("print")
# FALSE FALSE  TRUE  TRUE

Turns out print doesn't even have a separate method for printing numeric or character. Classes that have a print method are printed to the console using print. But classes that do not have a print method are not. Maybe they are printed using the default method?
print.default = function(x) .real_cat("*** print.default ***", x, "\n")
print.default(2345)
2345    # no
"hello" # no

No.
Maybe if I define a method for numeric, then it will print it using that method?
print.numeric = function(x) .real_cat("*** print.numeric ***", x, "\n")
print.numeric(2345)
2345    # no

print.character = function(x) .real_cat("*** print.character ***", x, "\n")
print.character("hello")
"hello" # no

Here is where I get stuck. I cannot figure out any way to have some basic classes like numeric or character print out directly to console using my own print function.
If this helps, here is the reason that I want to do this. I am writing a package to pretty-print values (https://github.com/prettyprint/prettyprint). Too many times, the output of an analysis is too hard to read, and therefore understand. Yes, you can make it pretty using format, signif, and round, and that's basically what the package already does for you in the background.
I would like to make pretty-printing as easy as possible for the user. At this point, they have to call my pretty-print function (pp(x)). I'd like to play around with giving the user the option to have the result pretty print automatically. (I would print both the non-pretty and the pretty version of the value, to make sure nothing is lost in the prettifying.)

A: See this comment in the source:
 *  print.default()  ->  do_printdefault (with call tree below)
 *
 *  auto-printing   ->  PrintValueEnv
 *                      -> PrintValueRec
 *                      -> call print() for objects
 *  Note that auto-printing does not call print.default.
 *  PrintValue, R_PV are similar to auto-printing.
 *
 *  do_printdefault
 *  -> PrintDefaults
 *  -> CustomPrintValue
 *      -> PrintValueRec
 *          -> __ITSELF__  (recursion)
 *          -> PrintGenericVector   -> PrintValueRec  (recursion)
 *          -> printList            -> PrintValueRec  (recursion)
 *          -> printAttributes      -> PrintValueRec  (recursion)
 *          -> PrintExpression
 *          -> printVector      >>>>> ./printvector.c
 *          -> printNamedVector >>>>> ./printvector.c
 *          -> printMatrix      >>>>> ./printarray.c
 *          -> printArray       >>>>> ./printarray.c

Consequently, auto-printing can only involve method dispatch for explicit classes (with a class attribute, a.k.a. objects). I assume a numeric is handled by printVector. Please check this yourself.
I adds a class AsIs (creating an object) and then print.AsIs is dispatched:
class(I(3))
#[1] "AsIs"


text:
Q: Error during installation of MySQL on Debian 10/arm64 I try to install mysql-server on my Debian 10. Actually i run Debian 10 on Mac Paralells (M1). So parallels doesn't support intel based operating systems. So debian run on arm64.
I downloaded mysql-apt-config_0.8.16-1_all.deb package and i install it with **sudo dpkg -i mysql-apt-config_0.8.16-1_all.deb **. This step ok.
But when i update system with sudo apt update, i get this errors:

N: Skipping acquire of configured file 'mysql-apt-config/binary-arm64/Packages' as repository 'http://repo.mysql.com/apt/debian buster InRelease' doesn't support architecture 'arm64'
N: Skipping acquire of configured file
'mysql-8.0/binary-arm64/Packages' as repository
'http://repo.mysql.com/apt/debian buster InRelease' doesn't support
architecture 'arm64'
N: Skipping acquire of configured file
'mysql-tools/binary-arm64/Packages' as repository
'http://repo.mysql.com/apt/debian buster InRelease' doesn't support
architecture 'arm64'

So i can't install mysql-server. My understanding is that mysql does not support arm64 because my processor is arm64. How can i fix it ?

A: The message you're getting is because you're using an external repository and that repository doesn't ship arm64 packages.  As a result, you won't be able to use it unless the provider (in this case, I assume Oracle) chooses to ship arm64 packages.
However, Debian does ship packages of MariaDB, which is generally compatible with MySQL, and can be used in most cases where one would want to use MySQL.  The package to install, should you want to do that, is default-mysql-server.
You could, of course, also download the source packages from the third-party repository you're using (assuming they're provided) and build them yourself in your VM.  You'd have to rebuild each subsequent version, though, so this will make applying security updates difficult, and I'd recommend a different solution.


text:
Q: Resizing a screenshot to be attached to an email I am currently building this Android application, where I will be taking a screenshot of a "TableLayout" and then emailing it as an attachment. Here is the part of the code which takes the screenshot.
However, when I try to attach the file, using the following code, it says that "File Size Too Large for Attachment". Can anyone suggest any other measures that I can take, apart from Bitmap.Compress, in order to make my file size even smaller? Thanks in advance!
private void getScreen()
            {
                View content = findViewById(R.id.TransactionLog);
                content.setDrawingCacheEnabled(true);

                content.buildDrawingCache(true);

                Bitmap bitmap = Bitmap.createBitmap(content.getDrawingCache());
                content.setDrawingCacheEnabled(false); // clear drawing cache

                File file = new File(Environment.getExternalStorageDirectory() +
                         File.separator + "whatever2.png");

                        try
                            {
                                file.createNewFile();
                                FileOutputStream ostream = new FileOutputStream(file);
                                bitmap.compress(CompressFormat.PNG, 0, ostream);
                                ostream.flush();
                                ostream.close();

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

                }

A: Try using Bitmap.createScaledBitmap:

public static Bitmap createScaledBitmap (Bitmap src, int dstWidth, int
  dstHeight, boolean filter)
  Since: API Level 1
Creates a new bitmap, scaled from an existing bitmap.
  Parameters
src       - The source bitmap.
dstWidth  - The new bitmap's desired width.
dstHeight - The new bitmap's desired height.
filter    - true if the source should be filtered.

FYI, the quality parameter passed to compress does not affect the file size when you are using CompressFormat.PNG.  Try using CompressFormat.JPEG instead, then try different quality values.
Alternatively, try this:
http://thinkandroid.wordpress.com/2009/12/25/resizing-a-bitmap/

A: Have you tried use a higher value for the quality parameter? (currently you're using 0 and it could go up to 100).
I suggest trying 80.
 boolean success = bitmap.compress(CompressFormat.PNG, 80, ostream);

Don't forget to test if it was successful (log the return value of that method).
You can also try to use another format (jpeg?).
To make things simpler, I suggest you to try to save it to the sdcard first and check if the size is something you'd be expecting. You might have some problem on the code that sends the email or it might not let you send large attachments.

A: How big is your image?  An image made from an app, saved as a png, assuming its not a screenshot of a 'picture', should be pretty small.  FAR smaller than what email should be able to accept, unless there's an arbitrarily small attachment size.
If what's in your table is an image, or has quite a bit of variance, you might consider jpeg instead of png.  Otherwise, my guess is something else is going on.


text:
Q: How to send continuous keypress to a program? I have been using SendKeys.Send() & SendKeys.SendWait() to send keys to the foreground program (a program different from the application written).
I tried sending a continuous key-press by sending repeatedly the same key with a certain delay between them but the effect was not the same as a continuous keypress in that application.
My question is: How can I send a continuous key-press to a program? The effect of that keypress must be the same as pressing myself that key continuously in the application.
SOLUTION EDIT
The solution was to call the method:
[DllImport("User32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg, UIntPtr wParam, IntPtr lParam);

with the parameters obtained from:
public System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName("process");
p[0].MainWindowHandle is hWnd
and using Spy on the window:

right clicking on a message line in Spy shows the wMsg, wParam and lParam (all 3 in hexadecimal)
SendMessage(p[0].MainWindowHandle, (uint)0x0100, (UIntPtr)0x00000041, (IntPtr)(0x001E0001));
By sending only one WM_KEYDOWN message the effect is as the key is pressed continuously. To stop the program acting as the key is continuously pressed i have to press that key on the keyboard and release it, so that WM_KEYUP is generated. Sending WM_KEYUP in the code gives an System.OverFlow "Arithmetic operation resulted in an overflow." exception. Any ideea why that might happen?
Thanks for your replies: Ation and takrl

A: Try to use Win API SendMessage with WM_KEYDOWN and WM_KEYUP. Proper delay should be between this messaging. Also you could use PostMessage for async sending.
[DllImport("User32.dll")]
            public static extern int SendMessage(IntPtr hWnd, uint msg, int wparam, int lparam);

A: If I get this right, you want to imitate the effect of pressing a key within an application, and then keep it pressed until the OS starts repeating the keystrokes? If that's it, an API approach like @Ation suggested is the way to go.
You should, however, analyze what the application receives, by using a tool like Spy++ or similar. For an OS-repeated keystroke, I believe there's no WM_KEYUP until the key is actually being released. And I don't think you can replicate this behavior by either using SendKeys.Send or SendKEys.SendWait.
EDIT
Here's an excerpt of a Spy++ log, taken of a TextBox control when the letter A is pressed:
<00168> 00010590 P WM_KEYDOWN nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<00173> 00010590 P WM_CHAR chCharCode:'97' (97) cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<00182> 00010590 P WM_KEYDOWN nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00187> 00010590 P WM_CHAR chCharCode:'97' (97) cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00196> 00010590 P WM_KEYDOWN nVirtKey:'A' cRepeat:3 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00201> 00010590 P WM_CHAR chCharCode:'97' (97) cRepeat:3 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00210> 00010590 P WM_KEYDOWN nVirtKey:'A' cRepeat:4 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00215> 00010590 P WM_CHAR chCharCode:'97' (97) cRepeat:4 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00224> 00010590 P WM_KEYDOWN nVirtKey:'A' cRepeat:3 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00229> 00010590 P WM_CHAR chCharCode:'97' (97) cRepeat:3 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00238> 00010590 P WM_KEYDOWN nVirtKey:'A' cRepeat:4 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00243> 00010590 P WM_CHAR chCharCode:'97' (97) cRepeat:4 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00252> 00010590 P WM_KEYDOWN nVirtKey:'A' cRepeat:3 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00257> 00010590 P WM_CHAR chCharCode:'97' (97) cRepeat:3 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00266> 00010590 P WM_KEYDOWN nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00271> 00010590 P WM_CHAR chCharCode:'97' (97) cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:0
<00280> 00010590 P WM_KEYUP nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:1

As you can see, there's several WM_KEYDOWN followed by WM_CHAR (this may be only relevant to the TextBox I used for this, I'm not sure about that), and a WM_KEYUP at the very end of it. The log had several other messages that didn't seem to be related to pressing the key (they're continuously numbered), but this may vary depending on your app or control you're going to use this for.
Notice the fRepeat:1 on the WM_KEYUP and all previous WM_KEYDOWN except the first one, that seems to denote it's an automatic repetition.


text:
Q: How to change column check constraint in table I have a column Column1 integer check(column1 >=0) not null unique;. Now i want to change the column so that the column1 has check value of <=0. I have already tried: alter table table1 alter column column1 type integer check(column1 <=0) not null unique; But it doesn't work. Any solutions?

A: So as you said what is your database this is the command you need:
alter table table1 add constraint CK_NEGATIVEVALUES check ( column1 <=0 )

You don't alter a column to add a check you alter a table to add a CONSTRAINT CHECK


text:
Q: Does $\mathbb{E}[X^6] < \infty$ imply $\mathbb{E}[X^4] < \infty$?
Let $X$ be a random variable.
  Does $\mathbb{E}[X^6] < \infty$ imply $\mathbb{E}[X^4] < \infty$?

My tries

*

*I know this isn't rigorous but I thought that when there was a counterexample, the rv in question would have density so I could write
$$
\mathbb{E}[X^k]
= \int_{\mathbb{R}} x^k f(x) \ \text{d} x,
$$
where $f$ is the PDF of $X$.
I thought that if I had a rv with density $f(x) := x^{-4}$ this would yield $\mathbb{E}[X^4] = 1$ and $\mathbb{E}[X^6] = \infty$ but as $\int_{\mathbb{R}} x^{-4} \ \text{d} x = \infty$, $f$ isn't a PDF, so I don't know where to continue from there.

*Jensens inequality gives $\mathbb{E}[X^k] \ge \mathbb{E}[X]^k$ from $k \in \mathbb{N}$ but if $\mathbb{E}[X] \in (0,1)$ we have $\mathbb{E}[X]^6 < \mathbb{E}[X]^4$ and for $\mathbb{E}[X] > 1$ we have $\mathbb{E}[X]^6 > \mathbb{E}[X]^4$, so I don't know where to continue from there.

*I wanted to use that $L^q(\Omega) \subset L^p(\Omega)$ for $p \le q$ if $\Omega$ is a finite measure space but I have no reason to believe I can restrict myself to that special case.

A: Your point $3.$ definitely applies: $\mathbb{E}[X^6]< \infty$ is the same as $X \in L^6(\Omega)$, and hence $X \in L^4(\Omega)$ by point $3.$, which is to say that $\mathbb{E}[X^4]<\infty$.
However, as previously mentioned in the comments, it suffices to see that $X^4 \leq X^6+1$. The inequality can be seen to follow from the fact that for $-1 \leq x \leq 1$, it is true that $x^4 \leq 1$, and for $\left| x \right| \geq 1$, $x^4 \leq x^6$. Hence, $x^4 \leq \max\{x^6,1\}\leq x^6+1$.
Since $X^6$ is integrable by assumption and $1$ due to the fact the measure space is finite, we have that $X^6+1$ is integrable and therefore $X^4$ is.

A: Jensen's inequality in fact gives $E[Y^k] \ge E[Y]^k$ for any nonnegative random variable $Y$ and any $k \ge 1$ ($k$ does not have to be an integer).  Now apply this with $Y = X^4$ and $k=6/4$.

A: This is an elementary but important consequence of Holder inequality.
I state and prove the following result.
Proposition: Let $(X,\mathcal{M},\mu)$ be a measure space with $\mu(X)<\infty$.
Let $0<a<b<\infty$. For any measurable function $f:X\rightarrow\mathbb{R}$,
we have that $\int|f|^{b}d\mu<\infty\Rightarrow\int|f|^{a}d\mu<\infty$.
Proof: Let $p=\frac{b}{a}\in(1,\infty)$ and let $q\in(1,\infty)$
such that $\frac{1}{p}+\frac{1}{q}=1$. Let $\xi=|f|^{a}$ and $\eta=1$.
By Holder inequality, we have
$$
\int|\xi\eta|\,d\mu\leq||\xi||_{p}||\eta||_{q}.
$$
Observe that $\int|\xi\eta|\,d\mu =\int|f|^{a}\,d\mu$, $||\xi||_{p}=\sqrt[p]{\int|\xi|^{p}\,d\mu}=\sqrt[p]{\int|f|^{b}\,d\mu}$,
and $||\eta||_{q}=\sqrt[q]{\mu(X)}$. Therefore
\begin{eqnarray*}
\int|f|^{a}\,d\mu & \leq & \sqrt[p]{\int|f|^{b}\,d\mu}\cdot\sqrt[q]{\mu(X)}<\infty
\end{eqnarray*}
 whenever $\int|f|^{b}\,d\mu<\infty$.


text:
Q: Для чего нужно использовать объект класса BooleanVar вместо обычной переменной типа bool? Например , я написал очень простую программу на Tkinter . Есть 3 флажка , активируя которые , можно изменять текстовую область . Она отображает , какие флажки нажаты :
from tkinter import *

class Application(Frame) :
    """Простое приложение"""
    def __init__(self,master) :
        super().__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self) :
        """Создаёт элементы управления"""
        self.is_first_checkbox = None # вопрос в этой строчке
        Checkbutton(self,
                    text = "Флажок 1",
                    variable = self.is_first_checkbox,
                    command = self.update_text
                    ).grid(row = 2, column = 0, sticky = W)

        self.is_second_checkbox = None # вопрос в этой строчке
        Checkbutton(self,
                    text = "Флажок 2",
                    variable = self.is_second_checkbox,
                    command = self.update_text
                    ).grid(row = 3, column = 0, sticky = W)

        self.is_third_checkbox = None # вопрос в этой строчке
        Checkbutton(self,
                    text = "Флажок 3",
                    variable = self.is_third_checkbox,
                    command = self.update_text
                    ).grid(row = 4, column = 0, sticky = W)

        self.results_txt = Text(self,width = 40, height = 5, wrap = WORD)
        self.results_txt.grid(row = 5, column = 0, columnspan = 3)

    def update_text(self) :
        """Обновляет текстовый элемент"""
        result = ""
        if self.is_first_checkbox :
            result += "Первый флажок активирован.\n"
        if self.is_second_checkbox :
            result += "Второй флажок активирован.\n"
        if self.is_third_checkbox :
            result += "Третий флажок активирован.\n"

        self.results_txt.delete(0.0,END)
        self.results_txt.insert(0.0,result)

window = Tk()
window.title("Флажки")
app = Application(window)
window.mainloop()

Результат - флажки активируются , но никаких изменений в текстовой области не происходит . Теперь я переписываю эту программу , заменяя обычные переменные на объекты класса tkinter.BooleanVar :
from tkinter import *

class Application(Frame) :
    """Простое приложение"""
    def __init__(self,master) :
        super().__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self) :
        """Создаёт элементы управления"""
        self.is_first_checkbox = BooleanVar() # вопрос в этой строчке
        Checkbutton(self,
                    text = "Флажок 1",
                    variable = self.is_first_checkbox,
                    command = self.update_text
                    ).grid(row = 2, column = 0, sticky = W)

        self.is_second_checkbox = BooleanVar() # вопрос в этой строчке
        Checkbutton(self,
                    text = "Флажок 2",
                    variable = self.is_second_checkbox,
                    command = self.update_text
                    ).grid(row = 3, column = 0, sticky = W)

        self.is_third_checkbox = BooleanVar() # вопрос в этой строчке
        Checkbutton(self,
                    text = "Флажок 3",
                    variable = self.is_third_checkbox,
                    command = self.update_text
                    ).grid(row = 4, column = 0, sticky = W)

        self.results_txt = Text(self,width = 40, height = 5, wrap = WORD)
        self.results_txt.grid(row = 5, column = 0, columnspan = 3)

    def update_text(self) :
        """Обновляет текстовый элемент"""
        result = ""
        if self.is_first_checkbox.get() :
            result += "Первый флажок активирован.\n"
        if self.is_second_checkbox.get() :
            result += "Второй флажок активирован.\n"
        if self.is_third_checkbox.get() :
            result += "Третий флажок активирован.\n"

        self.results_txt.delete(0.0,END)
        self.results_txt.insert(0.0,result)

window = Tk()
window.title("Флажки")
app = Application(window)
window.mainloop()

Теперь всё работает корректно . Мой вопрос состоит в следующем : какой смысл в использовании этих объектов вместо обычных переменных , чем они отличаются от переменных , слылающихся на простые логические значения ? Почему переменные в этом случае не работают и не принимают значение автоматически ? И тогда , в каких вообще случаях нужны использовать объекты класса BooleanVar .

A: tkinter.BooleanVar -- это объект Tk и он умеет хранить и отдавать значение, а, например, в self.is_first_checkbox у вас был бы False или True и немного другое -- они не изменяемые, у них нет какого-либо метода для изменения их состояния (типа метода set).
Т.е. виджет Checkbutton умеет менять значение объекта переданного в variable, но для этого нужны изменяемые объекты с определенными атрибутами (set и get).
А чтобы проверка с if self.is_first_checkbox : имела смысл, виджету нужно менять значение самого атрибута объекта, т.е. что-то вроде setattr(self, 'is_first_checkbox', True), а такое он не сможет сделать.

Немного подробнее про объект BooleanVar из tk:
class BooleanVar(Variable):
    """Value holder for boolean variables."""
    _default = False
    def __init__(self, master=None, value=None, name=None):
        """Construct a boolean variable.

        MASTER can be given as master widget.
        VALUE is an optional value (defaults to False)
        NAME is an optional Tcl name (defaults to PY_VARnum).

        If NAME matches an existing variable and VALUE is omitted
        then the existing value is retained.
        """
        Variable.__init__(self, master, value, name)

    def set(self, value):
        """Set the variable to VALUE."""
        return self._tk.globalsetvar(self._name, self._tk.getboolean(value))
    initialize = set

    def get(self):
        """Return the value of the variable as a bool."""
        try:
            return self._tk.getboolean(self._tk.globalgetvar(self._name))
        except TclError:
            raise ValueError("invalid literal for getboolean()")

Как видно, у самого объекта есть методы для установки и получения значения через методы set и get. А "подкапотом" этих методов происходит работа с tk, что наталкивает на вывод, что простые типы python не могут заменить объекты tk для работы с tk :)


text:
Q: C#: how can i stop the execution of for loop from outside of the loop? i have class that reads data from a large file (1GB) using a fixed buffersize and writes it in an array. i want to let the user cancels the process whenever they want to. how can i stop the loop from outside of the loop.( i think using events would be a good idea but dont know how to do it)
note: i have a form that will send the cancellation request.
for (int i = 0; i < fileContent.Length; i++)
                    {
                        try
                        {
                            fileContent[i] = br.ReadInt16();
                        }
                        catch (EndOfStreamException)
                        {
                            loadflag = 1;
                            contentSize = i;
                            break;
                        }
                    }
                    for (int k = 0; k < contentSize; k += ReSampleRate)
                    {
                        try
                        {
                            convertedData[(count * fileContent.Length / ReSampleRate) + j] = fileContent[k];
                            j++;
                        }
                        catch (IndexOutOfRangeException)
                        {
                            MessageBox.Show("could not load the file completely");
                            goto lable;
                        }
                        catch
                        {
                            MessageBox.Show("something went wrong");
                        }
                    }

                    if (loadflag == 1)
                    {
                        break;
                    }

                }

A: Make your method take a CancellationToken. Change your loop so it calls cancellationToken.ThrowIfCancellationRequested() each iteration. Ensure your caller catches the resulting OperationCancelledException. The form should create a CancellationTokenSource with a Token property that can be given to your method, and a cancel method that can be called by your form.
Note that your method need to be run on a background thread for all of this to work, typically using Task.Run, but this will require you to move your messageboxes, and any other code that updates the UI, outside the method to be cancelled. A possible exception to this might be if you have an async method that mostly awaits IO to complete.
Example:
private CancellationTokenSource cts = new CancellationTokenSource();;
public async void OnButtonPress(){
    try{
        cts = new CancellationTokenSource();
        await Task.Run(() => OnBackgroundThread(cts.Token));
        void OnBackgroundThread(CancellationToken cancel){
            foreach(var item in MyItemsToProcess){
                cancel.ThrowIfCancellationRequested();
                // Process item
            }
        }
       catch(OperationCancelledException){
           // do nothing
       }
       // Handle other errors
    }
}
public void OnCancelPress(){
    cts.Cancel();
}

Another variant is to check the cancellationToken.IsCancellationRequested property and return normally. But this makes it impossible for the caller to determine if the loop completed or not, at best it can check if the token was cancelled.
If you are looking for some way to cancel the loop without any changes to it you are out of luck. There are no good way to abort a running thread non-cooperativly.


text:
Q: Accuracy of solutions of differential equations with DeepXDE We used DeepXDE for solving differential equations. (DeepXDE is a framework for solving differential equations, based on TensorFlow). It works fine, but the accuracy of the solution is limited, and optimizing the meta-parameters did not help. Is this limitation a well-known problem? How the accuracy of solutions can be increased? We used the Adam-optimizer; are there optimizers that are more suitable for numerical problems, if high precision is needed?
(I think the problem is not specific for some concrete equation, but if needed I add an example.)

A: There are actually some methods that could increase the accuracy of the model:

*

*Random Resampling

*Residual Adaptive Refinement (RAR): https://arxiv.org/pdf/1907.04502.pdf
They even have an implemented example in their github repository:
https://github.com/lululxvi/deepxde/blob/master/examples/Burgers_RAR.py
Also, You could try using a different architecture such as Multi-Scale Fourier NNs. They seem to outperform PINNs, in cases where the solution contains lots of "spikes".


text:
Q: One oblique line separated in two (with gap in the middle) I am trying to make two centered oblique lines but to seem like one continues the other one. The thing is, this two lines should also stay in place no matter the screen size. I had some attempts but got nowhere. Other ideas are also welcome and as you can see I have used two spans for the oblique lines . Below is my code.

body{
    margin: 0;
    padding: 0;
}

#dLi{
    height: 100vh;
    width:33.33%;
    float:left;
    background-color: red;
}

#spansDiv{
    height: 100vh;
    width:33.33%;
    display: flex;
    flex-direction: column;
    align-items: center;

    background-color: pink;
    float:left;
}

#sI{
    height: 50vh;
    width: 0.3%;
    background-color: blue;
    transform: rotate(45deg);
    /*position: absolute;*/
}

#sI2{
    height: 50vh;
    width: 0.3%;
    background-color: blue;
    transform: rotate(15deg);
    margin-top:auto;
    /*position: absolute;*/
}

#dRi{
    height: 100vh;
    width:33.33%;
    float: left;
    background-color: green;
}
```
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css/style.css">
    <title>Test oblique</title>


text:
Q: Stripping special characters in R I have the following string
> str
[1]  "[ { \"category\" : \"book\"} , { \"category\" : \"Movie\"} , { \"category\" : \"Brand\"}]"

I want to strip it to get the following vector
> a
[1] "book" "Movie" "Brand"

My problem is how to handle the "" and \ within the string to pass it to either grep or gsub in R. This is what I did and I get an error
> grep("^\[ \{ \\"category\\" : \\"([a-zA-Z0-9/]+)\\".*",str)
Error: '\[' is an unrecognized escape in character string starting "^\["

Am I even on the right track?

A: Maybe the rjson package will sort you out:
> require(rjson)
> unlist(fromJSON(str))
  category category category
    "book"  "Movie"  "Brand"

ignoring the names ("category") that's what you want. Wrap in as.vector() to get rid of those.


text:
Q: Can build.sbt in Play 2.2+ project dependsOn a GitHub project SBT? Is it possible to write a build.sbt for Play 2.2+ that dependsOn a GitHub project? The dependency is a library, not a Play module, and it is a private BitBucket repo so it needs authentication. The resulting project is pushed up to Heroku for deployment.
How can sbt pull dependency artifacts from git? doesn't show the build.sbt syntax and doesn't address the authentication issue.

A: It's quite legitimate and the answer is as simple as the following in build.sbt:
lazy val bananaRdfProject =
  ProjectRef(uri("https://github.com/w3c/banana-rdf.git"), "banana-rdf")

and then dependsOn the lazy val, or
lazy val core = project dependsOn(
  ProjectRef(uri("git://github.com/w3c/banana-rdf.git"), "banana-jena")
)

See Can multi-projects from GIT be used as SBT dependencies? and SBT dependsOn RootProject: doesn't compile the dependency.


text:
Q: Why is Bragg's Law always presented as $n\lambda=2d\sin \theta$? In the vast majority of texts and handbooks on Bragg diffraction, Bragg's formula is presented as:
$$n\lambda=2d\sin \theta\tag{1}$$
where $\theta$ is the incident angle.
But constructive interference occurs when:
$$n\lambda=\text{path difference between incident and reflected ray}$$
So, for example:

then:
$$n\lambda=d\left(\sin\alpha + \sin\beta\right)\tag{2}$$
A long time ago I used that formula to determine the $d$-value of an R-DVD using a pen-type known wavelength red laser. Using $(1)$ I would only have 'seen' part of the constructive interferences (for $\alpha = \beta$).
So why is only $(1)$ taught?


text:
Q: Connecting to mysql from 127.0.0.1 instead of from localhost I have similar problem as
here. The problem is that solution proposed there does not work for me:
Just for now I have users:
+----------+------------------------------------+
| user     | host                               |
+----------+------------------------------------+
| root     | 127.0.0.1                          |
| root     | localhost                          |

both without passwords (just for now. I know it is bad!).
I'm connecting to mysql using this command:
mysql -u root -h 127.0.0.1 --protocol=tcp

After I logged in, I get:
mysql -u root -h 127.0.0.1 --protocol=tcp
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.1.61-log Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> \s
--------------
mysql  Ver 14.14 Distrib 5.1.61, for redhat-linux-gnu (x86_64) using readline 5.1

Connection id:      5
Current database:
Current user:       root@localhost
SSL:            Not in use
Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.1.61-log Source distribution
Protocol version:   10
Connection:     127.0.0.1 via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    latin1
Conn.  characterset:    latin1
TCP port:       3306
Uptime:         2 days 9 hours 2 min 13 sec

Threads: 1  Questions: 102  Slow queries: 0  Opens: 19  Flush tables: 1  Open tables: 12  Queries per second avg: 0.0
--------------

mysql> SELECT USER(),CURRENT_USER();
+----------------+----------------+
| USER()         | CURRENT_USER() |
+----------------+----------------+
| root@localhost | root@localhost |
+----------------+----------------+
1 row in set (0.00 sec)

mysql>

QUESTION:
How to login as 'root'@127.0.0.1?

A: Good evening, it's @RolandoMySQLDBA, the author of that post you mentioned.
Look at the last three lines
Server version:     5.1.61-log Source distribution
Protocol version:   10
Connection:     127.0.0.1 via TCP/IP

The last line says 127.0.0.1 via TCP/IP so you are 100% using the TCP/IP protocol.
Did you run SELECT USER(),CURRENT_USER(); ?
If you did, it should say
root@127.0.0.1 | root@127.0.0.1

It would seem weird for the output to be
root@127.0.0.1 | root@localhost

Please notice the following: Since both root users have identical grants and identical passwords (none in this case), mysqld decided to pick root@localhost. At this point, you are probably wondering, "Why would mysqld make such a choice ?"
In the DBA StackExchange, I have this 2-year-old post (MySQL error: Access denied for user 'a'@'localhost' (using password: YES)). In that past, I describe exactly how mysqld peforms user authentication. Note the paragraphs from pages 486,487 of MySQL 5.0 Certification Study Guide

There are two stages of client access control:
In the first stage, a client attempts to connect and the server either
  accepts or rejects the connection. For the attempt to succeed, some
  entry in the user table must match the host from which the clent
  connects, the username, and the password.
In the second stage (which occurs only if a client has already
  connected sucessfully), the server checks every query it receives from
  the client to see whether the client has sufficient privileges to
  execute it.
The server matches a client against entries in the grant tables based
  on the host from which the client connects and the user the client
  provides. However, it's possible for more than one record to match:

As I mentioned from the Certification Book, it's possible for more than one record to match. Therefore, mysqld made the choice.
If you delete root@localhost from mysql.user, that's one way to get SELECT USER(),CURRENT_USER(); to match. Another way is to give root@127.0.0.1 a password.
SUMMARY
Having 2 root users with identical means of being used for user authentication is the root cause as to why you cannot see root@127.0.0.1. Notwithstanding, you are using TCP/IP.
SIDE NOTE
Please make sure 127.0.0.1 is defined in the OS. Run this:
cat /etc/hosts | grep -c "127\.0\.0\.1"

If you get 0, then the OS does not know about it. You would need to add 127.0.0.1 to /etc/hosts and restart the network and then mysql.
UPDATE 2014-04-26 20:00 EDT
What I am about to say may sound silly, but the Documentation uses TCP instead of tcp

On Unix, MySQL programs treat the host name localhost specially, in a
  way that is likely different from what you expect compared to other
  network-based programs. For connections to localhost, MySQL programs
  attempt to connect to the local server by using a Unix socket file.
  This occurs even if a --port or -P option is given to specify a port
  number. To ensure that the client makes a TCP/IP connection to the
  local server, use --host or -h to specify a host name value of
  127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by
  using the --protocol=TCP option. For example:
shell> mysql --host=127.0.0.1
shell> mysql --protocol=TCP

The --protocol option enables you to establish a particular type of connection even when the other options would normally default to
  some other protocol.

Try using protocol=TCP like this
mysql -u root -h 127.0.0.1 --protocol=TCP -ANe"SELECT USER(),CURRENT_USER()"
mysql -u root -h localhost --protocol=TCP -ANe"SELECT USER(),CURRENT_USER()"

to see if it makes a  difference.
UPDATE 2014-05-09 16:19
You need to look over the /etc/hosts carefully
If you see this in /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

then logging in as root@127.0.0.1 should work properly
If you see this in /etc/hosts
127.0.0.1       localhost

then root@127.0.0.1 stands no chance of working

A: PHP is still trying to use the default socket location. This problem can appear if you have moved the MariaDB/MySQL folder from /var/lib/mysql to another location. In order to solve the problem you have to define the new socket's location in the /etc/php.ini file.
mysqli.default_socket =/newDBLocation/mysql/mysql.sock

Watch out, depending on which driver you use, you may have to specify the pdo_mysql.default_socket=!
In order to check your current directory run the following command in mysql:
select @@datadir;


text:
Q: Nested Dataobjects in Silverstripe 3.1? Is it possible to create nested Dataobjects in Silverstripe?
I tried it with an $has_many relation but the second dataobject wasn't shown in the first.
is this possible? how?

A: a hierachy of nested DataObjects was always possible in SilverStripe.
It was just the interface that was not exisiting or pretty bad in any version prior to 3.0
as of 3.0 you can nest GridFields as much as you want, not only once, you can nest it n times.
nesting dataobjects is nothing special, it is just the same as a relation from a page to a dataobject.
the relation can be has_many with a has_one on the other side, or a many_many with a belogs_many_many on the other side.
here an example with has_many:
class TournamentPage extends Page {
    private static $has_many = array('Teams' => 'Team');
    public function getCMSFields() {
        $fields = parent::getCMSFields();
        $fields->addFieldToTab('Root', Tab::create('TeamsTab', 'List of Teams'));
        $fields->addFieldToTab('Root.TeamsTab', GridField::create('Teams', 'The Teams', $this->Teams(), GridFieldConfig_RecordEditor::create());
        return $fields;
    }
}

class TournamentPage_Controller extends Page_Controller {}

class Team extends DataObject {
    private static $db = array('Title' => 'Varchar');
    private static $has_one = array('TournamentPage' => 'TournamentPage'); // to make has_many of TournamentPage work
    private static $has_many = array('Players' => 'Player');
    public function getCMSFields() {
        $fields = FieldList::create();
        $fields->push(TextField::create('Title', 'Team name');
        $fields->push(GridField::create('Players', 'The Players', $this->Players(), GridFieldConfig_RecordEditor::create());
        return $fields;
    }
}

class Player extends DataObject {
    private static $db = array('Title' => 'Varchar');
    private static $has_one = array('Team' => 'Team'); // to make has_many of Team work
    private static $has_many = array('DopingProblems' => 'DopingProblem');
    public function getCMSFields() {
        $fields = FieldList::create();
        $fields->push(TextField::create('Title', 'Player name');
        return $fields;
    }
}

and the template for that:
// file: TournamentPage.ss
<% loop $Teams %>
    Team: $Title

    Number of Players in this Team: $Players.Count

        <% loop $Players %>

Player name: $Title

        <% end_loop %>

<% end_loop %>


text:
Q: Javascript - recommended way to create an object It looks like there a number of ways to create object in Javascript per below:
var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};

function person(){
    this.firstName = 'first';
    this.lastName = 'last';
    this.age = 'age';
    this.eyeColor = 'eyecolor';
}

person = (function () {
    this.firstName = 'first';
        this.lastName = 'last';
        this.age = 'age';
        this.eyeColor = 'eyecolor';
}();

Could someone please help me understand which one of above is the best practice to use?
And also on what scenarios do we use self-invoking function?

A: If you want to get the most bang for your buck, you can use a function, which allows you to set "public" and "private" variables. For example:
function Person (name, age) {
    var number = (Math.random() * 100) | 0;
    // number is private; there's no way to access it outside
    // of the scope of this function
    var surpriseParty = new Date(Date.now() + number*24*3600*1000);
    // we're throwing you a party within the next 100 days
    this.name = name;    // public
    this.age = age;      // public
    return {
        getName: function () { return name },
        getAge: function () { return name },
        getPartyDate: function () { return surpriseParty }
    }
}

As commented in the code above, now only certain variables can be accessed:
var p = new Person("royhowie", 18);
// p.getName() => "royhowie"
// p.name => "royhowie"
// p.getAge() => 18
// p.age => 18
// p.number => undefined
// p.surpriseParty => undefined
// p.getPartyDate() => date within the next 100 days

In truth, though, you should use whatever fits the bill best. The above method is an easy way to encapsulate data, but if you want everything to be public, use the normal object syntax:
var p = { name: "royhowie", age: 18, surpriseParty: new Date() };

I wouldn't recommend the self-executing anonymous function syntax. You should declare the function elsewhere (at least for debugging); this at least gives you the option of creating two different instances of that object.

A: This question is already answered here which correctly states that there is no recommended way of creating a JavaScript Object. It completely depends upon your use case.
According to W3schools there is a standard way of creating objects:
The standard way to create an "object type" is to use an object constructor function. Here is an example:
function person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");

Hope this helps! :)


text:
Q: Notion of group generators I'm asking myself what the meaning of a statement like the following is:

Let $G$ be a group and $T_i \subseteq G$ be a family of subgroups of $G$ indexed by a possibly infinite set $I$. Now let $H$ be another group generated by $T_i, i\in I$.

As I understand the above is, that there is a surjective group homorphism
$$\prod_{i \in I} T_i \twoheadrightarrow H,$$
because every element in $H$ comes from some product of elements in $T_i$.
But consider the following case where $H'$ is another group:
Let $\varphi$ be an injective group homomorphism
$$\varphi: H' \hookrightarrow \prod_{i\in I} T_i$$
My first question now is:

Is it correct to say that $H'$ is generated by the $T_i$?

Secondly, is in which case can we talk about $\prod_{i \in I} T_i$ being the free product over $I$?
Thank you, Tom

A: As @H.B. said, $H$ is the smallest subgroup of $G$ that contains each of the $T_i$. There is not necessarily a surjective homomorphism $\phi: \prod T_i \to H$.  If you replace $\prod T_i$ with $\oplus T_i$, and you add the assumption that $t_i t_j =  t_j t_i$ for all $t_i \in T_i, t_j \in T_j, i \ne j$, then there is a canonical surjective homomorphism $\phi$ (if $|I| = 2$, this is given by $(t_1, t_2) \mapsto t_1 t_2)$.  However, without this commutativity condition, $\phi$ will definitely not be a homomorphism, and might not be surjective as a set map.
As examples, consider $G = S_3$.  In one example, $T_1$ is generated by $(1 2)$, and $T_2$ is generated by $(1 2 3)$.  In the second example, $T_1$ is generated by $(1 2)$ and $T_2$ is generated by $(1 3)$.  In both cases, $H = G$.  In the first example, $\phi$ is surjective but not a homomorphism.  In the second example, $\phi$ isn't even surjective, and it had no hope of being surjective since $ 6 = |H| > |T_1 \times T_2| = 4$.


text:
Q: Error: CRITICAL App Unable to get a Window, abort I use recently started using PyCharm and kivy.
I download all the Kivy dependencies from the instillation instructions
I use Windows 10 , Python v.3.5.1 and Kivy 1.11.1
Here is the code
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout

class MainApp(App):

    def build(self):
        return FloatLayout()

if __name__ == '__main__':
    app = MainApp()
    app.run()

Here is the error
[INFO   ] [Logger      ] Record log in C:\Users\mahdy\.kivy\logs\kivy_20-08-27_52.txt
[INFO   ] [Kivy        ] v1.11.1
[INFO   ] [Kivy        ] Installed at "C:\Users\mahdy\PycharmProjects\Whatsurnameman\venv\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
[INFO   ] [Python      ] Interpreter at "C:\Users\mahdy\PycharmProjects\Whatsurnameman\venv\Scripts\python.exe"
[INFO   ] [Factory     ] 184 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_gif (img_sdl2, img_pil, img_ffpyplayer ignored)
[CRITICAL] [Window      ] Unable to find any valuable Window provider. Please enable debug logging (e.g. add -d if running from the command line, or change the log level in the config) and re-run your app to identify potential causes
sdl2 - ImportError: DLL load failed: The specified module could not be found.
  File "C:\Users\<username>\PycharmProjects\<project name>\venv\lib\site-packages\kivy\core\__init__.py", line 63, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\<username>\PycharmProjects\<project name>\venv\lib\site-packages\kivy\core\window\window_sdl2.py", line 27, in <module>
    from kivy.core.window._window_sdl2 import _WindowSDL2Storage

[CRITICAL] [App         ] Unable to get a Window, abort.


text: Q: Support library 26 - DialogFragment, CursorAdaptor missing When I updated Android support library 26, it can't find classes like DialogFragment, CursorAdaptor etc. any more. Does that mean that I should use android.widget.CursorAdapter and android.app.DialogFragment instead?


text:
Q: Trying to nest a custom object proxy in a dict proxy As per the documentation provided by Python here, having a nested proxy object in another is fine; I already use this quite a bit. The problem however lies when I try to create my own object proxy, mainly because it has to exist and update itself.
For context, I'm on Python 3.6.9.
Here is an example I made to explain the problem I am having:
from multiprocessing.managers import SyncManager
from multiprocessing import Manager

class Foo:
    def __init__(self, num) -> None:
        self.num = num

    def inc(self) -> None:
        self.num += 1

    def __str__(self) -> str:
        return f"Current num: {self.num}"

SyncManager.register('Foo', Foo)

with Manager() as manager:
    # Create new managed dict
    test_dict = manager.dict()

    # Create new normal object in managed dict
    test_dict['t1'] = Foo(1)
    print(test_dict['t1'])

    # Try to update object in managed dict
    test_dict['t1'].inc()
    print(test_dict['t1']) # Not updated since it is not managed

    # Managed object NOT in managed dict
    test_obj = manager.Foo(10)
    print(test_obj._getvalue()) # Get actual object

    # Increment managed object
    test_obj.inc()
    print(test_obj._getvalue()) # Get actual object

    # Managed object IN managed dict
    test_dict['t2'] = manager.Foo(100) # Error
    print(test_dict['t2'])

The output of the above is as follows:
Current num: 1
Current num: 1
Current num: 10
Current num: 11
Traceback (most recent call last):
  File ".../test.py", line 37, in <module>
    test_dict['t2'] = manager.Foo(100) # Error
  File "<string>", line 2, in __setitem__
  File "/usr/lib/python3.6/multiprocessing/managers.py", line 772, in _callmethod
    raise convert_to_error(kind, result)
multiprocessing.managers.RemoteError:
---------------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3.6/multiprocessing/managers.py", line 228, in serve_client
    request = recv()
  File "/usr/lib/python3.6/multiprocessing/connection.py", line 251, in recv
    return _ForkingPickler.loads(buf.getbuffer())
  File "/usr/lib/python3.6/multiprocessing/managers.py", line 881, in RebuildProxy
    return func(token, serializer, incref=incref, **kwds)
TypeError: AutoProxy() got an unexpected keyword argument 'manager_owned'
---------------------------------------------------------------------------

From here, I can use the managed dict with no issues. I can create the managed object without issues either. Trying to put the latter in the former though causes the problem.
Now the error I got here was specifically due to AutoProxy() being given an extra argument, which is a known issue. I decided to make my own quick proxy to get past it.
So I updated the following lines:
from multiprocessing.managers import SyncManager

SyncManager.register('Foo', Foo)

to:
from multiprocessing.managers import SyncManager, MakeProxyType, public_methods

SyncManager.register('Foo', Foo, MakeProxyType('Foo', public_methods(Foo)))

The output is now:
Current num: 1
Current num: 1
Current num: 10
Current num: 11
Traceback (most recent call last):
  File ".../test.py", line 37, in <module>
    test_dict['t2'] = manager.Foo(100) # Error
  File "<string>", line 2, in __setitem__
  File "/usr/lib/python3.6/multiprocessing/managers.py", line 756, in _callmethod
    conn.send((self._id, methodname, args, kwds))
  File "/usr/lib/python3.6/multiprocessing/connection.py", line 206, in send
    self._send_bytes(_ForkingPickler.dumps(obj))
  File "/usr/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
    cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <class 'multiprocessing.managers.Foo'>: attribute lookup Foo on multiprocessing.managers failed

It's failing at trying to pickle... I'm not sure; it should be the proxy, and not the object, right? I tried to pickle manager.Foo(1), and got the same error; which was to be expected.
I'm stumped. I need to have the objects that are in a manager.dict() to be updated, and I can't simply replace the object with a new one with new parameters.
I can't use any newer version of Python, and I can't figure this out. Any help here would be appreciated.


text:
Q: R- key in data in data.frame when don't know row number If there is a data.frame names 'DF',how can I enter 'yellow' when I don't know the row number,thanks.
from
     fruit  year  color
?    apple  2017  red
?    apple  2018  red
?    apple  2019  red
?    banana 2017
?    banana 2018
?    banana 2019
?    orange 2017  orange
?    orange 2018  orange
?    orange 2019  orange

to
     fruit  year  color
?    apple  2017  red
?    apple  2018  red
?    apple  2019  red
?    banana 2017  yellow
?    banana 2018  yellow
?    banana 2019  yellow
?    orange 2017  orange
?    orange 2018  orange
?    orange 2019  orange

A: One way would be to create a look-up dataframe and then match based on fruit
color_fruit <- data.frame(fruit = c('apple', 'banana', 'orange'),
              color = c('red', 'yellow', 'orange'), stringsAsFactors = FALSE)

df$color <- color_fruit$color[match(df$fruit, color_fruit$fruit)]
df

#   fruit year  color
#1  apple 2017    red
#2  apple 2018    red
#3  apple 2019    red
#4 banana 2017 yellow
#5 banana 2018 yellow
#6 banana 2019 yellow
#7 orange 2017 orange
#8 orange 2018 orange
#9 orange 2019 orange

Or we can also join
merge(df, color_fruit, by = 'fruit')[-3]

data
df <- structure(list(fruit = c("apple", "apple", "apple", "banana",
"banana", "banana", "orange", "orange", "orange"), year = c(2017L,
2018L, 2019L, 2017L, 2018L, 2019L, 2017L, 2018L, 2019L), color = c("red",
"red", "red", "", "", "", "orange", "orange", "orange")), class = "data.frame",
row.names = c(NA, -9L))


text:
Q: Dropping every predictor once at a time in R Let's say I have 4 predictors x1, x2, x3, x4.
I want to have a code that drops every predictor one at a time.
For e.g.
set.seed(10)
y<-c(1:20)
x1<-c(1:20)*runif(20,min=0,max=2)
x2<-c(1:20)*runif(20,min=0,max=2)
x3<-c(1:20)*runif(20,min=0,max=2)
x4<-c(1:20)*runif(20,min=0,max=2)

lm1<- lm(y~x1+x2+x3+x4) #full model

#drop each predictor once

lm2.1<- lm(y~x2+x3+x4)
lm2.2<- lm(y~x1+x3+x4)
lm2.3 <- lm(y ~ x1+x2+x4)
lm2.4 <- lm(y ~ x1+x2+x3)

etc.

A: You can use drop1 if you want to see the contribution of each term:
drop1(lm1)

# Single term deletions
#
# Model:
# y ~ x1 + x2 + x3 + x4
#        Df Sum of Sq    RSS    AIC
# <none>              104.15 43.002
# x1      1    15.465 119.61 43.771
# x2      1    64.166 168.31 50.602
# x3      1    29.485 133.63 45.987
# x4      1     0.910 105.06 41.176

This is similar to anova(lm1, lm2.1, lm2.2, lm2.3, lm2.4).

A: I'm going to go ahead and assume you're looking for finding the best model guided by the data.
To automate the process and find out which would be the best model (data wise):
step(lm(y~x1+x2+x3+x4))

In your case it yields:
lm(y~x1+x2+x3)

as the best model.
This will also yield the contributions for each model. Note that it will consider in this case dropping each case, and evaluate which variable would be best to drop. Apparently X4 would be best to drop in this case. It even checked dropping more variables, but in this case it did not yield a better model.
As pointed out, it does not make much sense usually to optimize a model based on data only. If you still insist, an advise would be to cross-validate and see if on new data the model still holds (which it shouldn't, based on this random data). Moreover, it never hurts to consider whether the model "makes sense" from a substantive point (and in fact is very much advised).


text:
Q: Errors when passing metadata into context in golang I am working on specific with handling GRPC requests. I am trying to pass the meta from my GRPC request into the context based on this code sample: https://github.com/go-kit/kit/blob/master/auth/jwt/transport.go#L47.
(just in case, the contextKey explanation can be referred here: https://medium.com/@matryer/context-keys-in-go-5312346a868d#.vn10llkse):
Below is my code:
type contextKey string

func (c contextKey) String() string {
    return string(c)
}

var Headers := metadata.New(map[string]string{"auth":"", "abc": "", "xyz" : ""})

func ToGRPCContext() grpctransport.RequestFunc {
    return func(ctx context.Context, md *metadata.MD) context.Context {
       for _, header := range Headers {
           val, ok := (*md)[header]
           if !ok {
               return ctx
           }
           if len(val) > 0 {
              ctx = context.WithValue(ctx, contextKey(header), val)
           }
       }
       return ctx
    }

}

I am trying to read metadata fields (Headers) and pass it to the context.
I am getting the following errors. cannot use header (type []string) as type string in map index and cannot convert header (type []string) to type contextKey. I had fixed the above errors by accessing the index and doing something like this val, ok := (*md)[header[0]]. However, I want to pass all the elements of the map to the context.
Any suggestions on how to work around this problem?

A: I think you want to use the header name as the context key:
for name, header := range Headers {
  val := r.Header.Get(header)
  if len(val) > 0 {
    ctx = context.WithValue(ctx, contextKey(name), val)
  }
}

Alternatively, store the headers as a single value:
ctx = context.WithValue(ctx, contextKey("headers"), Headers)


text:
Q: Is there any GeoCast or broadcast Protocol implemented in veins demo example?
*

*Is there any GeoCast or broadcast Protocol implemented in veins demo?

*Is there any default suppression technique implemented such as (
Slotted p-Persistence , Slotted 1-Persistence , Weighted
p-Persistence )?

A: Veins is a generic framework and in his demo it shows how to implement a  nonsensical protocol for information dissemination.However, it use a native suppression technique without any optimization.Each vehicle only relays a single event message without duplication.
For more details about suppression techniques :http://ieeexplore.ieee.org/xpl/login.jsp?tp=&arnumber=4407231&url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D4407231
Try also the Platooning Extension for Veins. It's an extension of Veins which permits the realistic simulation of platooning (i.e., automated car-following) systems. It features realistic vehicle dynamics and several cruise control models, permitting the analysis of control systems, large-scale and mixed scenario, as well as networking protocols and cooperative maneuver.

A: No. The Veins demo only shows how to implement a (deliberately) nonsensical protocol for information dissemination.


text:
Q: Preg_match: get last two domain segments from url in one expression There is an example on php.net how to get last two domain segments in two steps:
    <?php
 //get host name from URL
preg_match("/^(http:\/\/)?([^\/]+)/i",
    "http://www.php.net/index.html", $matches);
$host = $matches[2];

// get last two segments of host name
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";

/* Output is php.net */

?>

But how can I do it in one step, using only one preg_match expression?

A: This piece of code:
$domain = 'http://www.php.net/index.html';
$url    = parse_url($domain);
$tokens = explode('.', $url['host']);

print_r($tokens);

Will give you this data:
Array
(
    [0] => www
    [1] => php
    [2] => net
)

I believe there is no need for regexs as far as it's very hard to properly parse URL with them. From resulting $tokens array you can extract any part of host name easily.
Update:
print_r($url);

$url array contains all necessary details:
Array
(
    [scheme] => http
    [host] => www.php.net
    [path] => /index.html
)


text:
Q: How to download html file with all source files in js? Currently I'm using this piece of code to download current page on click:
function Download() {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(document.documentElement.outerHTML));
  element.setAttribute('download', "file.html");
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

Problem is that there are some audio files which are played from other server (by <audio src> tag). I would like to also download these files so if something will be removed on the server, saved page can still play sounds.
My idea was to replace src part of tag with local path and download audio files separately, but I'm wondering if there is better solution and what it would be?
Thanks!

A: You can create a single page with any external asset contained in it directly by converting the content to data urls. This makes the self contained HTML file easier to handle.
For example

    <img src="data:image/png;base64,[encoded data, 10168 characters]">

is a png image that doesn't require any external resource.

A: Extending @6502's answer
<audio src="data:audio/ogg;base64,binarystring"/>

Convert your files to base64 string and replace binarystring with the produced string.
Convert Files to Base64 string

Use this method wisely because it will make page load slower! Bigger the
file slower the page load!


text:
Q: Identify the columns which contain zero and output its location Suppose I have a dataframe where some columns contain a zero value as one of their elements (or potentially more than one zero). I don't specifically want to retrieve these columns or discard them (I know how to do that) - I just want to locate these. For instance: if there is are zeros somewhere in the 4th, 6th and the 23rd columns, I want a list with the output [4,6,23].

A: You could iterate over the columns, checking whether 0 occurs in each columns values:
[i for i, c in enumerate(df.columns) if 0 in df[c].values]

A: Here is an approach that leverages a couple of lambda functions:
d = {'a': np.random.randint(10, size=100),
     'b': np.random.randint(1,10, size=100),
     'c': np.random.randint(10, size=100),
     'd': np.random.randint(1,10, size=100)
    }

df = pd.DataFrame(d)

df.apply(lambda x: (x==0).any())[lambda x: x].reset_index().index.to_list()

[0, 2]

Another idea based on @rafaelc slick answer (but returning relative locations of the columns instead of column names):
df.eq(0).any().reset_index()[lambda x: x[0]].index.to_list()

[0, 2]

Or with the column names instead of locations:
df.apply(lambda x: (x==0).any())[lambda x: x].index.to_list()

['a', 'c']

A: Use any() for the fastest, vectorized approach.
For instance,
df = pd.DataFrame({'col1': [1, 2, 3],
                   'col2': [0, 100, 200],
                   'col3': ['a', 'b', 'c']})

Then,
>>> s = df.eq(0).any()

col1    False
col2     True
col3    False
dtype: bool

From here, it's easy to get the indexes. For example,
>>> s[s].tolist()
['col2']

Many ways to retrieve the indexes from a pd.Series of booleans.


text:
Q: Xamarin forms- Fill and expand the entry or editor in Xamarin forms all platforms I need a fill and expand function to my editor field, in layout options have fill and expand, that works for iOS only but not for android and windows phone, I want it to expand without pressing the enter key. It should expand whenever the paragraph has more lines typed.
xaml code:
<ContentView Style="{StaticResource BorderStyle}">
    <Editor x:Name="Ed_Notes" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" TextColor="Black"
            FontSize="{x:Static views:FontSizeView.CustomFontSizeMeMeMe}" TextChanged="Ed_TextChanged"></Editor>
</ContentView>


text:
Q: Can you report someone for 'stealing' an answer? I posted an answer recently, after I don't know a minute another person posts the same answer. I find this fine. Except that he didn't include somethings that I did.
So he edits his answer to mock out mine. Code that I didn't include because I thought it was self explanatory was added.
Is this flag-able? Should it be?  Here is the post:  How to convert from Shapes to string, int, etc...?
I understand that the particular question I was asking about IS basic. That it will draw similar conclusions, that's why I figured it wasn't the best example. I hope that explains myself a little bit for the downvotes.

A: The goal of Stack Overflow is to be a resource of knowledge for years to come. To achieve this, answers should be written in a generalized manner that appeals to the general programming audience.
If you've left out things that you, or the asker, assume everyone should know, then you may be excluding a lot of people searching for the same answers who may benefit from the extra information.
When an answer is posted quickly, one strategy that you can use is to post an answer that's better than the others.  Outright copying is of course frowned upon, but posting a better answer is encouraged and embraced.
If you can think of ways to make your answer better, I encourage you to edit it and improve it. There may be things that the other poster left out that may be helpful. However, at some point, realize that your answer may get too generalized and lengthy. In that case, leave it be. The community is likely to upvote both of your answers.
Remember, just because someone else gains doesn't mean that you necessarily lose. :)
Oh, I should add that, if someone does do something unsavory, like actually really plagiarize another answer, you could do one or more of the following:

*

*Post a question on meta to get clarification, like you did here.

*Leave a comment to the poster asking them to fix his/her post, politely of course. Sometimes people have good intentions, even if they do wrong.

*Flag the answer using the custom flag reason, and describe the situation to a diamond moderator.

A: There are two questions here:

Should answers that don't add anything new be flagged?

Yes. Maybe. It depends a bit on the circumstances.
There are a lot of questions that are pretty basic and will inevitably attract multiples of essentially the same answer posted almost at the same time as different people read the question and realise they can post a solution. This is largely fine.
If someone comes along a year later and copy/pastes the same answer again, that answer should be flagged and possibly removed. Or at least a comment should be left for the answerer asking them to knock it off.

Did Andrew Cooper steal your answer?

I think you're making some big assumptions there.
There is a difference of 30 seconds between your answer and Andrew's. Both your answers addressed the same basic problem with the code sample in the question. If I were reading that question 45 minutes ago, I probably would've posted something virtually identical in response too.
To me this seems to fit the first category above. (And in the end it turned out that the asker simply forgot a method name.)
The best approach in situations like this, IMHO, is to make your answer stand out in any way you can - more (relevant!) information, clearer explanations, and so on.


text:
Q: Conjecture about the system of powerful equations Conjecture.
Let $a$ and $b \neq \pm 1$ be two integers.
Assume that the following system of congruences holds:
$$\left\{\begin{array}{l}a-1 \equiv 0\mod{b-1}\\a^2-1 \equiv 0\mod{b^2-1}\\ \ldots\\a^n-1 \equiv 0\mod{b^n-1}\end{array}\right. (\star)$$
$\bf{a.}$ Is it true that $\frac{(b-a)(b^2-a)\cdot\ldots\cdot(b^n-a)}{(b-1)(b^2-1)\cdot\ldots\cdot(b^n-1)}\in\mathbb{Z}?$ Answer to it is "no" and it's because the comment of bof (i.e. $a=5, b=3, n=2$).
$\bf{b.}$ Is it true that $\frac{(b-a)(b^2-a)\cdot\ldots\cdot(b^n-a)}{(b-1)(b^2-1)\cdot\ldots\cdot(b^n-1)} = \frac{u}{v}$, where $v$ is a power of $2$? And what is the bound of $\log_2 v$ in terms of $n$ (is it true that $v\leq 2^n$)?

My ideas.
I think (if $(\star)\Rightarrow \bf{b}$ is true) that the next lemma can be helpful
Lemma. Consider $2n$ positive integers $a_1, a_2,\ldots, a_n$ and $b_1, b_2,\ldots, b_n$. Let it given that for any prime $p\not= 2$ and any positive integer $k$, $\#\{i:a_i\equiv 0 \mod{p^k}\}\geq \#\{j: b_j\equiv 0\mod{p^k}\}$. Then we have $\frac{\prod_{i=1}^n a_i}{\prod_{j=1}^n b_j}=\frac{u}{v}$, where $v$ is a power of $2$.

So I am really interested in any proof of the Conjecture, or in a counterexample to it.

A: Your lemma may indeed be applied.
Notations. For a prime $p$ and non-zero integer $x$ let $|x|_p$ denote the maximal non-negative integer $k$ for which $p^k|x$; and $|0|_p=+\infty$.
Also denote $$f(p^t)=\#\left\{i\le n: |b^i-1|_p\geqslant t\right\},\\
g(p^t)=\#\left\{i\le n: |b^i-a|_p\geqslant t\right\}.$$
Then I claim that $\sum_t g(p^t)\geqslant \sum_t f(p^t)$ for odd $p$ and
$|n!|_2+\sum_t g(2^t)\geqslant \sum_t f(2^t)$. In other words, the expression
$$
2^{[n/2]+[n/4]+[n/8]+\dots}\prod_{k=1}^n \frac{b^k-a}{b^k-1}
$$
is integral.
Fix a prime $p$. Choose minimal $s\in \{1,2,\dots,n\}$ for which $b^s\equiv 1 \pmod p$ (if such $s$ does not exist, there is nothing to prove). Note that $p$ does not divide $s$, else $b^{s/p}\equiv b^s\equiv 1\pmod p$ and $s$ is not minimal. Next, by minimality the residues $1,b,b^2,\dots,b^{s-1}$ are distinct modulo $p$, hence they all are the $s$ distinct roots of the polynomial $x^s-1$ over $\mathbb{F}_p$. Since $p$ divides $a^s-1$, $a$ is a root of the same polynomial and we get $a\equiv b^r\pmod p$ for some $r\in \{0,1,\dots,s-1\}$. Denote $a=b^r+P$, where $p$ divides $P$.
Lemma 1. $|P|_p\geqslant |b^s-1|_p$.
Proof of Lemma 1. Assume the contrary, denote $|P|_p=d\geqslant 1$ and assume that $b^s-1$ is divisible by $p^{d+1}$. Then $a^s-1=(b^r+P)^s-1\equiv sb^r P \pmod {p^{d+1}}$, since both $b^{rs}-1$ and $P^2$ are divisible by $p^{d+1}$. But neither $b$ nor $s$ are divisible by $p$ and we conclude that $|a^s-1|=d<|b^s-1|$, a contradiction.
We need also the following lifting
Lemma 2. Assume that $|b^S-1|_p=\beta\geqslant 1$, where $1\le S\le n$, and $a\equiv b^R \pmod{p^\beta}$ for certain $R$, where $0\le R<S$. Then we may find $\tau\in \{0,1,\dots,p-1\}$ such that $a\equiv b^{R+S\tau} \pmod {p^{\beta+1}}$.
Proof of Lemma 2. We have $b^{R+S\tau}=b^R(1+(b^S-1))^\tau\equiv b^R+\tau b^R(b^S-1)\pmod{p^{\beta+1}}$, and $\tau b^r(b^s-1)$ modulo $p^{\beta+1}$ takes all residues divisible by $p^\beta$ exactly once when $\tau\in \{0,1,\dots,p-1\}$. In particular, it takes the residue $a-b^R$ as needed.
Now denote $|b^s-1|_p=\alpha\geqslant 1$. Note that if $p$ divides $b^x-1$, we have $s|x$ and $|b^s-1|_x\geqslant \alpha$. In the next lifting lemma (referred sometimes as Hensel lemma) there is a difference between odd and even $p$.
Lemma 3. If $p$ is odd and $|b^S-1|_p>0$ for some $S>0$, then $|b^{kS}-1|_p=|b^S-1|_p+|k|_p$. The same holds if $p=2$ and $|b^S-1|_p>1$.
Proof of Lemma 3. It suffices to consider the case of prime $k$, the general case case goes by induction on $k$. Denote $d=|b^S-1|_p$. We have $b^{kS}-1=(1+(b^S-1))^k-1=k(b^S-1)+\binom{k}2(b^S-1)^2+\dots$. If $k$ is not divisible by $p$, we have $|k(b^S-1)|_p=d$ and other terms are divisible by $p^{d+1}$, thus $|b^{kS}-1|_p=d$. If $k=p$, we get $|k(b^S-1)|_p=d+1$.
If either $p$ is odd, or $p=2$ and $d\geqslant 2$, all other terms are divisible by $p^{d+2}$ and we conclude that $|b^{kS}-1|_p=d+1$.
Lemma 3 implies that, if either $p$ is odd or $\alpha>1$, for given $t\geqslant 0$ the minimal $x$ for which $p^{\alpha+t}$ divides $b^x-1$ equals $S=sp^{t}$, and $f(p^{\alpha+t})=[n/S].$ Also $f(p^u)=[n/s]$ for all $u\leqslant \alpha$.
Consecutively applying Lemma 2 we find $R<S$ such that $a\equiv b^R\pmod{p^{\alpha+t}}$. Then at least $[n/S]$ indices $i\le n$ satisfy $a\equiv b^i\pmod {p^{\alpha+t}}$ (namely, $i=R,R+S,\dots,R+([n/S]-1)S$.) This proves the odd case.
It remains to understand what happens for $p=2$ (and odd $b$). If $b-1$ is divisible by 4, the very same argument works due to Lemma 3. So, it remains to consider the case $b=4k+3$. Denote $\alpha=|b+1|_2\geqslant 2$. Since $b^2-1$ divides $a^2-1$, we get $|a-1|_2+|a+1|_2\geqslant \alpha$, therefore $\alpha$ is congruent to $\pm 1$ modulo $2^{\alpha-1}$. For $2\leqslant t\leqslant \alpha-1$ the powers of $b$ modulo $2^t$ are $-1,1,-1,1,\dots$, thus $g(2^t)\geqslant [n/2]=f(2^t)$. Also note that $g(2)=f(2)=n$. As for $t\geqslant \alpha$, it may appear that $g(2^t)=0$ (say, it happens for $a=5$, $b=3$), but for all such $t$ we get $\sum_{t\geqslant \alpha} f(2^t)=[n/2]+[n/4]+\dots$. This finishes the even case.

A: Thank You Fedor Petrov for the proof. In fact, I have another argument.
$\textbf{Lemma 1.}$ Consider $2n$ positive integers $a_1, a_2,\ldots, a_n$ and $b_1, b_2,\ldots, b_n$. Let it given that for a prime $p$ and any positive integer $k$, $\#\{i\leq n:a_i\equiv 0 \mod{p^k}\}\geq \#\{j\leq n: b_j\equiv 0\mod{p^k}\}$. Then we have $\dfrac{\prod_{i=1}^n a_i}{\prod_{j=1}^n b_j}=\dfrac{u}{v}$, where $p\nmid v$.
$\textbf{Lemma 2.}$ Consider any three integers $a, b, l$ and a prime number $p>2$. Let given that $ord_{p^l}(a)\mid ord_{p^l}(b)$. Then there exist a positive integer $1\leq k\leq ord_{p^l}(b)$, such that $a\equiv b^k\mod{p^l}$.
To see why Lemma 2 is true use the existence of the primitive root mod $p^l$ for $p>2$.
$$\textbf{Proof of the conjecture.}$$
Consider the set of prime numbers $S=\{p>2: p\mid\prod_{i=1}^n(b^i-1)\}$. From Lemma 1 we get that to prove the conjecture it's enough to show that for a given $p\in S$ and any positive integer $l$ we have $\#\{i\leq n: p^l\mid b^i-a\}\geq\#\{j\leq n: p^l\mid b^j-1\}$.
Let $l$ be such that $\#\{j\leq n: p^l\mid b^i-1\}>0$, so $ord_{p^l}(b)\leq n$. Now, since $\dfrac{a^{ord_{p^l}(b)}-1}{b^{ord_{p^l}(b)}-1}\in\mathbb{Z}$ we get $p^l\mid a^{ord_{p^l}(b)}-1$. So $ord_{p^l}(a)\mid ord_{p^l}(b)$. From Lemma 2 we get that for some positive integer $1\leq k_a\leq ord_{p^l}(b)$, we have that $a\equiv b^{k_a}\mod{p^l}$, or in other words $p^l\mid b^{k_a}-a$ and $k_a\in\{i\leq n: p^l\mid b^i-a\}$.
Finally easy to compute $\#\{j\leq n: p^l\mid b^j-1\} = [\dfrac{n}{ord_{p^l}(b)}]$. But also from the previous observations we get that $k_a, k_a+ord_{p^l}(b), \ldots , k_a+\left([\dfrac{n}{ord_{p^l}(b)}]-1\right)ord_{p^l}(b)\in\{i\leq n: p^l\mid b^i-a\}$. So $\#\{j\leq n: p^l\mid b^j-1\} = [\dfrac{n}{ord_{p^l}(b)}]\leq\#\{i\leq n: p^l\mid b^i-a\}$. $\Box$
$$\textbf{Proof of the estimation }\log_2 v\leq [n/2]+[n/4]+\ldots$$
Here we can apply Lemma 1 from this post. So we get $$|(b-1)(b^2-1)…(b^n-1)|_2\leq |n!|_2|(b-a)(b^2-a)…(b^n-a)|_2=|(b-a)(b^2-a)…(b^n-a)|_2+([n/2]+[n/4]+\ldots )$$ $\Box$


text:
Q: subprocess.check_output(), zgrep, and match limit Context: I'm trying to find a github repository of a python package. To do that, I'm zgrep'ping package archive for github urls. And it works fine until I limit output by 1 result:
# works, returns a lot of results
subprocess.check_output(["zgrep", "-oha", "github", 'Django-1.10.1.tgz'])  #  works, a lot of results
# add -m1 to limit output, returns status 2 (doesn't work)
subprocess.check_output(["zgrep", "-m1", "-oha", "github", 'Django-1.10.1.tgz'])  #  works, a lot of results
# same command, different file - works
subprocess.check_output(["zgrep", "-m1", "-oha", "github", 'grabber.py'])

From the command line, all three commands work fine. Any ideas?
Traceback:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 574, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['zgrep', '-m1', '-oha', 'github', 'pkgs/Django-1.10.1.tar.gz']' returned non-zero exit status 2

Command line:
$ zgrep -m1 -oha "github.com/[^/]\+/django" pkgs/Django-1.10.1.tar.gz
github.com/django/django

A: So, the reason is: zgrep is a shell script, which simply pipes the archive through gzip and egrep. If we limit number of results, egrep terminates the pipe, so gzip exits and complaints. In a console we never see it, but subprocess somehow catches this signal and raises an exception.
Solution: write mini-version of zgrep that doesn't complain
gunzip < $FILE 2> /dev/null | egrep -m1 -ohia $PATTERN


text:
Q: Convert '00:00' to '00:00:00' pandas I have a DataFrame that has a column with time data like ['25:45','12:34:34'], the initial idea is: first convert this column to a list called "time_list". Then with a for, iterate and convert it to minutes
time_list = df7[' Chip Time'].tolist()

time_mins = []
for i in time_list:
    h, m, s = i.split(':')
    math = (int(h) * 3600 + int(m) * 60 + int(s))/60
    time_mins.append(math)

But I got this error: ValueError: too many values to unpack... . It is because within the data there are values of only minutes and seconds but also others with hours, minutes and seconds.
My idea is to convert this column into a single format, that of 'hh:mm:ss' but I can't find the way. Thanks for your reply

A: Instead of using h, m, s = i.split(':') you should be using t = i.split(':') because the first expects the i.split to always return 3 values, but in cases where i = [aa:bb] it will only return two. From there you use the length of t to decide if you need to calculate the seconds or not.
Your code is converting everything to seconds and could be replaced with something like this:
t = i.split(':')
for i in range(len(t)):
    math += t[i] * 3600 ** (1./(60 ** i))
    # 3600 ** (1./(60 ** i)) returns 3600, 60, 1 for i = 0, 1, 2
time_mins.append(math)

but if your goal is just to append :00 to any entry that dosen't have seconds then you could just do this:
t = i.split(':')
if len(t) == 2:
    time_mins.append(str(i)+":00")
else:
    time_mins.append(i)

A: I found a solution:
I reformatted that column with a function:

*

*Creating function

def format_date(n):
    if len(n) == 5:
        return "{}:{}:{}".format('00', n[0:2], n[3:5])
    else:
        return n**

*Applying in that column with labda:

df7['ChipTime'] = df7.apply(lambda x: format_date(x.ChipTime), axis=1)
df7

and done. Thank you.