text:
Q: Changing Entry Text change text in other Entry text in item of ListView UPDATED:
I've got a ListView that get items added by a button.
The items have this template:
<ListView x:Name="ListViewAlbaranFactura"
            Margin="10"
            CachingStrategy="RecycleElement"
            HasUnevenRows="True">

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Frame Margin="10" BackgroundColor="White">
                            <StackLayout>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="Auto" />
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="Auto" />
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="40" />
                                    </Grid.ColumnDefinitions>

                                    <Button
                                        x:Name="BotonBorrarFacAlb"
                                        Grid.Row="0"
                                        Grid.Column="2"
                                        BackgroundColor="White"
                                        Clicked="BorrarItem"
                                        HorizontalOptions="End"
                                        Text="">
                                        <Button.FontFamily>
                                            <OnPlatform
                                                x:TypeArguments="x:String"
                                                Android="fa-solid.ttf#Font Awesome 5 Free Solid"
                                                iOS="Font Awesome 5 Free" />
                                        </Button.FontFamily>
                                    </Button>
                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="0"
                                        Text="Nro:" />
                                    <Label
                                        Grid.Row="1"
                                        Grid.RowSpan="2"
                                        Grid.Column="0"
                                        Text="Articulo:" />
                                    <Label
                                        Grid.Row="3"
                                        Grid.Column="0"
                                        Text="Relacion U/C:" />

                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="1"
                                        LineBreakMode="TailTruncation"
                                        Text="{Binding IdFacAlb}" />
                                    <Label
                                        Grid.Row="1"
                                        Grid.RowSpan="2"
                                        Grid.Column="1"
                                        LineBreakMode="WordWrap"
                                        Text="{Binding ArtFacAlb}"
                                        VerticalTextAlignment="Start" />
                                    <Label
                                        Grid.Row="3"
                                        Grid.Column="1"
                                        LineBreakMode="TailTruncation"
                                        Text="{Binding UnidadesCajaFacAlb}" />

                                </Grid>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*" />
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="0"
                                        Text="{Binding Label1}" />
                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="2"
                                        Text="{Binding Label2}" />

                                    <Entry
                                        x:Name="NameUnidadesFacAlb"
                                        Grid.Row="0"
                                        Grid.Column="1"
                                        Keyboard="Telephone"
                                        Text="{Binding UnidadesFacAlb}"
                                        />
                                    <Entry
                                        x:Name="NameCajasFacAlb"
                                        Grid.Row="0"
                                        Grid.Column="3"
                                        Keyboard="Telephone"
                                        Text="{Binding CajasFacAlb, StringFormat='{0:f2}'}"
                                         />

                                </Grid>
                                <Grid x:Name="gridTotal">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*" />
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="0"
                                        Text="Precio: " />
                                    <Label
                                        x:Name="TotalFacAlb"
                                        Grid.Row="0"
                                        Grid.Column="1"
                                        Text="{Binding TotalFacAlb, StringFormat='{0:F2} €'}" />

                                </Grid>

                                <Button
                                    BackgroundColor="Black"
                                    Clicked="btnGuardarAlbFac"
                                    HorizontalOptions="FillAndExpand"
                                    Text="Guardar"
                                    TextColor="White" />
                        </StackLayout>
                    </Frame>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

In my .CS i binding context to:
public AlbaranFactura (Modelos.Lite.Cabecera cabecera, Modelos.Lite.Cliente cliente)
    {
        this.cabecera = cabecera;
        this.cliente = cliente;
        InitializeComponent ();
        this.albaranFactura = new Controladores.AlbaranFacturaController(cabecera, ListViewAlbaranFactura, cliente);
        this.BindingContext = albaranFactura;
    }

And in AlbaranFacturaController :
public AlbaranFacturaController (Modelos.Lite.Cabecera cabecera, ListView ListViewAlbaranFactura, Modelos.Lite.Cliente cliente)
    {
        this.ListViewAlbaranFactura = ListViewAlbaranFactura;
        this.cliente = cliente;
        this.cabecera = cabecera;
        CargarAlbaranFactura();

        AddArticulo = new Command(abrir);
    }

Where CargarAlbaranFactura()load data:
public void CargarAlbaranFactura()
    {
        try
        {
            Utils.UIHandler.RunOnUI(() => {
                ListViewAlbaranFactura.BeginRefresh();
            });
            var NroCliente = cliente.CODIGO;
            var data = Conexiones.SQLiteHandler.GetSql(Connstring, "SELECT * FROM CabFacAlb;");
            Modelos.Lite.CabFacAlb cab = data.Select(q => SelectCabFacAlb(q)).Where(q => q.ClienteCFA == NroCliente).SingleOrDefault();
            var IdClienteTest = cab.NumCFA;
            var data2 = Conexiones.SQLiteHandler.GetSql(Connstring, "SELECT * FROM FacAlb;");
             List<Modelos.Lite.FacAlb> listadata2 = data2.Select(q => SelectFacAlb(q)).Where(q => q != null).ToList();

            var facalbList = new ObservableCollection<Modelos.Lite.FacAlb>();

            try
            {
                facalbList = new ObservableCollection<Modelos.Lite.FacAlb>(listadata2.Where(q => q != null && q.IdFacAlb == IdClienteTest ));
            }
            catch(Exception ex)
            {
                facalbList = null;
            }

            foreach(var item in facalbList)
            {
                var relacion = item.UnidadesCajaFacAlb;
                if(relacion == 0)
                {
                    item.Label1 = "Kg :";
                    item.Label2 = "Ud :";
                }
                else
                {
                    item.Label1 = "Ud :";
                    item.Label2 = "Cajas :";
                }
            }
            Utils.UIHandler.RunOnUI(() => {
                this.ListViewAlbaranFactura.ItemsSource = null;
                this.ListViewAlbaranFactura.ItemsSource = facalbList;
                ListViewAlbaranFactura.EndRefresh();
            });
        }
        catch (Exception ex)
        {
            Utils.UIHandler.ErrorDebug("Cargar Albaran/factura: Warning", ex.Message, Utils.UIHandler.MessageLevel.Warning);
        }

    }

I don't understand how link directly the text from a entry in a item to the other entry text.
My items are Modelos.Lite.FacAlbwhere are:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

    public class FacAlb : INotifyPropertyChanged
{
    public long         IdContador { get; set; }
    public long         IdFacAlb { get; set; }
    public string       FechaFacAlb { get; set; }
    public string       TipoDocumento { get; set; }
    public string         ArtFacAlb { get; set; }
    public string unidadesFacAlb;
    public string cajasFacAlb;
    public string UnidadesFacAlb
    {
        get
        {
            return unidadesFacAlb;
        }
        set
        {
            try
            {
                if (value == unidadesFacAlb) return;
                unidadesFacAlb = value;
                if (UnidadesFacAlb != "")
                {
                    totalFacAlb = (PrecioFacAlb * double.Parse(UnidadesFacAlb))*((100-DtoFacAlb)/100);
                }
            }catch(Exception ex)
            {
                Console.WriteLine("Error " + ex.Message);
            }

            SetCajas();
        }

    }
    public string CajasFacAlb
    {
        get
        {
            return cajasFacAlb;
        }
        set
        {
            if (value == cajasFacAlb) return;
            cajasFacAlb = value;
            SetUnidades();
        }
    }
    public double?      UnidadesCajaFacAlb { get; set; }
    public double?      PrecioFacAlb { get; set; }
    public double?      DtoFacAlb { get; set; }
    public double?      totalFacAlb;
    public double?      TotalFacAlb
    {
        get
        {
            return totalFacAlb;
        }
        set
        {

            if (value == totalFacAlb) return;
            totalFacAlb = value;

        }
    }
    public string       Label1 { get; set; }
    public string       Label2 { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    void SetCajas()
    {
        if(UnidadesCajaFacAlb != 0 && UnidadesCajaFacAlb != null && UnidadesFacAlb != "")
        {
            double? valor = double.Parse(UnidadesFacAlb) / UnidadesCajaFacAlb;

            if(valor != null)
            {
                CajasFacAlb = valor.ToString();
            }
            else
            {
                CajasFacAlb = "";
            }

        }
        else
        {
            CajasFacAlb = "";
        }

    }
    void SetUnidades()
    {
        if(UnidadesCajaFacAlb != 0 && UnidadesCajaFacAlb != null && CajasFacAlb != "")
        {
            double? valor = double.Parse(CajasFacAlb) * UnidadesCajaFacAlb;
            if(valor != null)
            {
                UnidadesFacAlb = valor.ToString();
            }
            else
            {
                UnidadesFacAlb = "";
            }

        }
        else
        {
            UnidadesFacAlb = "";
        }
    }

    public FacAlb() { }
    public FacAlb(Dictionary<string, object> q)
    {

        this.IdContador = (long)q["IdContador"];
        this.IdFacAlb = (long)q["IdFacAlb"];
        this.FechaFacAlb = q["FechaFacAlb"] as string;
        this.TipoDocumento = (string)q["TipoDocumento"];
        this.ArtFacAlb = (string)q["ArtFacAlb"];
        this.PrecioFacAlb = double.Parse(q["PrecioFacAlb"].ToString());
        this.DtoFacAlb = (double?)q["DtoFacAlb"];
        this.UnidadesCajaFacAlb = q["UnidadesCajaFacAlb"] is DBNull ? 0 : (double?)q["UnidadesCajaFacAlb"];
        this.UnidadesFacAlb = q["UnidadesFacAlb"].ToString();
        this.CajasFacAlb = q["CajasFacAlb"].ToString();

    }

}

How i build the MVVM function that control the PropertyChanged ?

A: If using INotifyPropertyChanged in FacAlb , set/get of parameters can be writtren as follow:
FacAlb:
public class FacAlb : INotifyPropertyChanged
{

private long idContador;
public long IdContador
{
   set
   {
      if (idContador != value)
      {
         idContador = value;
         OnPropertyChanged("IdContador");
      }
    }
    get
    {
         return idContador;
    }
}

private long idFacAlb;
public long IdFacAlb
{
   set
   {
      if (idFacAlb != value)
      {
         idFacAlb = value;
         OnPropertyChanged("IdFacAlb");
      }
    }
    get
    {
         return idFacAlb;
    }
}

privatestring fechaFacAlb;
public string FechaFacAlb
{
   set
   {
      if (fechaFacAlb != value)
      {
         fechaFacAlb = value;
         OnPropertyChanged("FechaFacAlb");
      }
    }
    get
    {
         return fechaFacAlb;
    }
}

private string TipoDocumento;
public string tipoDocumento
{
   set
   {
      if (tipoDocumento != value)
      {
         tipoDocumento = value;
         NotifyPropertyChanged("TipoDocumento");
      }
    }
    get
    {
         return tipoDocumento;
    }
}

private string artFacAlb;
public string ArtFacAlb
{
   set
   {
      if (artFacAlb != value)
      {
         artFacAlb = value;
         NotifyPropertyChanged("ArtFacAlb");
      }
    }
    get
    {
         return artFacAlb;
    }
}
//... other code

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged([CallerMemberName] String propertyName = "")
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

//... other code

}

Here is a official document , and a discussion about using INotifyPropertyChanged in Xamarin.Forms.


text:
Q: QSystemTrayIcon activated signal: DoubleClick without Trigger I want to show context menu on left click and run app on double click.
For this i have next code:
...
connect(this, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(slotActivated(QSystemTrayIcon::ActivationReason)));
...
void MyTray::slotActivated(ActivationReason reason)
{
    if(reason==QSystemTrayIcon::DoubleClick)
        startApp();
    else
        if(reason==QSystemTrayIcon::Trigger
           || reason==QSystemTrayIcon::MiddleClick)
                contextMenu()->popup(QCursor::pos());
}

It works, but for double click case i got two slot calls - one for Trigger and only then for DoubleClick. As result context menu shown and hidding in a moment.
Is there is a way to avoid this?

A: Rather than using slotActivated, you need to handle the mouse events.
Whilst these aren't directly available in QSystemTrayIcon, it does allow you to install an event filter and handle the mouse events from there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not able to click dropdown I am a new learner in selenium and try to click on a dropdown to populate list but it keeps on giving me runtime exception:

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException:
    Element is not currently visible and so may not be interacted with )

Please help. Below is my code that I am executing.
    WebDriver dr=new FirefoxDriver();
    dr.get("https://jqueryui.com/selectmenu/");
    dr.manage().window().maximize();
    dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    dr.switchTo().frame(dr.findElement(By.className("demo-frame")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("speed-       menu"))).click();

A: To click on the Dropdown Select a speed, here is your own code with minimal changes:
    System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
    WebDriver dr=new FirefoxDriver();
    dr.get("https://jqueryui.com/selectmenu/");
    dr.manage().window().maximize();
    dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    dr.switchTo().frame(dr.findElement(By.className("demo-frame")));
    dr.findElement(By.xpath("//*[@id='speed-button']/span[@class='ui-selectmenu-text']")).click();

Let me know if this Answers your Question.

A: Try This
WebDriver driver = new FirefoxDriver();
driver.get("https://jqueryui.com/selectmenu/");
WebElement DynamicElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));

OR
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("yourid")));


text:
Q: after effects looping for web im making a video for a website in after effects
Its  a simple under construction page. The video made in after effects effectively has two parts

*

*transitions in the text,

*some minor flicker animation.

I want to keep the flicker animation going for the rest of the time (infinite loop on my page), instead of looping the whole video. How do i Do that?

A: You can use a video api like this one:
http://videojs.com/docs/api/
A simple event would be the solution.
var myFunc = function(){
  var myPlayer = this;

if(myPlayer.currentTime == x) {
myPlayer.currentTime(y);
};
myPlayer.addEvent("eventName", myFunc);

A: Your best bet is some kind of script (like the one posted by Gijoey above...) You can technically export videos to be "looping" but trusting that keyframing to translate across codecs/browsers is risky. I would convert the vid to something like an FLV / F4V as well. You could wrap it in a SWF if you want to deal with flash, but that's probably unnecessary for this purpose :P


text:
Q: glassfish and tomcat print date as question marks after creating respective services in windows 10 glassfish and tomcat prints date correctly if service is not created,
but after creating it as a service, date is printed wrongly.
Even in glassfish log the datetime is coming as ????-??-??T??:??:??.???+0530
Sample Code from java that prints wrongly when Locale.XX is not provided as parameter in SimpleDateFormat .
String dateInString = new SimpleDateFormat(pattern).format(new Date());
out.println(dateInString);

OUTPUT
??-??-???? ??:??:??

When Local.XX was provided:
String pattern = "MM-dd-yyyy HH:mms";
SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.UK);
out.println(formatter.getTimeZone().getDisplayName());
out.println(new Date());
out.println(formatter.format(new Date()));
out.println(formatter.getTimeZone().getDisplayName());

OUTPUT
India Standard Time
Thu Apr 12 10:40:04 IST 2018
04-12-2018 10:40:04
India Standard Time

GlassFish Version:  4.1.2
Java Version: 1.8.0_161
Initially the Datetime format for the system was set in Marati Language, and was later changed to English, but that did not solve the issue.
The problem exists only in this specific system. Other systems with same configurations have no issues.


text:
Q: Retrieving value from one table to another I have three tables

*

*tab_contactlist (contact_id(identity(1,1) not null), name, address, phoneno, emailaddress)

*tab_group (group_id (identity(1,1) not null), group_name)

*tab_information (contact_id, group_id)

My question is while inserting the value into tab_contactlist and tab_group then how to store two tables (tab_contactlist, tab_group) id into tab_contactlist where contact_id and group_id is in tab_contactlist ..
Can anyone have any idea about this? Please help me..

A: create table #tab_contactlist(
contact_id int identity(1,1) not null
,name varchar (100)
,address varchar (100)
,phoneno varchar (100)
,emailaddress varchar (100)
)

create table #tab_group(
group_id int identity(1,1) not null
,group_name varchar (100)
)

create table #tab_information(
contact_id int
,group_id int
)

declare @contact_id_var int
declare @group_id_var int

insert into #tab_contactlist (name,address,phoneno,emailaddress)
    values ('name1','address1','phoneno1','emailaddress1')
select @contact_id_var = SCOPE_IDENTITY()

insert into #tab_group (group_name) values ('group_name1')
select @group_id_var = SCOPE_IDENTITY()

insert into #tab_information(contact_id,group_id) values (@contact_id_var ,@group_id_var)

A: declare @contact_id_var int
declare @group_id_var int

insert into tab_contactlist (....) values (....)
select @contact_id_var = @@IDENTITY

insert into tab_groupvalues (....) values (....)
select @group_id_var = @@IDENTITY

insert into tab_information(contact_id,group_id) values (@contact_id_var ,@group_id_var)


text:
Q: How to parse JSON object with $.ajax() method I am trying to parse a JSON object (not stored on a file) by using $.ajax() method but it is not functioning. What am I doing wrong?
var painting = [
        {
        "title": "Boardwalk 5",
        "artist": "Arnie Palmer",
        "image": "ap1.jpg",
        "price": 850
        },
        {
        "title": "A Lasting Piece",
        "artist": "Arnie Palmer",
        "image": "ap2.jpg",
        "price": 450
        },
        {
        "title": "Surf at High Tide",
        "artist": "Arnie Palmer",
        "image": "ap3.jpg",
        "price": 950
        },
        {
        "title": "The Games We Play",
        "artist": "Arnie Palmer",
        "image": "ap4.jpg",
        "price": 850
        }
      ];
$(document).ready(function () {
$.ajax({
    type: 'GET',
    url: 'painting',
    dataType: 'json',
    success: jsonParser
});

});

function jsonParser(json) {
    $.getJSON(painting, function(data){
        $.each(painting, function(k,v){
            var title = v.title;
            var price = v.price;
            $('#container').append('

' + title + '
$' + price + '

')
        });
    });
}

A: Why do you need .ajax to parse json that is in variable?
Have you tried only this:
$.each(painting, function(k,v){
  var title = v.title;
  var price = v.price;
  $('#container').append('

' + title + '
$' + price + '

')
});

If I understood you good, you do not need .getjson and .ajax since those are Ajax calls to retrieve external data?

A: Maybe he's trying to get a json from a file ?
Maybe painting.json or painting is his json file.
that'll explain why he's using ajax and getJson.
You have to understand that  $.getJSON uses $.ajax.
So :
var painting = [
    {
    "title": "Boardwalk 5",
    "artist": "Arnie Palmer",
    "image": "ap1.jpg",
    "price": 850
    },
    {
    "title": "A Lasting Piece",
    "artist": "Arnie Palmer",
    "image": "ap2.jpg",
    "price": 450
    },
    {
    "title": "Surf at High Tide",
    "artist": "Arnie Palmer",
    "image": "ap3.jpg",
    "price": 950
    },
    {
    "title": "The Games We Play",
    "artist": "Arnie Palmer",
    "image": "ap4.jpg",
    "price": 850
    }
  ];
  $(document).ready(function () {

    $.getJSON('painting.json', function(data){
        $.each(data, function(k,v){
            var title = v.title;
            var price = v.price;
            $('#container').append('

' + title  + '
$' + price + '

')
        });

     });
});

is enough


text:
Q: Sound in raw from EditText Data Storage Excuse me, can you help me. I'm making an application for children learning. The application of writing the alphabet in the form of "EditText". I want this text into sound from /raw. I have A.mp3 - Z.mp3 from /raw
MediaPlayer mplayer;
Button play;

private final View.OnClickListener playButtonListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // play
        if (mplayer != null) {
            mplayer.start();

        }
    }
    };

     .........
       .........
       .........

    play = (Button) findViewById(R.id.button1);
    play.setOnClickListener(playButtonListener);
    mplayer = MediaPlayer.create(this, R.raw.(txtToDisplay)); <------- this is error

       }
         .........
          .........
         .........
    //prediction.name is data storage
       txtToDisplay = prediction.name;
        showText1.setText(txtToDisplay);

My data storage is "prediction.name" or txtToDisplay. Prediction.name is A,B,C,D,E,F,G,H ... ,Z. My sound in /raw A.mp3, B.mp3. C.mp3 ... ,Z.mp3
This is full my java
package com.example.belajargesture;

import java.util.ArrayList;
import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements
        OnGesturePerformedListener {
    private GestureLibrary mLibrary;
    EditText showText1;
    String txtToDisplay = "";
    //musik
    MediaPlayer mplayer;
    Button play;
    //musik

    //musik
    private final View.OnClickListener playButtonListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // play
            if (mplayer != null) {
                mplayer.start();

            }
        }
    };
    //musik

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);
        if (!mLibrary.load()) {
            finish();
        }

        GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
        gestures.addOnGesturePerformedListener(this);

        //musik
        play = (Button) findViewById(R.id.button1);
        play.setOnClickListener(playButtonListener);
        mplayer = MediaPlayer.create(this, R.raw.a);
        //musik

    }

    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
        ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
        showText1 = (EditText) findViewById(R.id.editText1);
        // We want at least one prediction
        if (predictions.size() > 0) {
            Prediction prediction = predictions.get(0);
            // We want at least some confidence in the result
            if (prediction.score > 1.0) {
                // Show the spell
                txtToDisplay = prediction.name;
                showText1.setText(txtToDisplay);

            }

        }
    }

}


text:
Q: Proving that this map is neither open nor closed
Let X={(x,y)$\in \mathbb{R}^2  :x \geq$ 0 or y=0}, and let T be the subspace topology on X induced by induced by usual topology on $\mathbb{R}^2$ and let U be the usual topology on $\mathbb{R}$. Define f:$X \to \mathbb{R}$ by f((x,y)=x for all (x,y) $\in X$. Prove that it is neither open nor closed.

I am really confused on how this problem should be solved . I tried to make some counterexamples but couldn't sucessfully disprove it.
This question was about proving f to be a quotient map and I proved that by definition but I am struck in this.
Can you please spare some time for it?

A: $\{(x,y): 1<y<2, 0 \leq x <1\}$ is an open set in $X$ whose image is not open. $\{(x,\frac  1 x)
: x>0\}$ is a closed set in $X$ whose image is not closed.


text:
Q: My bootstrap modal isn't working Question
I'm making a reservation plugin for a website. I want a modal for a datepicker, but from my perspective everything seems right. But when I click the modal-button, nothing happens. I've searched on the internet en dubble checked my css/js links but I think everything is the right place.
Does anyone know what I'm doing wrong and help me in the right direction? Thanks
MY CODE
testpage_modal.php
<?php /* Template name: Modal template */ ?>

<?php get_header(); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php the_title();?>

    Selecteer uw gewenste datum *

    <input type="text" name="datum" value="" required>

    <button type="button" class="btn btn-default btn-md" data-toggle="modal" data-target="#my_btn">Kies datum >    </button>

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

Modal Header

Some text in the modal.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

<?php endwhile; endif; ?>

<?php
get_footer(); ?>

header.php
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">

<title>Title</title>

<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">

<link rel="stylesheet" type="text/css" href="css/style.css" >

footer.php

A: Your data-target doesn't match the modals:
 <button type="button" class="btn btn-default btn-md" data-toggle="modal" data-target="#my_btn">Kies datum >    </button>

Should be:
 <button type="button" class="btn btn-default btn-md" data-toggle="modal" data-target="my_modal">Kies datum >    </button>

Or if you want to use the javascript, then you should give your button the ID = "my_btn", like this
<button type="button" class="btn btn-default btn-md" id="my_btn">Kies datum >    </button>

A: button data-target & modal id should be match otherwise your modal not worked.
<button type="button" class="btn btn-default btn-md" data-toggle="modal" data-target="#my_btn">Kies datum >    </button>

A: No need to use this JS code. Just remove those lines:

and replace following line for your button:
<button type="button" class="btn btn-default btn-md" data-toggle="modal" data-target="#my_modal">Kies datum >    </button>


text:
Q: What is the third argument for in Django url patterns? I am new to Django and I am trying to understand it. If I write a url pattern like this
url(r'^$', 'newsletter.views.home', name='home'),

it works. and If I write it like this
url(r'^$', 'newsletter.views.home'),

it still works, but I get the following data from the server
RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got newsletter.views.contact). Pass the callable instead.
  url(r'^contact/$', 'newsletter.views.contact'),
My first question is what does the third argument do. the
name='home' or name='contact'. What is it reffering to.

and my second question is what does
Pass the callable instead.

mean? Again, I have read the docs and came here for a bit more clarity in laymen's terms. All help and advice is welcome

A: When it says pass the callable, it means you should import the view itself and include that in your url pattern.
from newsletter.views import home

url(r'^$', home, name='home'),

Another option is to import the views module itself
# renaming allows us to import more than one views at once
from newsletter import views as newsletter_views

url(r'^$', newsletter_views.home, name='home'),

Naming url patterns allows you to reverse url patterns (e.g. go from a name to a url). This means you don't have to hardcode urls in your views and templates.
If you have
url(r'^home/$', home, name='home'),

then you can use reverse('home') in your code, and {% url 'home' %} in your templates, instead of writing /home/ repeatedly.


text: Q: What's the fastest way to draw sth on UIView? I'm developing a msqrd-like game and I can see that SpriteKit is kinda slow, so is manual adding .addSubview. What's the other way to draw simple 2d object (so it'll really fast)?


text:
Q: Using Karate, I am trying to match two json arrays which are out of order for e.g.
* def products = [{"ProductCode":"a","UnitPrice":100.0},{ {"ProductCode":"b","UnitPrice":200.0}]

* def inventory = [{"ProductCode":"b","UnitPrice":200.0},{ {"ProductCode":"a","UnitPrice":100.0}]

* match products == inventory

This fails as the order of elements in the array are not matching. How can I tell karate to ignore the order?

A: You really really should read the docs: https://github.com/intuit/karate#match-contains
* def products = [{"ProductCode":"a","UnitPrice":100.0},{"ProductCode":"b","UnitPrice":200.0}]
* def inventory = [{"ProductCode":"b","UnitPrice":200.0},{"ProductCode":"a","UnitPrice":100.0}]
* match products contains only inventory

A:
The match operation is smart because white-space does not matter, and the order of keys (or data elements) does not matter. Karate is even able to ignore fields you choose - which is very useful when you want to handle server-side dynamically generated fields such as UUID-s, time-stamps, security-tokens and the like.

The match syntax involves a double-equals sign '==' to represent a comparison (and not an assignment '=').


text:
Q: Technical term for services like Sandstorm.io This isn't exactly a programming question but I thought this would still be the best community to find an answer for my question.
I'd like to know if there is a specific technical term that describes services like sandstorm.io. I'm looking for kind of a buzzword more specific than "personal cloud" or "SaaS", describing exactly this model of having packaged web applications available in an app-store for one-click deployment to a private cloud environment.
The reason why I'm looking for such a search word is that I need to do some scientifical research on evaluating such a concept for enterprise application. So if you know some related work for that topic by chance please let me know.
And are there any alternatives with the same concept as Sandstorm?

A: I'm the founder of Sandstorm and I don't know if there is a precise term to use here. Other "self-hostable personal cloud" platforms include ownCloud, Cozy Cloud, and YunoHost. Other "private cloud app markets" include Bitnami and AppDirect (who actually powers many markets). Other "container engines/infrastructure" include Docker, Rocket, Kubernetes, and Mesos. Other "web application firewalls" include Imperva, f5, Guardium.
Note that Sandstorm's fine-grained containerization model is not implemented by any other platform to my knowledge, and this makes Sandstorm pretty fundamentally different from all these other products.
PS. I'd love to hear the results of your research when they're ready. :)


text:
Q: struct.pack and struct.unpack only doing the first character of a string So I'm trying to pack a packet header, and things are working fine, except for header flags I need to pack as strings are only unpacking the first character of the string.
For instance,
string = "ahhhhhh"
buffer = pack("s", string.encode('UTF-8'))
list = unpack("s", buffer)
print(list)

gives me (b'a')
What am I doing wrong?

A: Ah, so for my format string, I have to specify the amount of characters in the string I'm packing
string = "ahhhhhh"
buffer = pack("7s", string.encode('UTF-8'))
list = unpack("7s", buffer)
print(list)

would be correct


text:
Q: SQL: Selecting Distinct users and groupby based on condition I have a DB table:
User_id | User Name | Join_date  | Activity_date |
1           abc       01/01/2021    02-01-2021
2           jay       01/01/2021    03-01-2021
2           jay       01/01/2021    04-01-2021
1           abc       01/01/2021    09-01-2021
1           abc       01/01/2021    16-01-2021
2           jay       01/01/2021    05-01-2021
3           xyz       03/03/2021    12-03-2021
3           xyz       03/03/2021    30-03-2021
2           jay       01/01/2021    26-01-2021

I want to bucketize the user based on their Activity_date, as in users who do the activity every next day into table1, users who do activity weekly(gap of 6-7 days) into table2, all the other users into table3.
The output something like this:
temporary_table1: (people who do an activity every next continues day)
User_id | User Name | Join_date  | Activity_date |
2           jay       01/01/2021    03-01-2021
2           jay       01/01/2021    04-01-2021
2           jay       01/01/2021    05-01-2021

temporary_table_2: (people who do activist every 6-7 days from their first  Activity_date)
User_id | User Name | Join_date  | Activity_date |
1           abc       01/01/2021    02-01-2021
1           abc       01/01/2021    09-01-2021
1           abc       01/01/2021    15-01-2021

temporary_table_3: (Adding user_id =2 here because from the last activity done by this user to the recent activity done there is more than seven days of gap)
User_id | User Name | Join_date  | Activity_date |
3           xyz       03/03/2021    12-03-2021
3           xyz       03/03/2021    30-03-2021
2           jay       01/01/2021    26-01-2021

How to achieve this in SQL (Redshift)?

A: You should be able to do something like this and then you can make your grouping on the date_diff:
SELECT
user_id,
user_name,
join_date
activity_date,

#window function
LAG(activity_date) OVER (PARTITION BY user_id ORDER BY activity_date ASC) as day_before,

#difference in days between activity_date and day_before
DATEDIFF(
    day,
    LAG(activity_date) OVER (PARTITION BY user_id ORDER BY activity_date ASC),
    activity_date
    ) as date_diff
FROM your_dataset


text:
Q: How to retrieve all links from HTML document using DOMXPath I have this code
  <?PHP
      $content = '

         <title></title>

            second link

         ';

    $doc = new DOMDocument;
    $doc->loadhtml($content);
    $xpath = new DOMXPath($doc);
    $hrefs = $xpath->evaluate("/html/body//a");
    for ($i = 0; $i < $hrefs->length; $i++) {
            $href = $hrefs->item($i);
            $url = $href->getAttribute('href');
            echo $url ."
";
    }
    ?>

this code is very simple it just retrieve all anchor tags from an HTML document
I found it here
what I want is more complex :)
I want to retrieve all anchor tags + all children and parents and their attributes for every anchor tag
for example the result I want is when retrieving the first anchor tag is something like this
         1-html
         2-body
         3-ul
         4-li(class:list,id:list1111,style:etc....)
         5-a(href:www.example.com etc..)
         6-img(width:257 etc)

I want to iterate from the top level to the lowest level for every anchor tag and I want to be able retrieve the attributes for each tag
It is very difficult for me because of "DOMXPath" :( however it might be easy for some of you
do you have any question?
do you know how to solve this problem?
Thanks in advance

A: XPaths should make it so you don't need to iterate. To pull the important attributes of li use an XPath like:
//li/@class

or
//li/@id

which should give you an iterable object you can use.
Here's some more information on XPaths

A: Maybe you should write a simple XSLT stylesheet. Match the  tag, and then ancestor::* would give all parent nodes, child::* would give you all the children - you would have a lot more power using simple XPath syntax via XSLT.


text:
Q: Registering and receiving results from multiple DBMS_ALERTS in Java I have this little piece of code that registers for multiple DBMS_ALERTs and runs asynchronously in a servlet returning the responses in a JSONArray. The problem is that it registers and works only for the FIRST alert but not for the others?
When running this as an SQL script all is nice and dandy.
The SQL script I use:
DECLARE
alt varchar(100);
msg varchar(100);
sts integer;

BEGIN

dbms_alert.register('appdelete');
dbms_alert.register('devicelock');
dbms_alert.register('userlostapp');
dbms_alert.register('userlostdevice');

dbms_alert.waitany(alt,msg,sts,60);
dbms_output.put_line('alt= '||alt||' msg= '||msg||' sts= '||sts||chr(10));

END;

Also, it never runs the System.out parts in my method. Why is that? Did I make some stupid mistakes with AsynkTask(first time I use it so please be gentle)?
What am I missing here?

The code that registers the DBMS_ALERTs:
protected JSONArray dbmsAlert() {

    JSONArray DBMSResponse = new JSONArray();
    JSONObject responseRow = new JSONObject();

    CallableStatement cs1 = null;
    CallableStatement cs2 = null;

    String sql, sql1, sql2, sql3, sql4 = null;

    try {
        System.out.println("Trying to establish connection...");
        conn = ds1.getConnection();

        sql1 = "{call dbms_alert.register('appdelete')}";
        sql2 = "{call dbms_alert.register('devicelock')}";
        sql3 = "{call dbms_alert.register('userlostapp')}";
        sql4 = "{call dbms_alert.register('userlostdevice')}";

        System.out.println("Connection established!");

        for (int i = 1; i < 4; i++) {
            System.out.println("Entered FOR LOOP!");
            cs1 = conn.prepareCall("sql" + i);
            System.out.println("sql" + i);
            cs1.execute();
        }

        sql = "{call dbms_alert.waitone(?, ?, ?, 86400)}";

        System.out.println("Preparring Call for cs2...");
        cs2 = conn.prepareCall(sql);

        System.out.println("Registering Parametrs for cs2...");
        cs2.registerOutParameter(1, Types.VARCHAR);
        cs2.registerOutParameter(2, Types.VARCHAR);
        cs2.registerOutParameter(3, Types.INTEGER);

        int x = 0;
        int i = 0;

        System.out.println("DONE Preparring Call and Registering Parametrs!");
        while(x == 0) {
            System.out.println("Entered WHILE LOOP!");
            i++;
            cs2.execute();
            Integer result = cs2.getInt(3);

            if (result == 1) {
                System.out.println("dbmsAlert |DBMSResponse| for 1 : " + result);
            } else {
                String Result2 = cs2.getString(2);
                responseRow.put("DBMS", Result2);
                DBMSResponse.put(i, responseRow);

            }
        }
    } catch (Exception e) {
         //TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            cs2.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            cs1.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    System.out.println("dbmsAlert |DBMSResponse| for 0 : " + DBMSResponse);
    return DBMSResponse;
}

The code that runs the dbmsAlert() asynchronously:
1. The doGet() part:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    final AsyncContext asyncContext = request.startAsync(request, response);
    asyncContext.setTimeout(0);
    contexts.add(asyncContext);

    System.out.println("| contexts | contains : " + contexts.size() + " asyncContext elements");

    try {
        System.out.println("| HANDLING REQUEST |");
        handleRequests(request, response);
        System.out.println("| HANDLING REQUEST end |");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

2. The doPost() part:
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    doGet(request, response);

    List<AsyncContext> asyncContexts = new ArrayList<>(this.contexts);
    this.contexts.clear();

    System.out.println("| HANDLING RESPONSE |");

    System.out.println("| doPost | FOR REACHED!");
    for (AsyncContext asyncContext : asyncContexts) {

        int i = 1;

        System.out.println("| doPost | TRY REACHED!");
        try {
            asyncContext.getResponse();
            System.out.println("| dbmsAlert | REACHED! " + i++);
            dbmsAlert();
            System.out.println("| dbmsAlert | PASSED! " + i++);
            asyncContext.complete();
            System.out.println("| HANDLING RESPONSE end |");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Thanks.

A: Found the problem!
THIS piece of code(now that I look at it it hurts my eyes):
for (int i = 1; i < 4; i++) {
    System.out.println("Entered FOR LOOP!");
    cs1 = conn.prepareCall("sql" + i);
    System.out.println("sql" + i);
    cs1.execute();
}

SHOULD BE like this:
String[] sqls = new String[] {sql1, sql2, sql3, sql4};

for (int i = 0; i < 4; i++) {
    ALERTS.add(i, sqls[i]);
    System.out.println("ALERTS : " + ALERTS.get(i));

    csA = conn.prepareCall(ALERTS.get(i));
    csA.execute();
}

Really really really... stupid mistake.


text:
Q: NumberFormatException in Android app I am trying to make a simple contact list app. I tried to edit my contact by clicking on the phone list through activity for result, after editing when I pressed the save button and it gives me null pointer exception by throwing "id=null" at this line
long rowId=Long.parseLong(DBHandler.Key_ID)

in activity result(...) function. During debugging, when I clicked the contact for editing on the list it gets the id, but when I saved the edit part it gives null to id. Please help me.
Here is source code:
public class WebpreneurActivity extends ListActivity {

    private static final int CONTACT_CREATE = 0;
    private static final int CONTACT_EDIT = 1;
    public static  long id1;
    //select the second one, Android view menu
    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private DBHandler dbHelper;
    private Cursor c;
    ImageButton imageButton;
    public static long  rowId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d("database1" ,"0");
        Log.d("Your Location4", "ok4:");
        super.onCreate(savedInstanceState);
        Log.d("database1" ,"1");
        setContentView(R.layout.activity_webpreneur);
        Log.d("database1" ,"2");
        dbHelper = new DBHandler(this);
        Log.d("database1" ,"3");
        dbHelper.open();
        fillData();
        //dbHelper.open();

        //addListenerOnButton();
        //dbHelper.addContact();

        imageButton = (ImageButton) findViewById(R.id.imageButton1);
        Log.d("database1" ,"button");
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d("database1" ,"b4");
                Intent i = new Intent(getApplicationContext(), ContactEdit.class);
                startActivityForResult(i, CONTACT_CREATE);

                Log.d("database1" ,"button3");
                //fillData();
            }
         });

         //dbHelper.close();
     }

     @SuppressWarnings("deprecation")
     public void fillData() {
         Log.d("Your Location4", "ok6:");
         c = dbHelper.fetchAllRows();
         Log.d("Your Location4", "ok8:");
         //startManagingCursor(c);
         Log.d("Your Location4", "ok2:");
         NoIdCursorWrapper nc = new NoIdCursorWrapper(c, DBHandler.Key_ID);
         ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_row, nc, new String[] { DBHandler.Key_Name, DBHandler.Key_Phone }, new int[] { R.id.name, R.id.phonenumber });
         setListAdapter(adapter);
     }

     protected void onListItemClick(ListView l, View v, int position,   long id) {
         super.onListItemClick(l, v, position, id);

         Intent i = new Intent(this, ContactEdit.class);
         i.putExtra(DBHandler.Key_ID, c.getLong(c.getColumnIndex(DBHandler.Key_ID)));
         i.putExtra(DBHandler.Key_Name, c.getString(c.getColumnIndex(DBHandler.Key_Name)));
         i.putExtra(DBHandler.Key_Address, c.getString(c.getColumnIndex(DBHandler.Key_Address)));
         i.putExtra(DBHandler.Key_Phone, c.getString(c.getColumnIndex(DBHandler.Key_Phone)));
         i.putExtra(DBHandler.Key_Website, c.getString(c.getColumnIndex(DBHandler.Key_Home)));
         startActivityForResult(i, CONTACT_EDIT);
     }

     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);

         if (resultCode == RESULT_OK) {
             String name = data.getStringExtra(DBHandler.Key_Name);
             String address = data.getStringExtra(DBHandler.Key_Address);
             String mobile = data.getStringExtra(DBHandler.Key_Phone);
             String home = data.getStringExtra(DBHandler.Key_Home);

             //String id = data.getStringExtra(DBHandler.Key_ID);
             switch (requestCode) {
                 case CONTACT_CREATE:
                     Log.d("Your Location4", "jj:");
                     dbHelper.createRow(name, address, mobile, home);
                     Log.d("Your Location4" , "ok90:");
                     fillData();
                     break;

                 case CONTACT_EDIT:
                     //String id = data.getStringExtra(DBHandler.Key_ID);
                     long rowId=Long.parseLong(DBHandler.Key_ID); ////Giving null pointer exception at this point
                     Log.d("Your Location4" , "ok9b:");
                     if (rowId != (Long)null){
                         dbHelper.updateRow(rowId, name, address, mobile, home);
                     }
                     fillData();
                     break;
              }
          }
      }
  }

Here is my log cat/// [Note : Formatted logcat properly]
01-29 16:12:13.617: E/AndroidRuntime(26320): FATAL EXCEPTION: main
        01-29 16:12:13.617: E/AndroidRuntime(26320): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.webpreneur_contactlist/com.webpreneur_contactlist.WebpreneurActivity}: java.lang.NumberFormatException: ID
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2553)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:2595)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at android.app.ActivityThread.access$2000(ActivityThread.java:121)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:973)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at android.os.Handler.dispatchMessage(Handler.java:99)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at android.os.Looper.loop(Looper.java:138)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at android.app.ActivityThread.main(ActivityThread.java:3701)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at java.lang.reflect.Method.invokeNative(Native Method)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at java.lang.reflect.Method.invoke(Method.java:507)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at dalvik.system.NativeStart.main(Native Method)
        01-29 16:12:13.617: E/AndroidRuntime(26320): Caused by: java.lang.NumberFormatException: ID
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at java.lang.Long.parse(Long.java:353)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at java.lang.Long.parseLong(Long.java:344)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at java.lang.Long.parseLong(Long.java:311)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at com.webpreneur_contactlist.WebpreneurActivity.onActivityResult(WebpreneurActivity.java:129)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at android.app.Activity.dispatchActivityResult(Activity.java:3908)
        01-29 16:12:13.617: E/AndroidRuntime(26320):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2549)

A: change to:
long rowId=data.getLongExtra(DBHandler.Key_ID,0);

and after that:
 if (rowId != 0){
                         dbHelper.updateRow(rowId, name, address, mobile, home);
                     }

A: Wrap it with a try-catch and handle the exception
long rowId;
try {
    rowId=Long.parseLong(DBHandler.Key_ID);
} catch (NumberFormatException ex) {
    //Handle exception!
    //f.ex. rowId = -1;
}


text:
Q: Problems with samsung Pivotal web services and volley, Android application I have a pivotal service but when accessing the developed Android application that serves but when I use the application on a Samsung, it doesn't work, the following error is out:

java.net.UnknownHostException: host == null

A: Can you clarify. Volley is a client side library which you will deploy to a device.
Pivotal Web Services is a cloud based PaaS that can host web applications. It appears from your error that you haven't specified a URL for your client? Are you having issues with the server your volley client is trying to access?


text:
Q: send non-delivery notification I am fairly sure MobileMe (and possibly Mail.App) had a feature which allowed you to send a non-delivery notification for an email. This is possibly the best way to battle spam, however I can not find this feature anywhere now. Has it been removed or is it hidden somewhere else?

A: This page suggests that the feature exists in Mail under Lion. The feature, however, does not appear to exist, either as a toolbar option, nor as a Message menu command, nor as a context menu command, nor as an item in the Help file for Mail. The aforelinked document says "Lion" in its title, but refers to Mail 4.0; the Mail program under Lion is Mail 5.1.

This may or may not have anything to do with Apple's acknowledgement that bounce does not always dissuade spammers.


text:
Q: Turn off FPS monitor in chrome while DEV TOOLS is open It's crazy I have to post about this to get an answer but there is no way of googling this
I somehow made the FPS box show whenever I'm in developer tools, and I cannot find out how to hide it again.
if I google, they give me this link:
chrome://flags/#show-fps-counter
This option shows the option with dev-tools closed, but not with dev-tools open.
Please don't tell me to go to that link, yes I tried it and rebooted chrome.
I need to do UX/UI but the fact that the top right corner is obfuscated is making it very frustrating, especially because i cannot right click to close it, or view/window -> show/hide fps, or any simple answer.
Why is it so hard and hidden to do this? Even searching in the "help" for fps gives no results

A: There's a "Show FPS meter" checkbox buried in the Rendering subtab of the Elements tab:

+1 for how obscure and hard to find this was.

A: Got it
Open Developer Tools
Click the gear in top right of developer tools
Scroll to bottom "Restore Defaults and reload"
Still isn't a "Real Answer" but it did what I wanted
Stupid how that restore defaults is different from the Chrome > preferences > restore defaults

A: Just restored chrome to default settings because no one could answer
Edit: Don't do this if you are trying to solve this problem, as it will not change dev-tools settings


text:
Q: Error adding std_logic_vectors I wanna have a simple module that adds two std_logic_vectors. However, when using the code
below with the + operator it does not synthesize.
library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.std_logic_arith.all;

entity add_module is
        port(
  pr_in1   : in std_logic_vector(31 downto 0);
  pr_in2   : in std_logic_vector(31 downto 0);
  pr_out   : out std_logic_vector(31 downto 0)
        );
end add_module;

architecture Behavior of add_module is

begin

    pr_out <= pr_in1 + pr_in2;

end architecture Behavior;

The error message I get from XST
Line 17. + can not have such operands in this context.
Do I miss a library? If possible, I do not wanna convert the inputs into natural numbers.
Many thanks

A: Don't use std_logic_arith - I've written about this (at some length :).
Do use numeric_std - and do use the right type on your entity ports.  If you are doing arithmetic, use numerical types (either integers, or (un)signed vectors, as appropriate).  They'll synthesise perfectly well.
std_logic_vectors are good for

*

*when you don't care about numerical values (a set of control bits, some random data bits)

*when you don't know about the type of the input (say an adder which can operate on both signed and unsigned numbers based on a control flag).

A: How do you want the compiler to know if your std_logic_vectors are signed or unsigned ? Adder implementation is not the same in these two cases, so you need to explicitly tell the compiler what you want it to do ;-)
Note: VHDL syntax highlighting in StackOverflow is crappy. Copy/paste this code in your preferred VHDL editor to read it more easily.
library IEEE;
use IEEE.std_logic_1164.all;
-- use IEEE.std_logic_arith.all; -- don't use this
use IEEE.numeric_std.all; -- use that, it's a better coding guideline

-- Also, never ever use IEEE.std_unsigned.all or IEEE.std_signed.all, these
-- are the worst libraries ever. They automatically cast all your vectors
-- to signed or unsigned. Talk about maintainability and strong typed language...

entity add_module is
  port(
    pr_in1   : in std_logic_vector(31 downto 0);
    pr_in2   : in std_logic_vector(31 downto 0);
    pr_out   : out std_logic_vector(31 downto 0)
  );
end add_module;

architecture Behavior of add_module is
begin

  -- Here, you first need to cast your input vectors to signed or unsigned
  -- (according to your needs). Then, you will be allowed to add them.
  -- The result will be a signed or unsigned vector, so you won't be able
  -- to assign it directly to your output vector. You first need to cast
  -- the result to std_logic_vector.

  -- This is the safest and best way to do a computation in VHDL.

  pr_out <= std_logic_vector(unsigned(pr_in1) + unsigned(pr_in2));

end architecture Behavior;

A: Good advice from @Aurelien to use numeric_std.
Bear in mind that adding two 32 bit values can result in a 33 bit value and decide how you want to handle the overflow.

A: You cannot do an arithmetic operation with just std_logic_vector. Either you have to convert the std_logic_vector to signed/unsigned (depending on your code requirements) (see 1 below) or else convert them to integers (see 2 below)

*

*
     pr_out = std_logic_vector(unsigned(pr_in1) + "01")

*
     pr_out = std_logic_vector(integer(pr_in1) + 99)

These are just examples. You can change them based on your requirements.

A: The easy way to solve this error is:
Add library of unsign,
After that your code starts to work.
Use
ieee.std_logic_unsigned.all;
pr_out <= pr_in1 + pr_in2;


text:
Q: unknown table in my database of Oracle 10g When I did a select * from tab in my schema, it showed all the tables along with few new tables which are not created by me. The names of the table are quit contradictory to oracle naming conventions. One of them is like BIN$BwCyfyRPTJMKYfRpcHhiuQ==$0.
When I tried to drop them, it gave error invalid table name. I don't understand how did they got created in the first place. This is a local database of Oracle 10g. I doubt it as Virus. Please help how to get rid of these or I ll have to format my machine.

A: Those are dropped tables that were moved to the recycle bin.
If you run
PURGE RECYCLEBIN;

then those tables will go away.
More details in the manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9018.htm#SQLRF01803


text:
Q: IIS Reverse Proxy with OpenIdConnect going to wrong Identity provider OpenIdConnect (Azure) Settings
// COOKIES: Tells it to use cookies for authentication.
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    CookieManager = new SystemWebCookieManager()
});

// OPEN-ID: Authenticate via Azure AD using OpenIdConnect.
//https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-webapi-openidconnect/
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
    ClientId = ClientID,
    Authority = Authority,
    PostLogoutRedirectUri = PostLogoutRedirectUri,
    Notifications = new OpenIdConnectAuthenticationNotifications()
    {
        AuthenticationFailed = PrincipalService.OnAzureAuthenticationFailure,
        // REFERENCE: https://russellyoung.net/2015/09/05/mvc-role-based-authorization-with-azure-active-directory-aad/
        AuthorizationCodeReceived = (AuthorizationCodeReceivedNotification notification) =>
        {
            var username = notification.AuthenticationTicket.Identity.Name.Split('#').LastOrDefault();
            Logger.Log(Level.Auth, "Azure login success! Username: '" + username + "'.");
            return Task.FromResult(0);
        }
    }
});

ARR Url Rewrite Settings
<rewrite>
    <outboundRules>
        <preConditions>
            <preCondition name="ResponseIsHtml1">
                <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
            </preCondition>
        </preConditions>
    </outboundRules>
    <rules>
        <rule name="Secondary Server" stopProcessing="true">
            <match url="(.*)" />
            <conditions>
                <add input="{CACHE_URL}" pattern="^(https?)://" />
            </conditions>
            <action type="Rewrite" url="https://qa2mobile.auntmillies.com/{R:1}" />
            <serverVariables>
            </serverVariables>
        </rule>
    </rules>
</rewrite>

Problem
Azure AD authentication works just fine normally, but once I setup a reverse-proxy it starts taking me to my own domain as if it's the identity provider.
e.g. https://my.domain.com/<guid>/oauth2/authorize?client_id=<guid>&etc

*

*From this point, if I manually change my.domain.com to login.microsoftonline.com it'll log me in and proceed to work normally.

*If I remove the reverse proxy and set the server up normally, it goes directly to login.microsoftonline.com instead of my domain.

What is causing this? I mean, obviously the reverse proxy, but how do I fix it without removing the reverse proxy?

A:
What is causing this? I mean, obviously the reverse proxy, but how do I fix it without removing the reverse proxy?

As far as I know, if you use url rewirte rule in the web.config, it will rewrite all the request to the https://my.domain.com/ domain which is include the login.microsoftonline.com.
I suggest you could write a new rule which is used to match the /oauth2 request url to directly rediret to the login.microsoftonline.com instead of the https://my.domain.com/. Then it will work well.
More details, you could refer to below url rewrite rule.
    <rewrite>
        <rules>
          <rule name="rule2" stopProcessing="true">
            <match url="<talentid>/oauth2/(.*)" />
            <action type="Redirect" url="https://login.microsoftonline.com/{R:0}" />
          </rule>
            <rule name="ReverseProxyInboundRule1" stopProcessing="true">
                <match url="(.*)" />
                <action type="Rewrite" url="https://<domain>.com/{R:1}" />

            </rule>
        </rules>
        <outboundRules>

            <preConditions>
                <preCondition name="ResponseIsHtml1">
                    <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
                </preCondition>
            </preConditions>
        </outboundRules>
    </rewrite>


text:
Q: $type for Array field returns false I have a collection having following data:

{"_id" : ObjectId("5220222f8188d30ce85d61cc"),

"testfields" : [{
              "test_id" : 1,
              "test_name" : "xxxx"
          }]
    }
when I query :
db.testarray.find({ "testfields" : { "$type" : 4 } })

it returns no data,but same returns data when I do:
db.testarray.find({ "$where" : "Array.isArray(this.testfields)" })

It returns data, do the type:4 identifies some other kind of list?

A: Because testfields is an Array, $type : 4 will perform the "is array" check against every element in testfields as opposed to testfields itself.  Since your testfields contains just one Object, it does not get returned.
If on the other hand you inserted the following into your collection,
db.testarray.insert( { "testfields" : [ { "test_id" : 1, "test_name" : "xxxx" },
                                        [ "a", "b" ] ] } );

it would get returned because now one of the elements of testfields is an Array.
More info explaining this in the docs.


text:
Q: Why django_admin_log table is empty in Django Rest Framework I am developing a web application where I'm using Django 2.0.8 and Django Rest Framework to build a RESTful API. I have build some endpoint for basic CRUD operations. The problem is now I am trying to view log to my admin Dashboard. (Custom Admin Panel). But when I browsed my Database (PostgreSQL), I found that I have django_admin_log table but it is totally empty. But I created some object with those endpoints. Doesn't Django keep logs of user's activities by default? Or am I missing something?
PS: I was authenticated while creating those objects
django_admin_log table

A: Django logs actions done only via the Admin Panel. You can create custom logic to create records in the admin log table using the LogEntry model from django.contrib.admin.models.


text:
Q: async pushing data into array as web worker returns result I have developed code to perform operations by creating 5 web workers. I am simply sending integers to web workers to generate a sum and return a json object. I am pushing that result into an array. This array is stored in local storage once all web workers complete their task. The problem is array stored in local storage doesn't store values in the order returned by each web worker. If web worker returned the value first then the array must contain its value at zero index which means async operation is not being met. How do I go about doing this?
Here's my code for .js file:
      window.onload = init;
   var running = 0;
    var arr=[1,1001,2001,3001,4001];
   var sec=[1000,2000,3000,4000,5000]
   var results=[];
    function init() {

      sendworker();
    }

   function sendworker()
    {

     var n, worker;
     display("Starting workers...");

     for (n = 0; n <5; ++n) {
    workers = new Worker("jsonWorker.js");
    workers.onmessage = workerDone;
    workers.postMessage({id: n, start: arr[n],end:sec[n]});
    ++running;

     }

}

  function workerDone(e) {
    --running;
    display("Worker  " + e.data.id + " is done, sum of integers between: "+e.data.start+ "&"+e.data.end+"=" + e.data.sum);
    results.push(e.data.sum);

    if (running === 0) { // <== There is no race condition here, see below
        display("All workers complete");
        window.localStorage.setItem("Results", JSON.stringify(results));

    }
}

function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg);
    document.body.appendChild(p);
}

// My code for web worker.js
 this.onmessage = function(e) {
  var data = e.data;
  var a=data.start;
  var b=data.end;
  var c=0;
  for (var i=a; i<= b; i++) {

     c=c+i;

  }
  this.postMessage({id: e.data.id,start:a,end:b,sum: c});

};

In the picture worker 0 returned result first so its data should be on the second index of array stored in local storage but it is not.

A: Use their id as offset ( to get the results sorted after when they were started):
results[e.data.id] = e.data.sum;

A: You could use await Promise.all([someCall(), anotherCall()]).
You will get your results in the right order. (if you are transpiling your code)


text:
Q: Gif Loading Flutter I am using ImageNetwork for loading the gif but its getting cropped after one complete circle .
The same gif working fine in android natively.
Here is the code i am using :
Image.file("gif_url",
                  height: ScreenUtil().setHeight(250),
                  width: ScreenUtil.screenWidthDp,
                  fit: BoxFit.fitHeight)

Below is the link of the result video of the gif i am getting.
With Flutter i am getting this result:

With Native i am getting this result:

I want the same result as in Native one.
Please let me know how can i achieve that

A: try Image.asset like following:
Image.asset(
                  AssetUtils.loader // path to gif file,
                  alignment: Alignment.center,
                  fit: BoxFit.scaleDown,
                  height: MediaQueryUtils(context).height * 0.1,
                  width: MediaQueryUtils(context).height * 0.1,
                ),


text:
Q: Child process in php executes destructor of class objects created in parent process In the below code. I am trying to understand the behavior.
class ForkManager
{
    private $_max_workers = 3;
    private $_open_processes = 0;
    private $_tasks = array();

    public function setMaxWorkers($num)
    {
        $this->_max_workers = $num;
    }

    public function addTask($command)
    {
        $this->_tasks[] = $command;
    }

    public function execute()
    {
        while($this->_tasks) {
            $command = array_shift($this->_tasks);
            $pid = pcntl_fork();
            if(!$pid) {
                /* Execute in child process start */
                echo "$command\n";
                exec($command, $return, $out);
                exit(0);
                /* Execute in child process end */
            } else {
                ++$this->_open_processes;
                //var_dump($this->_open_processes, $this->_max_workers);
                if($this->_open_processes >= $this->_max_workers) {
                    (pcntl_wait($status));
                    --$this->_open_processes;
                }
            }
        }
    }

    public function getOpenProcess()
    {
        return $this->_open_processes;
    }

    public function isAllTaskCompleted()
    {
        return $this->_open_processes;
    }
}

class Scheduler {

    public function __construct() {
        var_dump("Waking up...");
    }

    private function getTasksForCurrentHour() {
        //static for now
        return array(
            'startmusic',
            'logintohris',
            'checkforerrorsemail',
            'startcoffeemachine'
        );
    }

    public function run() {
        $fm = new ForkManager();
        $tasks = $this->getTasksForCurrentHour();
        foreach ($tasks as $key => $task) {
            $fm->addTask('php UnversalWorker.php ' . $task);
        }
        $fm->execute();
    }

    public function __destruct() {
        var_dump("All tasks done... Going to sleep for an hour");
    }
}

$s = new Scheduler();
$s->run();

Now, the output of the code according to me should be
string(12) "Waking up..."
php UnversalWorker.php startmusic
php UnversalWorker.php logintohris
php UnversalWorker.php checkforerrorsemail
php UnversalWorker.php startcoffeemachine
string(44) "All tasks done... Going to sleep for an hour"

But the actual output is
string(12) "Waking up..."
php UnversalWorker.php startmusic
php UnversalWorker.php logintohris
php UnversalWorker.php checkforerrorsemail
string(44) "All tasks done... Going to sleep for an hour"
php UnversalWorker.php startcoffeemachine
string(44) "All tasks done... Going to sleep for an hour"
string(44) "All tasks done... Going to sleep for an hour"
string(44) "All tasks done... Going to sleep for an hour"
string(44) "All tasks done... Going to sleep for an hour"

It seems that every child process is calling the destructor of the parent process i.e. Scheduler class. I want to know is this the default behavior? If yes then any particular reason for that. And if no, then there must be some bug in my implementation. Can any one point me to that.


text:
Q: Can't connect to IIS site on network IP I've got a Server 2012 R2 box with IIS on it. I can't connect to the default website on the server's IP address. It stopped working after I disjoined one domain and joined another (not sure if this is related).
I can only connect to the site via localhost
Things I've checked

*

*The default website is bound to *:80. I've also tried binding it to the public IP only

*netsh show iplisten is empty (which should mean bind to all IPs)

*netstat -an shows IIS listening on 0.0.0.0:80

*I can telnet to localhost 80, but cannot telnet to xxx.xxx.xxx.xxx 80

*I can also telnet to hostname 80 where hostname resolves to an link-local IPv6 address

*I've checked the IP is correct (I'm RDPing to it)

*I've disabled the windows firewall

What could cause this?

A: Well, I didn't manage to figure it out so I just deployed a new server from scratch. Chock that one up to the strange books.

A: I had this issue and created the netsh listen to get it working.
C:\>netsh

netsh>http

add iplisten ipaddress=xxx.xxx.xxx.xxx

exit

A: Try binding new IP using the instruction given in "Add and Remove IP Address Bindings", which includes the steps to add new IP to your website in IIS.


text:
Q: TikZ/pgfplots: How to plot product of sine and piecewise linear function Problem description
I would basically like to recreate the following image in TikZ:
http://krashan.ppa.pl/articles/u1synth/adsr.png
This boils down to the question of how to multiply a sine wave with a piecewise linear function in TikZ/pgf.
Restrictions & freedoms

*

*Colors from original image do not need to be reproduced :)

*I'd like to solve this problem without having to store data in an external file

*I'm happy to use pgfplots and/or pgfmath
Minimal (non-)working example
I am getting a feeling that the appropriate mechanism to attack this problem in TikZ/pgf is its function declaration mechanism (but I'm not sure whether I'm right).
In the example below, I have implemented only the first part of the piecewise linear function, to try and multiply it with a sine function. However, when I do so, the entire plot disappears (comment out the line marked TODO in the example below to confirm).
\documentclass{article}

\usepackage{pgfplots}

% Declare (first part of) piecewise linear function
\pgfmathdeclarefunction{p}{1}{%
  \pgfmathparse{ ((x>=0) && (x<=50))*x/50 }
}

\begin{document}

\begin{tikzpicture}[domain=0:500]

  \begin{axis}

    % Plot piecewise linear function
    \addplot[thick, blue]{p(x)};

    % Plot sine function
    \addplot[red, samples=500, smooth]{sin(20*x)};

    % Plot product of both. TODO: Makes entire plot disappear
    %\addplot[thick, green, samples=500, smooth]{sin(30*x)*p(x)};

  \end{axis}

\end{tikzpicture}

\end{document}

Bonus ideas for implementation

*

*Signal max of piecewise linear function should always be +1

*x axis should represent milliseconds

*Total duration of envelope should be around 500ms, but:

*It would be nice if the following parameters could be set by the user:

*

*Total time T=A+D+S+R

*Attack time A

*Decay time D

*Release time R

*Sustain level L

*The sustain time S would be automatically derived as S = T-(A+D+R)

A: You can define a piecewise linear function by multiplying the pieces with the conditions that check for the interval and adding them. Then you just have to multiply the sine function with the piece-wise linear function.
What's the problem with your solution?
In fact, there is only a single character missing: Add a percent sign after the \pgfmathparse expression:
\pgfmathdeclarefunction{p}{1}{%
  \pgfmathparse{ ((x>=0) && (x<=50))*x/50 }% <<<<<<<<
}

Without it, a space will be added to the left of the plot for every call of the function, so the plots moves out of the page towards the right.

\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{calc}

\pgfmathdeclarefunction{ADSR}{1}{%
  \pgfmathparse
    {(                  #1<=\pA      )*(#1/\pA)                          +%
     (and(#1>\pA      , #1<=(\pA+\pD))*(#1*(-\pL)/\pD + 1 + \pA*\pL/\pD) +%
     (and(#1>(\pA+\pD), #1<=(\pT-\pR))*(1-\pL)                           +%
     (and(#1>(\pT-\pR), #1<=\pT      )*((1-\pL)/\pR*(-#1+\pT))
    }%
}

\begin{document}
\begin{tikzpicture}
\newcommand\pT{500} % total
\newcommand\pA{100} % attack
\newcommand\pD{100} % decay
\newcommand\pR{100} % release
\newcommand\pL{0.2} % sustain level
\newcommand\pF{50}  % frequency (not in Hz, but proportional)
  \begin{axis}[x=0.2mm,y=2cm]
    \addplot[domain=0:\pT, green, samples=5000] {ADSR(x)*sin(\pF*x)};
    \addplot[domain=0:\pT, red, samples=100] {ADSR(x)};
  \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: The following SQL code throws error     SELECT fp.Physician_Key,
       fp.Month,
       pd.DisplayName,
       hd.ProductName,
       SUM(AmtPaid) AS TotalCost
FROM F_ProgramCost_Fact fp
INNER JOIN D_HEALTHPLANDim hd ON hd.HealthPlan_Key = fp.HealthPlan_Key
INNER JOIN D_PHYSICIANDim pd ON fp.Physician_Key = fp.Physician_Key
INNER JOIN F_MemberPatient_FactLess mpf ON fp.MemberPatientFact_Key = mpf.MemberPatientFact_Key
GROUP BY fp.Physician_Key

Getting this error "Column 'F_ProgramCost_Fact.Month' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
Please help!
Thanks

A: you need to group by all the columns:
select fp.Physician_Key,fp.Month,pd.DisplayName,hd.ProductName,SUM(AmtPaid) as TotalCost
From F_ProgramCost_Fact fp
Inner Join D_HEALTHPLANDim hd
ON hd.HealthPlan_Key = fp.HealthPlan_Key
Inner join D_PHYSICIANDim pd
ON fp.Physician_Key = fp.Physician_Key
Inner Join F_MemberPatient_FactLess mpf ON fp.MemberPatientFact_Key = mpf.MemberPatientFact_Key
Group By fp.Physician_Key,fp.Month,pd.DisplayName,hd.ProductName


text:
Q: PHP GD Resizing Causes Artifacts I have a function that I'm using to accept user-uploaded images, proportionally scale it to a have a maximum width/height of 4,000px, and also generate 400px and 800px thumbnails. It needs to be capable of handling transparent PNGs and applying a white background.
My current code does all of this, however, it adds undesirable artifacts not typical of JPEGs. They're vertical striations and look like a very washed out barcode when viewed close up (400% Zoomed Screenshot attached). This even occurs on the original image when uploaded at the size it's being scaled to. It seems to be even more prevalent with transparent PNGs, but happens in white regions of JPEGs as well. JPEGs are being saved with Quality 80.

function resize_image($file, $w, $h, $strict = false, $crop = false, $path = null, $thumbnail = false)
{
    // Check for Valid Image + Calculate Ratio
    list($width, $height) = getimagesize($file);

    if (empty($width) || empty($height))
    {
        echo json_encode(['result' => 'error', 'error' => 'file_format_invalid']);
        http_response_code(405);
        exit;
    }

    $r = $width / $height;

    if (!$strict)
    {
        $w = min($w, $width);
        $h = min($h, $height);
    }

    $wTa = min($w, 400);
    $hTa = min($h, 400);

    $wTb = min($w, 800);
    $hTb = min($h, 800);

    // Apply Crop Constraint
    if ($crop)
    {
        if ($width > $height)
        {
            $width = ceil($width - ($width * abs($r - $w / $h)));
            $widthTa = ceil($width - ($width * abs($r - $wTa / $hTa)));
            $widthTb = ceil($width - ($width * abs($r - $wTb / $hTb)));
        }

        else
        {
            $height = ceil($height - ($height * abs($r - $w / $h)));
            $heightTa = ceil($height - ($height * abs($r - $wTa / $hTa)));
            $heightTb = ceil($height - ($height * abs($r - $wTa / $hTb)));
        }

        $newWidth = $w;
        $newHeight = $h;
    }

    else
    {
        if ($w / $h > $r || $r < 1)
        {
            $newWidth = $h * $r;
            $newWidthTa = $hTa * $r;
            $newWidthTb = $hTb * $r;

            $newHeight = $h;
            $newHeightTa = $hTa;
            $newHeightTb = $hTb;
        }

        else
        {
            $newHeight = $w / $r;
            $newHeightTa = $wTa / $r;
            $newHeightTb = $wTb / $r;

            $newWidth = $w;
            $newWidthTa = $wTa;
            $newWidthTb = $wTb;
        }
    }

    // Create, Resample + Return Image
    $src = imagecreatefromstring(file_get_contents($file));
    $dst = imagecreatetruecolor($newWidth, $newHeight);
    $fff = imagecolorallocate($dst, 255, 255, 255);

    imagefill($dst, 0, 0, $fff);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (!is_null($path))
    {
        imagejpeg($dst, $path, 80);

        if ($thumbnail)
        {
            $dstThumbA = imagecreatetruecolor($newWidthTa, $newHeightTa);
            $dstThumbB = imagecreatetruecolor($newWidthTb, $newHeightTb);

            $fffThumbA = imagecolorallocate($dstThumbA, 255, 255, 255);
            $fffThumbB = imagecolorallocate($dstThumbB, 255, 255, 255);

            imagefill($dstThumbA, 0, 0, $fffThumbA);
            imagefill($dstThumbB, 0, 0, $fffThumbB);

            imagecopyresampled($dstThumbA, $src, 0, 0, 0, 0, $newWidthTa, $newHeightTa, $width, $height);
            imagecopyresampled($dstThumbB, $src, 0, 0, 0, 0, $newWidthTb, $newHeightTb, $width, $height);

            imagejpeg($dstThumbA, str_replace('.jpg', '-thumb.jpg', $path), 80);
            imagejpeg($dstThumbB, str_replace('.jpg', '-thumb@2x.jpg', $path), 80);
        }
    }

    return $dst;
}

A: I concluded that the issue is specific to the environment (occurs on PHP 7.1.3 under Ubuntu, but not under PHP 7.0.1 on Windows). Reinstalling php7.1 and php7.1-gd had no effect.
Ultimately I decided to bite the bullet and rewrite with ImageMagick, resulting in a much more concise block of code:
$magickSource = new Imagick();
$magickSource->readImageBlob(file_get_contents($file));
$magickSource = $magickSource->flattenImages();

$magickFull = clone $magickSource;
$magickFull->resizeImage(min($originalWidth, $newWidth), min($originalHeight, $newHeight), Imagick::FILTER_LANCZOS, 1, true);
$magickFull->setImageCompression(Imagick::COMPRESSION_JPEG);
$magickFull->setImageCompressionQuality(75);
$magickFull->stripImage();
$magickFull->writeImage($path);
$magickFull->destroy();

if ($thumbnail)
{
    $magickThumb = clone $magickSource;
    $magickThumb->resizeImage(min($originalWidth, 400), min($originalHeight, 400), Imagick::FILTER_LANCZOS, 1, true);
    $magickThumb->setImageCompression(Imagick::COMPRESSION_JPEG);
    $magickThumb->setImageCompressionQuality(75);
    $magickThumb->stripImage();
    $magickThumb->writeImage(str_replace('.jpg', '-thumb.jpg', $path));
    $magickThumb->destroy();
}

The calls to setImageCompression(), setImageCompressionQuality, and stripImage() yielded a 53% reduction in combined filesizes. (Source)


text:
Q: BigQuery Schema error despite updating schema I'm trying to run multiple simultaneous jobs in order to load around 700K record to a single BigQuery table. My code (Java) creates the schema from the records of is job, and updates the BigQuery schema, if needed.
Workflow is as follows:

*

*A single job creates the table and sets the (initial) schema.

*For each load job we create the schema from the records of the job. Then we pull the existing table schema from BigQuery, and if it's not a superset of the schema associated with the job, we update the schema with the new merged schema. The last part (starting from pulling the existing schema) is synced (using a lock) - only one job performs it at a time. The update of the schema is using the UPDATE method, and the lock is released only after the client update method returns.

I was expecting to avoid encountering schema update errors using this workflow. I'm assuming that once the client returns from the update job, then the table is updated, and that jobs that are in process can't be hurt from the schema update.
Nevertheless, I still get schema update errors from time to time. Is the update method atomic? How do I know when a schema was actually updated?

A: Updates in BigQuery are atomic, but they are applied at the end of the job. When a job completes, it makes sure that the schemas are equivalent. If there was a schema update while the job was running, this check will fail.
We should probably make sure that the schemas are compatible instead of equivalent. If you do an append with a compatible schema (i.e. you have a subset of the table schema) that should succeed, but currently BigQuery doesn't allow this. I'll file a bug.


text:
Q: Add logo to bottom right corner of a plain frame which already has an image I have a plain beamer frame with an image in it. I also want to add a logo to the bottom right corner of the frame. How do I do it?
\begin{frame}[plain]
    \begin{figure}[h]
        \centering
        \includegraphics[width=0.4\linewidth]{images/someimage}
        \caption{Caption}
        \label{result:label}
    \end{figure}
\end{frame}

A: If you only want it on this frame, you can use tikz posisioning.
\documentclass{beamer}
\usepackage{tikz}

\begin{document}
\begin{frame}[plain]
    \begin{figure}[h]
        \centering
        \includegraphics[width=0.4\linewidth]{example-image-A}
        \caption{Caption}
        \label{result:label}
    \end{figure}
    \tikz[remember picture, overlay] {\node[anchor=south east, outer sep=0pt] at (current page.south east) {\includegraphics[width=2cm]{example-image-B}};}
\end{frame}
\end{document}


text:
Q: How to create register form that depends on fields checking in mvc4? I want to create a register form in mvc 4 application. So, when user registers, in that time I want to define user's status (he is programmer or not) and to show (or hide) dynamically some extra fields to fill depending on user's choice.
In default case, all fields seems, if user is not programmer (by unchecking checkbox field), to hide Language, Site and Probation fields. My register model is like this:
public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "*", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "*")]
        public string ConfirmPassword { get; set; }

        [Display(Name = "Profession")]
        public bool IsProgrammer { get; set; }

        [Required]
        [Display(Name = "Language")]
        public string Language { get; set; }

        [Required]
        [Display(Name = "Site")]
        public string Site { get; set; }

        [Required]
        [Display(Name = "Probation")]
        public string Probation { get; set; }
    }

If user is programmer, Language, Site and Probation fields are required, user must fill them.
How should I create Register model that, if user is not programmer, Language, Site and Probation fields not required and let to register ?
My second question is that, how show (hide) fields dynamically, when checkbox is checked (unchecked)?

A: Quick search on 'mvc asp.net conditional required field' gave me these few links:
Conditional Data Annotation
Using IValidatableObject
Flexible Conditional Data Annotation
These are more targeted towards server-side validation.
So to answer your questions:

*

*Check out the links, they will be helpful

*You can use jQuery to achieve that, learn more about jQuery Hide and Show


text:
Q: Vectorization with numpy I am trying to create a Gaussian blurred matrix. I am modifying code from http://www.labri.fr/perso/nrougier/teaching/numpy/numpy.html
dev_data has rows of 784 pixel features, and I would like to blur with the neighbors around the pixel in question along with the pixel itself. When we're along the outer edges (rows 1,-1, columns 1,-1), discard any out of bounds neighbors. I am not quite sure how to do this discarding.
Code:
# Initialize a new feature array with the same shape as the original data.
blurred_dev_data = np.zeros(dev_data.shape)

#we will reshape the 784 feature-long rows into 28x28 matrices
for i in range(dev_data.shape[0]):
    reshaped_dev_data = np.reshape(dev_data[i], (28,28))
    #the purpose of the reshape is to use the average of the 8 pixels + the pixel itself to blur
    for idx, pixel in enumerate(reshaped_dev_data):
        pixel = np.mean(reshaped_dev_data[idx-1:idx-1,idx-1:idx-1] + reshaped_dev_data[idx-1:idx-1,idx:idx] + reshaped_dev_data[idx-1:idx-1,idx+1:] +
             reshaped_dev_data[idx:idx,idx-1:idx-1] + reshaped_dev_data[idx:idx,idx:idx] + reshaped_dev_data[idx:idx,idx+1:] +
             reshaped_dev_data[idx+1:  ,idx-1:idx-1] + reshaped_dev_data[idx+1:  ,idx:idx] + reshaped_dev_data[idx+1:  ,idx+1:])
    blurred_dev_data[i,:] = reshaped_dev_data.ravel()

I get an error with the index:
ValueError: operands could not be broadcast together with shapes (0,0) (0,27)

It's not an indexerror, so I'm not quite sure what I'm doing wrong here/how to fix it.

A: Try this:
pixel = np.mean(reshaped_dev_data[idx-1:idx+1, idx-1:idx+1])

Also, read about slicing.

So I looked further at your code, and you're doing a few things wrong:

*

*This is not a Gaussian kernel.

*Recomputing reshaped_dev_data multiple times in a loop.

*Looping over the wrong things.

*Trying to mutate pixel on line 9. This is bad because:

*

*Mutation of the object you are looping over is generally bad

*That will not mutate anyways! pixel is like a "value" holder. Changing it does not change the array you are looping over.

*Not writing vectorized code!

Here's a naive, non-vectorized way of doing it:
def conv(arr, i, j):
    return np.mean(arr[i-1:i+1, j-1:j+1])

blurred_dev_data = np.zeros_like(dev_data)
reshaped_dev_data = dev_data.reshape(28, 28)

for i, row in enumerate(reshaped_dev_data):
    for j, pixel in enumerate(row):
        blurred_dev_data[i, j] = conv(reshaped_dev_data, i, j)

Notice that we're doing a convolution. So we could simply just use the built in libraries to perform a convolution on the averaging kernel.

Regarding your comments,
def conv(arr, i, j):
    # Ensure the boundaries are not exceeded
    a = max(i-1, 0)
    b = min(i+1, 28)
    c = min(j-1, 0)
    d = max(i+1, 28)

    return np.mean(arr[a:b, c:d])

blurred_dev_data = np.zeros_like(dev_data)

for n, data in enumerate(dev_data):
    reshaped = data.reshape(28, 28)
    blurred = np.zeros_like(reshaped)

    for i, row in enumerate(reshaped):
        for j, pixel in enumerate(row):
            blurred[i, j] = conv(reshaped, i, j)

    blurred_dev_data[n] = blurred.ravel()

Notice I modified conv because I'd forgotten to ensure boundaries were not exceeded.
Note: It is much, much faster to use existing libraries such as SciPy or OpenCV to perform the 2D convolution, or in this case, a mean averaging filter.


text:
Q: what is minimum number of parameters to be passed to a function while creatng a library function for matrix addition I'm creating a simple library function for basic matrix operations and one of it is matrix addition,as IMO the function seems to have too many parameters passed to it, but on the other hand i feel all the parameters passed are required and there is no other way to get them in the function directly.
so here's the code snippet :
  void mat_add(int r1, int c1, int m1[][c1], int r2, int c2, int m2[][c2],int res[][c1])
{
    if (r1 == r2 && c1 == c2)
    {
        for (int i = 0; i < r1; i++)
        {
            for (int j = 0; j < c1; j++)
            {
                res[i][j] = m1[i][j] + m2[i][j];
            }
        }
    }
    else
    {
        fprintf(stderr, "ERROR:matrix sizes are not same\n");
        exit(-1);
    }
}

Of course, its the real necessary parameters should be passed,
but I really dont know what i am doing is just too much,it can be reduced or not,
so is there any way you can reduce the number of parameters passed and get the required data(#rows and #columns) from those itself in the function?

A: The minimum number of parameters is 1. A struct or a pointer to a struct with all parameters that you need to perform an operation.


text:
Q: Resizing image on the fly This is my .htaccess. All is working fine. Except there is a problem with this part:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule pic/(.*)--(\d+)*.(jpe?g|JPE?G|gif|GIF|png|PNG)?$ index.php/image/getinsize/?p=pic/$1\.$3&s=$2 [QSL,NS,L]

This creates resized image on the fly for example from:
/pic/posts/2015-12/43242/gals/picture.jpg
and stores it as:
/pic/posts/2015-12/43242/gals/picture--900.jpg
Image is saved on hdd and served by Apache. Problem is when next time the same image is requested, instead of serving already resized image, server is resizing and overiding it. Any idea why the !-f doesn't work?
Options +FollowSymLinks

RewriteEngine on

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule static\/([^/]+)\/([^/]+)$ static/$1/$2 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule static/help/bg\/(.*)\/?$ /static/help/bg/item.php?l=$1 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (lng_[^/]+)\/([^/]+)\/([^/]+)\/?$ /index.php/$2/$3?lng=$1 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule news\/([0-9]+)\/([^/]+)\/([0-9]+)\/?$ /index.php/posts/post/?id=$1&pagenum=$3 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule news\/([0-9]+)\/([^/]+)\/?$ /index.php/posts/post/?id=$1 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule polls\/([0-9]+)\/([^/]+)\/?$ /index.php/polls/poll/?id=$1 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule pic/(.*)--(\d+)*.(jpe?g|JPE?G|gif|GIF|png|PNG)?$ index.php/image/getinsize/?p=pic/$1\.$3&s=$2 [QSL,NS,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule pic\/(.*)--(pdf)(\d+)*\.(jpe?g|JPE?G|gif|GIF|png|PNG)?$ /index.php/image/getinsizefrompdf/?p=pic/$1\.$4&s=$3&f=$2 [QSD,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ([^/]+)\/([^/]+)\/([^/]+)\/?$ /index.php/$1/$2/$3 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (lng_[^/]+)\/([^/]+)\/([^/]+)\/([^/]+)\/?$ /index.php/$2/$3/$4?lng=$1 [QSA,L]

RewriteRule ^feed/?$ /index.php/index/rss [QSA,L]

RewriteRule ^sitemap\.xml$ /index.php/index/sitemapxml [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ([^/]+)\/([0-9]+)\/?$ /index.php/pages/page/?url=$1&pagenum=$2 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ([^/]+)\/([^/]+)\/?$ /index.php/pages/page/?lang=$1&url=$2 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ([^/]+)\/([^/]+)\/?$ /index.php/$1/$2 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ([^/]+)\/?$ /index.php/pages/page/?url=$1 [QSA,L]


text:
Q: github push -> redmine issue duplicate comments I've successfully connected github to redmine and whenever someone puts an issue reference in a commit message and pushes it to github, a comment is added to the redmine issue referring back to the git commit.  This is all fine and well, except that I end up with duplicates.  I'm not sure what causes the duplicate, but I think it's when the commit is part of a non-fast-forward merge.
What can I do to prevent the duplicates?  I had a look at the github hook to understand how it was getting a list of git commits, but couldn't follow it.

A: Do you have multiple branches in your repo?
Each time a commit is merged into a another branch, github will trigger the hook and write another comment to Redmine.


text:
Q: AngulagJS MVC Web API 2 Login I want to create a login page where im not using the aspnetusers table but my member table.
How can I create my own token, authorization/authentication?
So far this is my code:
web api 2 controller for api call and
signin controller js
"use strict";

app.controller('MemberSignInController', MemberSignInController);

MemberSignInController.$inject = ['$scope', '$http', '$location', '$routeParams', 'toaster', '$rootScope', 'DataServiceFactory']

function MemberSignInController($scope, $http, $location, $routeParams, toaster, $rootScope, DataServiceFactory) {

    var vm = this;

    vm.member = {};

    vm.signIn = function () {
        vm.showMessage = false;

        var params = {
            cardNumber: vm.member.username,
            password: vm.member.password
        };

        $http.post('api/member/login', params).then(
            function (response) {
                $rootScope.loggedIn = true;
                DataServiceFactory.Id = response.data.memberId;
                window.location = '#!/profile';
            },
            function (response) {
                toaster.pop('error', "Sign In Failed", response.data, 5000);
                $rootScope.loggedIn = false;
                window.location = '#!/signIn';
            }
        );

    }
}

so far this is my code yet and its working but when i refresh my page, the login userdata is clear, i have to logout to login again to be able to see the data.
Please help me, thanks!!

A: Your login userdata is cleared on refresh because it is not stored anywhere.
Since you are using AngularJS with Webapi, you need to understand your calls are sessionless.
You have to use cookies to store data after successful login, and on refresh you need to check if data is available on cookie.
If data is available in cookie, keep the session or redirect to login page.
On logout, clear the cookies.