text:
Q: How to insert a character in a list, based on the consecutive appearance of two elements from another list? Python I have a DataFrame with a lot of strings and a function that inserts a character in a string, according to a condition. The problem is that my code somehow sees the input string s wrongly.
The list s consists of elements from two lists: (1) member list (2) non-member list. My goal is to insert the number '1' into s when any 'member' is followed by any two consequtive 'non-members'. A maximum of one '1' should be added to s. This is the code.
import pandas as pd
members = ['AA', 'BBB', 'CC', 'DDDD']
non_members = ['EEEE', 'FF', 'GGG', 'HHHHH', 'III', 'JJ']
s = ['AA', 'EEEE', 'GGG', 'FF']

So the result I am trying to achieve for s is to get the following output:
['AA', '1', 'EEEE', 'GGG', 'FF']

This is my code:
df = pd.DataFrame(s, columns =['string'])
d = df['string']

def func(row):
    out = ""
    look = 2
    for i in range(len(row)-look):
        out += row[i]
        if (row[i] in members) & \
           (row[i+1] in non_members) & \
           (row[i+2] in non_members):
            out += '1' + row[i+1:]
            break
    return out

e = d.apply(func)
print(e)

This gives the following result:
0
1    EE
2     G
3

But what I hope to get is this:
['AA', '1', 'EEEE', 'GGG', 'FF']

Any suggestions how to solve this?
This question is related to this one: How to add a character to a list if two items from another list appear consecutively? Python

A: You can use shift to figure out where that condition is met.
mask = ((df['string'].isin(members))
         & (df['string'].shift(-1).isin(non_members))
         & (df['string'].shift(-2).isin(non_members)))

One way to insert in the rows in between might be to do something like this.
import numpy as np
df.set_index(df.index*2, inplace=True)

indices = mask[mask==True].index.values+1

df_add = pd.DataFrame(data=np.repeat(1, len(indices)), index=indices, columns=['string'])

pd.concat([df, df_add]).sort_index()
  string
0     AA
1      1
2   EEEE
4    GGG
6     FF

A: @ALollz code looks cleaner beacsue they use mask and isin but yeah shift is definitely the idea.
import pandas as pd

import sys

def fun(row):
    members = ['AA', 'BBB', 'CC', 'DDDD']
    non_members = ['EEEE', 'FF', 'GGG', 'HHHHH', 'III', 'JJ']
    try:
        if (row["string"] in members):
            if(row["next"] in non_members):
                if(row["nextnext"] in non_members):
                    return(1)
        return(0)
    except:
        e = sys.exc_info()[0]
        print(e)
        print("!")
        return(0)
    return(0)

def insert_row(idx, df, df_insert):
    dfA = df.iloc[:idx, ]
    dfB = df.iloc[idx:, ]
    df = dfA.append(df_insert).append(dfB).reset_index(drop = True)
    return df

def primary(d):
    df = d.copy()
    a = d.shift(-1)
    b = d.shift(-2)
    df['next'] = a
    df['nextnext'] = b
    e = df.apply(fun,axis=1)
    x = 0
    while( x<len(e) and e[x]==0 ):
        x+=1
    if(x!=len(e)):
        d = insert_row(x+1,d,pd.DataFrame(["1"], columns=["string"]))
    return(d)

s = ['AA', 'EEEE', 'GGG', 'FF']

df = pd.DataFrame(s, columns =['string'])
print(primary(df))

A: I like the answer of ALollz, but prefer a more visual approach. Here's an example that requires two inserts.
import pandas as pd
import numpy as np
members = ['AA', 'BBB', 'CC', 'DDDD']
non_members = ['EEEE', 'FF', 'GGG', 'HHHHH', 'III', 'JJ']
s = ['AA', 'EEEE', 'GGG', 'CC', 'III', 'JJ']
ser = pd.Series(s)
# view the multiple "frames" from the list in a dataframe
df = pd.DataFrame([ser, ser, ser.shift(-1), ser.shift(-2)],
index=["orig","s", "s+1", "s+2"]).T

   orig     s   s+1  s+2
0    AA    AA  EEEE  GGG
1  EEEE  EEEE   GGG   CC
2   GGG   GGG    CC  III
3    CC    CC   III   JJ
4   III   III    JJ  NaN
5    JJ    JJ   NaN  NaN

Similar to the mask approach, create a column showing whether the conditions are fulfilled.
df["s"] = df["s"].isin(members)
df["s+1"] = df["s+1"].isin(non_members)
df["s+2"] = df["s+2"].isin(non_members)
df["fulfilled"] = df.all(axis=1)

   orig      s    s+1    s+2  fulfilled
0    AA   True   True   True       True
1  EEEE  False   True  False      False
2   GGG  False  False   True      False
3    CC   True   True   True       True
4   III  False   True  False      False
5    JJ  False  False  False      False

get the index of the "1" positions to be inserted into the final s_out list. This is simply the orig index plus the index in only "True" positions
index = df.loc[df.fulfilled].index
df.loc[index, "index in s_out"] = index + np.arange(1, len(index) + 1)

   orig      s    s+1    s+2  fulfilled  index in s_out
0    AA   True   True   True       True             1.0
1  EEEE  False   True  False      False             NaN
2   GGG  False  False   True      False             NaN
3    CC   True   True   True       True             5.0
4   III  False   True  False      False             NaN
5    JJ  False  False  False      False             NaN

Insert the "1" into the s_out list at the required positions.
s_out = s.copy()
for i in df["index in s_out"].dropna().astype(int):
    s_out.insert(i, "1")
s_out

['AA', '1', 'EEEE', 'GGG', 'CC', '1', 'III', 'JJ']


text:
Q: SQL for Oracle command MYSQL:
SELECT * FROM book ORDER BY $sidx $sord LIMIT $start , $limit;

How do I turn this into Oracle?

A: You have to use rownum property, BUT you have to apply it to the result set already ordered AND you need to pass it from the inner query (credit to Bob Jarvis and Daniel Hilgarth: check their explanations and links given in comments as well). It should be something like this:
SELECT * FROM
(SELECT b.*, rownum as row_num FROM book b ORDER by $sidx $sord)
WHERE row_num BETWEEN $start AND $start + $limit;

A: I am not familiar with the oracle syntax, but you can use the ROW_NUMBER() function to rank the rows then select those with rank BETWEEN @start and @limit:
   SELECT *
   FROM
   (
       select *,
           ROW_NUMBER() OVER (ORDER BY ID DESC) AS rank
       FROM book
   )
   WHERE rank BETWEEN @start AND @end
   /* OR
   WHERE BETWEEN ((@PageNum - 1) * @PageSize + 1)
     AND (@PageNum * @PageSize)
   /*

A: select * from(
select rownum as row_num, id from t
  )
where row_num between :start and :start+:limit

A: 10g Onwards
WITH CTE AS(SELECT  b.*, Row_Number() OVER(ORDER BY SIDX,SORD) AS Rn FROM BOOK b)
SELECT *
FROM CTE
WHERE Rn BETWEEN STARTLIMIT AND ENDLIMIT

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dejar de pedir numero tras introducir un 0 (do-while) C Introducir 0 y que deje de preguntar por introducir numeros
    do{
       for(i=0; i<DIM; i++){
        printf("Introduzca un numero para el vector[%d]: ", i);
        fflush(stdin);
        scanf("%d", &vector[i]);
        }
      }while((vector[i]!=0) && (i<DIM));
    }

A: debería eliminar el for.
    int i=-1;

    do {
        i++;
        printf("Introduzca un numero para el vector[%d]: ", i);
        fflush(stdin);
        scanf("%d", &vector[i]);
    } while ((vector[i]!=0) && (i<DIM));


text:
Q: Colocar Fecha Actual en un datetimepicker al Inicializar un Formulario Los pongo en contexto. lo que quiero hacer es que al abrir un formulario hijo ya me aparezca la fecha actual en un Datetimepicker... ya que con ello hago una consulta a la base de datos para ver los pendientes del día.
Por ahora, lo que hago es declarar una variable de tipo Datetime y mandarcela al método para mostrar la consulta, pero al pasarle esa variable a mi Datetimepicker no le pasa nada… y me marca error…
el error que me marca es el siguiente:

'No se puede reconocer la cadena como valor DateTime válido.'

Me sale ya que no lleva ningun dato, como que la variable que declare no le paso los datos al datetimepicker...
Espero puedan ayudarme.
public partial class Polizacancelada : Form
{
    public Polizacancelada()
    {
        DateTime date = DateTime.Now;
        InitializeComponent();
        Pendientes(date);
        fechadependientes.Text = Convert.ToString(date.ToString("dd/MM/yyyy"));
    }
}

Avances y Pruebas:
public Polizacancelada()
    {
        DateTime date = DateTime.Now;
        InitializeComponent();
        Pendientes(date);

        fechadependientes.Format = DateTimePickerFormat.Custom;
        //Le indicas tu formato
        fechadependientes.CustomFormat = "dd/MM/yyyy";
        //Aqui bastara pasar el date a ToString()
        fechadependientes.Text = date.ToString();
    }

Al hacerlo de esta otra manera:
public Polizacancelada()
    {
        DateTime date = DateTime.Now;
        InitializeComponent();
        Pendientes(date);

        fechadependientes.Value = DateTime.Now;
    }

me sale el mismo error con las dos formas...
El metodo al que le mando el Datetime es el siguiente:
private void Pendientes(DateTime df)
    {
        try
        {
            SqlDataAdapter DA = new SqlDataAdapter("Select * from CANCELACIONES where Listo='PEN' and FechadeIngreso='"+df.ToString("yyyyMMdd")+"'", MenuInicio.conexion);
            DataTable DT = new DataTable();
            DA.Fill(DT);
            mostrarpendientes.DataSource = DT;
            if(mostrarpendientes.Rows.Count==0)
            {
                CancelarPendientes.Visible = false;
                mostrarpendientes.Visible = false;
                label5.Visible = true;
            }
            else
            {
                CancelarPendientes.Visible = true;
                label5.Visible = false;
                this.mostrarpendientes.Columns["NumCancelacion"].Visible = false;
                this.mostrarpendientes.Columns["NumPoliza"].Visible = false;
                foreach (DataGridViewRow row in mostrarpendientes.Rows)
                {
                    String Dato= row.Cells["Listo"].Value.ToString();
                    if (Dato=="OK")
                    {
                        row.DefaultCellStyle.BackColor = Color.Green;
                        row.DefaultCellStyle.ForeColor = Color.White;
                    }
                    else
                    {
                        row.DefaultCellStyle.BackColor = Color.White;
                        row.DefaultCellStyle.ForeColor = Color.Black;
                    }
                }
                mostrarpendientes.Visible = true;
            }
        }
        catch (SqlException ex)
        {
            MessageBox.Show("ERROR: " + ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

A: Si deseas poner formato el dateTimePicker puedes utilizar la propiedad Format del picker, y indicarle que lo quieres personalizar
 InitializeComponent();
 //Le dices que tome tu formato
 dateTimePicker1.Format = DateTimePickerFormat.Custom;
 //Le indicas tu formato
 dateTimePicker1.CustomFormat = "dd/MM/yyyy";
 Pendientes(date);
 //Aqui bastara pasar el date a ToString()
 dateTimePicker1.Text = date.ToString();

A: Asi de sencillo:
  dateTimePicker1.Value = DateTime.Now;

A: La linea siguiente, en el código private void Pendientes(DateTime df)parece tener un error:
SqlDataAdapter DA = new SqlDataAdapter("Select * from CANCELACIONES where Listo='PEN' and FechadeIngreso='"+df.ToString("yyyyMMdd")+"'", MenuInicio.conexion);

La conversión parece estar indicada de manera incorrecta:
df.ToString("yyyyMMdd")

Pienso que deberia ser
df.ToString("yyyy/MM/dd")

Quedando la linea completa de la siguiente forma.
  SqlDataAdapter DA = new SqlDataAdapter("Select * from CANCELACIONES where Listo='PEN' and FechadeIngreso='"+df.ToString("yyyy/MM/dd")+"'", MenuInicio.conexion);

No soy entendido en Sql pero pienso que ahí puede haber un error, prueba con este cambio y si resulta me notificas.

REVISANDO LA RESPUESTA ANTERIOR.
Revisando con mas detalle tu captura de pantalla, es evidente que tu error es lanzado antes del punto en que te señale la corrección anterior, cuando al llamar al procedimiento Pendientes y al pasarle como parámetro la conversión que realizas Conver.ToDateTime(fechadependientes.Text.ToString()). Hay aquí varias conversiones que me parecen innecesarias, fechadependientes.Text es un string por tanto la conversión fechadependientes.Text.ToString() no es necesaria, pero además el argumento del procedimiento Pendientes es de tipo DateTime si fechadependientes es el control DateTimePicker no es necesario hacer referencia a la propiedad fechadependientes.Text, pues el control DateTimePicker da como salida la propiedad Value que es de tipo DateTime, no es necesario obtener un string para entonces convertirlo a DateTime si ya en el DateTimePicker tienes ese valor sin necesidad de convertirlo, bastaria con hacer la llamada de la siguiente forma.
private void fechadependientes_ValueChanged(object sender, EventArgs e)
{
    Pendientes(fechadependientes.Value);
}

Estos aspectos que te señalo son cosas elementales, no tienen discusión; solo que en tu pregunta hay un error de redacción que viola los requisitos adoptados como practica en este sitio y es que las cuestiones de error en código, no deben mostrarse en imágenes, si no en código escrito (en texto), todos los que han respondido a tú pregunta se han centrado en el código que colocaste, sin embrago el error es lanzado en un procedimiento de tu código que solo aparece en la captura de pantalla.
Te recomiendo hacer el cambio que te indiqué, Pendientes(fechadependientes.Value); pero no pierdas de vista, lo que te había dicho anteriormente, pues cuando resuelvas ese error es posible que te salte error en el procedimiento Pendientes


text:
Q: jquery - Change IMG src on rollover I've the following code: (a fiddle is here)

> Anniversary

> Birthday

> Christmas

> Wedding

and I'm attempting to change the src attribute of the image based on the rel value of the anchor.
I'm trying this jquery -
$("ul.rollover_list li a").hover(function() {
            var $link = $(this).attr('rel');
            var $target = $(this).closest('img.changeable');
            $($target).attr('src', $link);
        });

as I need to use it multiple times on a page.
Am I right in thinking that .closest() will locate the nearest matching element by traversing up the DOM?
Don't know what I'm missing but it ain't happy.

A: That line that appears as...
$($target).attr('src', $link);

should probably be...
$target.attr('src', $link);

A: You have 2 problems in your jQuery:

*

*jQuery's closest() method only works in trees, in other words: it will only work if the wanted result is a parent of the current element.

*$($target). $target is already an element, you can't select an element using an element as a selector, for that you'd need a method like find however, this isn't what you were trying to do.

http://jsfiddle.net/U7SNz/2/


text:
Q: Show Bootstrap modal on page load after scrolled percentage only once I have this almost working but seem to be missing some logic. I want the bootstrap modal to appear when someone gets 70% down the page when scrolling. It works, but when I close the modal it opens right back up again since I am still at 70% on the page. Any idea how to only make the modal open once after I close it?
$(document).scroll(function(e){
  var scrollAmount = $(window).scrollTop();
  var documentHeight = $(document).height();
  var scrollPercent = (scrollAmount / documentHeight) * 100;

  if(scrollPercent > 70) {
      // Popup in view after 70% scroll
     firePopup();
  }

  function firePopup() {
    $('#myModal').modal('show');
  }

  function reposition() {
      var modal = $(this),
      dialog = modal.find('.modal-dialog');
      modal.css('display', 'block');
      dialog.css("margin-top", Math.max(0, ($(window).height() - dialog.height()) / 2));
  }
  $('.modal').on('show.bs.modal', reposition);
  $(window).on('resize', function() {
      $('.modal:visible').each(reposition);
  });
});

A: add a class to modal once it is displayed and if class exists then dont show it again.
function firePopup() {
  if(!$('#myModal').hasClass('displayedOnce')){
      $('#myModal').modal('show');
      $('#myModal').addClass('displayedOnce');
  }

  }

A: You could create a global variable modalOpened and set it to false, and set it true when modal opened. Then you could check modalOpened and only show modal if it's false. Something like this.

var modalOpened = false;
$(document).scroll(function(e){
  var scrollAmount = $(window).scrollTop();
  var documentHeight = $(document).height();
  var scrollPercent = (scrollAmount / documentHeight) * 100;
  if(scrollPercent > 70) {
      // Popup in view after 70% scroll
   if(!modalOpened){
    firePopup();
   }
  }

  function firePopup() {
    $('#myModal').modal('show');
 modalOpened = true;
  }

  function reposition() {
      var modal = $(this),
      dialog = modal.find('.modal-dialog');
      modal.css('display', 'block');
      dialog.css("margin-top", Math.max(0, ($(window).height() - dialog.height()) / 2));
  }
  $('.modal').on('show.bs.modal', reposition);
  $(window).on('resize', function() {
      $('.modal:visible').each(reposition);
  });
});
.app{
 background: gold;
 width: 100vw;
 height: 100vh;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Bootstrap Modal</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias illo doloremque voluptate numquam corporis exercitationem, nemo voluptatibus fuga magni labore voluptas et porro necessitatibus nulla accusantium omnis vitae perspiciatis. Maiores veniam excepturi praesentium cum aliquid ratione tempora blanditiis repudiandae dolorum distinctio quo ad facere, est similique. Distinctio odit debitis quae aliquid commodi aperiam, asperiores aut, adipisci sunt quod cum placeat nemo facere iusto, laudantium earum quis quasi atque rerum. Dolorem porro reprehenderit, repellendus obcaecati a sapiente deserunt eligendi, reiciendis incidunt atque officiis animi aliquam esse cumque rerum debitis dignissimos veritatis, non ullam earum hic maiores neque magni at! Sapiente nostrum debitis atque repellat porro earum ipsum et, nobis iure, autem amet tempore doloremque dignissimos, asperiores ullam quo aliquid repellendus ea obcaecati eos voluptatem deleniti optio! Architecto cum a dolor aliquam nam ex illo ipsum dolorem expedita, fugiat! Non, dolores totam aliquam fugiat et nobis. Ab illo, pariatur adipisci mollitia cum? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil pariatur quas commodi aspernatur sequi minus adipisci quam eveniet labore aut molestiae dolores corporis numquam, dolore consequuntur unde laudantium sed illo facere rerum tenetur, fuga! Error nam ipsa, facilis enim porro at! Non, officiis, omnis. Sed quia quam, deleniti nostrum officia consectetur. Quam nemo incidunt magnam ut aspernatur obcaecati non tenetur quidem inventore, asperiores quaerat. Saepe amet temporibus, reiciendis deserunt, repellendus eum accusantium iure. Incidunt enim nisi quae rerum maiores iste reiciendis, voluptates culpa in maxime numquam tenetur rem, tempora cumque expedita praesentium eum dolor! Rerum nemo magni doloribus, voluptatem quisquam impedit tempora, repudiandae architecto perspiciatis quo at aliquid dolor voluptate voluptates, numquam recusandae quasi asperiores soluta deserunt adipisci eius provident quidem odio. Sit aperiam impedit voluptatem ipsum incidunt consequatur pariatur, similique natus enim, officiis officia dolor voluptatum! Rerum reiciendis, illo commodi ea corporis distinctio necessitatibus quidem! Quidem qui autem, consequuntur tempora praesentium saepe officia ipsam harum iure doloribus cumque culpa ipsa, ad accusamus aliquid pariatur animi! Animi accusantium id, ad consequuntur illo, porro similique quisquam, fugit harum dolore quasi facilis impedit tenetur quibusdam placeat et doloribus excepturi perspiciatis hic labore ex doloremque? Nam, voluptas, aspernatur. Quia temporibus odit, reiciendis fugit.

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

Modal title

        ...

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

Note, this will not persist once browser reloaded, if you want to display it once every day or week or something like this, you have to use cookies or localStorage.


text:
Q: Loop to insert row AND then select first cell of that row in VBA I have a column with a list of either 't/n' or 's/n' which have been sorted. I also have a script that will loop through each cell, checking for when 't/n' switches to 's/n' (t/n is always sorted first), and then inserts three blank rows.
The issue is, after the rows have been inserted, I want to select the cell just above the newly separated (thanks to new rows) 's/n' data - this is because I'll then call another script that will pull in a list of headers (that will sit above the 's/n' data)
So far I have:
Sub modTestTemplate()

Dim rngTestTemplate As Range
Set rngTestTemplate = Range("B2").End(xlDown).Offset(4, 0)
rngTestTemplate.Select

Dim LastRow As Integer
Dim CurrentRow As Integer
LastRow = rngTestTemplate.End(xlDown).Row
CurrentRow = 1

Do While CurrentRow <= LastRow

    If Range("B" & CurrentRow).Value = "s/n" Then
        Range("B" & CurrentRow).EntireRow.Resize(3).Insert xlUp
        LastRow = LastRow + 1
        CurrentRow = CurrentRow + 1
        Exit Do
    End If

    CurrentRow = CurrentRow + 1 ' this sets the cell back to the start for the loop

Loop

'when the loop is done I'm wanting to select the cell just above 's/n' as the data needs headers

End Sub

A: Range("B" & CurrentRow).Select does the job - as pointed out by SJR.


text:
Q: Missing Cast error from Visual studio When Load Data from MySql to Data Grid Table I have mobile app project using Xamarin. Forums with MySql.
I have page AboutPage.xaml :
<?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:d="http://xamarin.com/schemas/2014/forms/design"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 mc:Ignorable="d"
                 x:Class="MyExpect.Views.AboutPage"
                 xmlns:vm="clr-namespace:MyExpect.ViewModels"
                 Title="{Binding Title}"
                 xmlns:dg="clr-namespace:Xamarin.Forms.DataGrid;assembly=Xamarin.Forms.DataGrid"
                 xmlns:conv="clr-namespace:DataGridSample.Views.Converters;assembly=DataGridSample">
        <ContentPage.BindingContext>
            <vm:AboutViewModel />
        </ContentPage.BindingContext>

        <ContentPage.Content>
            <dg:DataGrid x:Name="datagirdtable">
            </dg:DataGrid>
        </ContentPage.Content>
    </ContentPage>

and AboutPage.cs :
using System;
using System.ComponentModel;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace MyExpect.Views
{

    public partial class AboutPage : ContentPage
    {
        Connections matchs = new Connections();
        public AboutPage()

        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);
            FillGirdView();
        }
        void FillGirdView() {
            datagirdtable.ItemsSource = matchs.ShowData();
        }
    }
}

and Connection Class :
using System;
    using System.Collections.Generic;
    using System.Text;
    using MySql.Data.MySqlClient;
    using System.Data;
    namespace MyExpect
    {
        class Connections
        {
            MySqlConnection connect = new
            MySqlConnection("Server=localhost;Database=myexpect;uid=root;pwd=;");
            public DataTable ShowData() {
                DataTable dt = new DataTable();
                MySqlDataAdapter da = new MySqlDataAdapter("select * from matchs", connect);
                da.Fill(dt);
                return dt;
            }
        }
    }

I am trying to view Table Data on Gird Data Table ,but i receive this message :
CS0266 C# Cannot implicitly convert type 'System.Data.DataTable' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)

A: @Jason
I made these changes to get data from server ,I convert the table to json encode page then i made a model :-
using System;
using System.Collections.Generic;
using System.Text;

namespace NewMyExpect.Models
{
    class matchs
    {

        public string m_id { get; set; }
        public string S_id { get; set; }
        public string Weak { get; set; }
        public string League { get; set; }
        public string home { get; set; }
        public string away { get; set; }
        public string m_date { get; set; }
        public string homere { get; set; }
        public string awayre { get; set; }
        public string m_daytime { get; set; }
        public string m_time { get; set; }
        public string m_day { get; set; }

    }
}

and made list in the page which show table data :-
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="NewMyExpect.Views.AboutPage"
             Title="{Binding Title}">

    <ListView x:Name="MatchListView">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal">

                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</ContentPage>

then make HttpClient in C# :
using System;
using System.ComponentModel;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using Newtonsoft.Json;

namespace NewMyExpect.Views
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class AboutPage : ContentPage
    {
        public AboutPage()
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);

            GetMatchs();
        }

        private async void GetMatchs()
        {
            HttpClient MyMatchs = new HttpClient();
            var responsematchs = await MyMatchs.GetStringAsync("https://technosat-iq.com/myexpect/activegames.php");
            var matchs = JsonConvert.DeserializeObject<List<Models.matchs>>(responsematchs);
            MatchListView.ItemsSource = matchs;
        }
    }
}

and this is the result :-


text:
Q: String comparison using Excel ODBC driver The following SQL query gives this error :

"[Microsoft][ODBC Excel Driver] Too few parameters. Expected 1."

Dim adoRS As New ADODB.Recordset

adoRS.Open "SELECT CStr(BOX) AS 'STRBOX',SLOT FROM [BIOSAMPLES$] WHERE STRBOX = '" & CStr(nBoxID) & "'" & " ORDER BY SLOT", adoConn

What is wrong?

A: Ok, I've found a workaround to this stupid Excel problem. This is my solution:
Dim adoRS As New ADODB.Recordset

adoRS.Open "SELECT BOX,SLOT FROM [BIOSAMPLES$] WHERE CStr('B' & BOX) = 'B" & CStr(nBoxID) & "'" & " ORDER BY SLOT", adoConn

Cheers.-


text:
Q: Passing Variable Values of WooCommerce using Pixel Code I have been requested by a Marketing company to place a Pixel Code in my WooCommerece checkout page to track conversions and generate reports.
Pixel Code:
<!-- Offer Goal Conversion: Cameras -->

It's required to replace AMOUNT with the sale amount of my cart and replace SUB_ID with the unique value (Like Order Number/id).
I tried replacing both values with several variables and values Like order_id, $order_id, $subtotal, subtotal but it doesn't seem to read and pass any data to the conversion report.
I need help to identify the correct WooCommerce variables for Cart Subtotal and Order Number that will read and pass data to the conversion report.
My Website is www.Trenddr.com
Thank You.

A: for subtotal:
1) With global $woocommerce; variable:
global $woocommerce;
$woocommerce->cart->subtotal;

// or
$woocommerce->cart->get_cart_subtotal()

2) Without global $woocommerce; variable:
WC()->cart->subtotal

// Or
WC()->cart->get_cart_subtotal()

for the order id:
global $woocommerce, $post;

$order = new WC_Order($post->ID);

//to escape # from order id

$order_id = trim(str_replace('#', '', $order->get_order_number()));


text:
Q: Visual Studio Bower error I'm going through some ASP.NET tutorials and I've encountered an error I don't know how to resolve. I just added a Bower pacakge(?) and Visual Studio (Enterprise 2015) placed it under a Dependencies branch. Under that is the Bower branch and in that the package appears. Both Dependencies and Bower say "- not installed" after them. I've right-clicked and selected the "Restore" option. Viusal Studio works for a while and then says an error occured. The following error appears in the Output window:
PATH=.\node_modules\.bin;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External\git
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External\Bower.cmd" install --force-latest
bower underscore#~1.83      not-cached git://github.com/jashkenas/underscore.git#~1.83
bower underscore#~1.83         resolve git://github.com/jashkenas/underscore.git#~1.83
bower underscore#~1.83         ECMDERR Failed to execute "git ls-remote --tags --heads git://github.com/jashkenas/underscore.git", exit code of #-532462766

I'm not terribly familiar with Git, but I know I shouldn't have to have it installed in my workstation. Anyone know what's going on?

A: I believe bower uses Git client to pull packages directly from GitHub using entries in the packages bower.json file.
Specific to your problem, Git (and therefore bower) is unable to connect to GitHub due to firewall issues. Similar issue here
You can set global git variables (e.g. git config --global xxx) to set proxy etc. to hopefully work around this problem.
According to the error your Git Client is installed locally at C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External\git


text:
Q: How to apply styles to TabPane in new Antd Tabs component This is my old implementation of the Tabs component in Ant Design.
const tabList = [
  {
    key: "tab1",
    label: "Tab1",
    children: <Tab1 />,
  },
  {
    key: "tab2",
    label: "Tab2",
    children: <Tab2 />,
  },
];

<Tabs onChange={onTabChange} activeKey={selectedTab}>
  {tabList.map((tab) => {
    const { key, label, children } = tab;
    return (
      <Tabs.TabPane
        key={key}
        tab={label}
        style={{ margin: "1.5rem auto 1.5rem" }}
      >
        {children}
      </Tabs.TabPane>
    );
  })}
</Tabs>;

In the new version ( > 4.23.0 ) the boilerplate got reduced.
I can simply pass my tabList to my Tabs as a prop items.
The new code looks something like this.
<Tabs items={tabList} />

But I had an issue with styling.
I am adding top and bottom margins to all of my TabPane components.
To get that margin in the new implementation. I had to do something like this.
  {
    key: "tab1",
    label: "Tab1",
    children: <Tab1 style={{margin: "1.5rem 0 1.5rem"}} />,
  },

Here I am facing two issues.

*

*I need to add this for all my tabs in the tabList

*I need to have a div in every component spreading the props that are passed above.

function Tab1(props) {
  return
JSX for original Tab1
;
}

Is there a better way to do this?

A: Higher order component can solve this issue
Use a higher Order component like <TabPaneWrapper> or <TabChildrenWrapper>. This component does nothing but to wrap your children (<TabPane>) with a div and give the styles you require.
Component:
export function TabPaneWrapper({
  children,
  ...props
}){

  return (

      {children}

  );
}

Usage:
const tabList = [
  {
    key: "tab1",
    label: "Tab1",
    children: <TabPaneWrapper> <Tab1 /> </TabPaneWrapper>,
  },
  {
    key: "tab2",
    label: "Tab2",
    children: <TabPaneWrapper> <Tab2 /> </TabPaneWrapper>,
  },
];

If you have more tabs or use this tabs component in multiple places. You will find TabPaneWrapper to be repetitive. In such case,

*

*You can create a custom Tabs component like <CustomTabs/> which takes the tabList mentioned in the question.

*Instead of wrapping every tab in the tabList with <TabPaneWrapper/>. You can loop this list inside the <CustomTabs/> component to generate the tabList mentioned above and then pass it to the Ant Desing <Tabs/> component.


text:
Q: Postgresql restore with compressed dump file I took a postgresql DB Bacup with the below command
pg_dump -Z6 -h localhost test_db -f test_db.tar -p port
Now If I try to restore it with psql facinf the below error:
psql:test_db.sql:117359: error: invalid command \gg<CB>t<E4>Iƣ<AC>=<AF>*ESC^TDuV^P^Ov<B6><B0>
psql:test_db.sql:117362: error: invalid command \a>@
psql:test_db.sql:117363: error: invalid command \"<99>k<86>
psql:test_db.sql:117372: error: invalid command \<9B>遥<FD><FE><BA>j
psql:test_db.sql:117406: ERROR:  invalid byte sequence for encoding "UTF8": 0x8a

With pg_restore:

pg_restore: error: input file does not appear to be a valid archive

I thought i was using -Fc with pg_dump, but somehow I missed it. Now Can you help me to restore this Backup to postgresql.
I'm Using PostgreSQL 14.5
I've tried below commands

*

*cat test_db.tar | psql test_db -U postgres -h localhost -p port

*\i testdb.tar

*even Tried to rename the dump file from test_db.tar to test_db.dump and tried restoring it. Nothing is working.

A: It seems -Z6 generates a gzipped file.
You can convert that into a plain text SQL script that psql can read using. To unzip it using gzip you will need to rename it, e.g. to test_db.sql.gz
Then you can use:
gzip -k -d test_db.sql.gz

-k  will keep the original file

A: Since I didn't mention the format of the dump with -F, by default it created a plain dump file with -Z6 compression and with the extension of .tar
The mistake on my end was that I forgot to mention the dump file format.
After trying the below command, it worked
zcat test_db.tar | psql -d test_db -U postgres -h localhost -p port


text:
Q: PHP select closest to variable Just wondering how I would select the closest variable.
I have a set list of military times, i.e:
0030
0100
0130
0200
etc...
All in half hour increments. How would I select the closest time to now.
For example.
User clicks on the button, php gets the time it is now, and selects the closest time variable. So if it's 0144, it would pick 0130. and if it's 0146, it would pick 0200.

A: Since you always store times at 30 minutes interval, subtract the last 2 digits (minutes) from the current time from 30.
For example:
If current time is 0146,

*

*strip out 46 (minutes)

*Take absolute difference from 30

*If difference > 15, take the next available time slot for 0146
(which is 0200 here)

*If difference <= 15, take the previous available time before 0146
(which is 0130 here)

Hope this helps.

A: For ease, in your calculations treat them as integers, ignoring the leading zeroes as they're not useful to your calculations.
You have 144 and you want to round down to 130, or 146, up to 200. Similarly 14 (0014) would go to 0 (0000) and 15 (0015) up to 30.
Simple if/thens would suffice to complete this.

A: I believe this should do it:
function military_time() {
    $hour = (int) date('G');
    $minute = (int) date('i');

    $rounded_minute = round($minute / 30);

    switch ($rounded_minute) {
        case 0:
            $minute = '00';
            break;
        case 1:
            $minute = '30';
            break;
        case 2:
            $minute = '00';
            $hour = (int) $hour + 1;
            break;
    }

    // 2400 should become 0000
    if ($hour > 23) $hour = 0;

    // leading zero
    if ($hour < 10) $hour = '0' . $hour;

    return $hour . $minute;
}

echo military_time();

Could probably be improved though.

A: You can try
$times = array("0030","0100","0130","0200");

echo "<pre>";
echo militaryTime($times, "0020"), PHP_EOL;
echo militaryTime($times, "0050"), PHP_EOL;
echo militaryTime($times, "0144"), PHP_EOL;
echo militaryTime($times, "0146"), PHP_EOL;
echo militaryTime($times, "0220"), PHP_EOL;

Output
0030
0100
0130
0200
0200

Function Used
function militaryTime($times, $selected) {
    if (empty($times))
        trigger_error("Empty array not supported ");
    $times[] = $selected;
    sort($times);
    $position = array_search($selected, $times, true);
    $current = DateTime::createFromFormat("Hi", $times[$position]);
    $previous = isset($times[$position - 1]) ? DateTime::createFromFormat("Hi", $times[$position - 1]) : null;
    $next = isset($times[$position + 1]) ? DateTime::createFromFormat("Hi", $times[$position + 1]) : null;

    if ($previous != null && $next == null) {
        return $previous->format("Hi");
    }
    if ($previous == null && $next != null) {
        return $next->format("Hi");
    }

    $closest = ($current->diff($previous)->format("%i") - $current->diff($next)->format("%i") <= 0) ? $previous : $next;
    return $closest->format("Hi");
}


text:
Q: How can I make a linux background process (in c) that launches a Python script I made a Linux background process (in c++) that monitors a directory and attempts to launch a Python script if a certain file appears in that directory. My issue is that the child process responsible for launching the Python script exits immediately after the execvp function is called and I can't understand why. All of the necessary files are under root's ownership. Here is my code if it helps. Thank you in advance for any pointers! I have marked the error in my code where the error occurs. I have also included the Python script to be called
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

using namespace std;

char* arguments[3];
FILE* fd;
const char* logFilePath = "/home/BluetoothProject/Logs/fileMonitorLogs.txt";
char* rfcommPath = (char*)"/home/BluetoothProject/RFCOMMOut.py";
void logToFile(const char*);
void doWork();

void logToFile(const char* str) {
    fd = fopen(logFilePath, "a");
    fprintf(fd, "%s\n", str);
    fclose(fd);
}

int main() {
    arguments[0] = (char*)"python";
    arguments[1] = rfcommPath;
    arguments[2] = NULL;
    pid_t pid = fork();
    if(pid < 0) {
        printf("Fork failed");
        exit(1);
    } else if(pid > 0) {
        exit(EXIT_SUCCESS);
    }
    umask(0);
    pid_t sid = setsid();
    if(sid < 0) {
        logToFile("setsid() didn't work.");
        exit(1);
    }
    if ((chdir("/")) < 0) {
                logToFile("chdir() didn't work.");
                exit(EXIT_FAILURE);
        }
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
    doWork();
}

void doWork() {
    pid_t pid = fork();
    if(pid < 0) {
        logToFile("doWork() fork didn't work.");
    } else if(pid > 0) {
        int status = 0;
        waitpid(pid, &status, 0);
        if(WEXITSTATUS(status) == 1) {
            logToFile("Child process exited with an error.");
        }
    } else {
        int error = execvp(arguments[0], arguments);   //Here is where the error is
        if(error == -1) {
            logToFile("execvp() failed.");
        }
        exit(1);
    }
}

Python script (AKA RFCOMMOut.py)
import RPi.GPIO as gpio
import serial
led_state = 0
led_pin = 11
gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led_pin, gpio.OUT)
try:
    ser = serial.Serial(port = '/dev/rfcomm0',
            baudrate = 9600,
            parity = serial.PARITY_NONE,
            stopbits = serial.STOPBITS_ONE,
            bytesize = serial.EIGHTBITS)
except IOException as e:
    logFile = open("/home/BluetoothProject/Logs/fileMonitorLogs.txt", "a")
        logFile.write("(First error handler) There was an exception:\n")
        logFile.write(str(e))
    logFile.write("\n")
        logFile.close()

#gpio.output

def process_input(input):
    global led_state
        if input == "I have been sent.\n":
                if led_state == 1:
            led_state = 0
            gpio.output(led_pin, led_state)
        else:
            led_state = 1
            gpio.output(led_pin, led_state)

while True:
    try:
        transmission = ser.readline()
        process_input(transmission)
    except IOError as e:
        logFile = open("/home/BluetoothProject/Logs/fileMonitorLogs.txt", "a")
        logFile.write("(second error handler) There was an exception:\n")
        logFile.write(str(e))
        logFile.write("\n")
        logFile.close()
        break
led_state = 0
gpio.output(led_pin, led_state)
gpio.cleanup()
print("End of program\n")

A: The question is a little unclear, so I'll try to take a few different educated guesses at what the problem is and address each one individually.
TL;DR: Remove close(STDOUT_FILENO) and close(STDERR_FILENO) to get more debugging information which will hopefully point you in the right direction.
execvp(3) is returning -1
According to the execvp(3) documentation, execvp(3) sets errno when it fails. In order to understand why it is failing, your program will need to output the value of errno somewhere; perhaps stdout, stderr, or your log file. A convenient way to do this is to use perror(3). For example:
#include <stdio.h>
...
void doWork() {
  ...
  } else {
    int error = execvp(arguments[0], arguments);
    if(error == -1) {
      perror("execvp() failed");
    }
  }
  ...
}

Without knowing what that errno value is, it will be difficult to identify why execvp(3) is failing.
execvp(3) is succeeding, but my Python program doesn't appear run
execvp(3) succeeding means that the Python interpreter has successfully been invoked (assuming that there is no program in your PATH that is named "python", but is not actually a Python interpreter). If your program doesn't appear to be running, that means Python is having difficulty loading your program. To my knowledge, Python will always output relevant error messages in this situation to stderr; for example, if Python cannot find your program, it will output "No such file or directory" to stderr.
However, it looks like your C program is calling close(STDERR_FILENO) before calling doWork(). According to fork(2), child processes inherit copies of their parent's set of open file descriptors. This means that calling close(STDERR_FILENO) before forking will result in the child process not having an open stderr file descriptor. If Python is having any errors executing your program, you'll never know, since Python is trying to notify you through a file descriptor that doesn't exist. If execvp(3) is succeeding and the Python program appears to not run at all, then I recommend you remove close(STDERR_FILENO) from your C program and run everything again. Without seeing the error message output by Python, it will be difficult to identify why it is failing to run the Python program.
As an aside, I recommend against explicitly closing stdin, stdout, and stderr. According to stdin(3), the standard streams are closed by a call to exit(3) and by normal program termination.
execvp(3) is succeeding, my Python program is running, but my Python program exits before it does any useful work
In this case, I'm not sure what the problem might be, since I'm not very familiar with Raspberry Pi. But I think you'll have an easier time debugging if you don't close the standard streams before running the Python program.
Hope this helps.


text:
Q: Why are the shades of black in a custom SCNGeometry lighter than in an SCNSphere In this scene

*

*the column of spheres on the left are created using SCNSphere()

*the column of 'circles' on the right are created using SCNGeometry() using .point primitives

*there is only an ambient light source

*all geometries are using a .constant lighting model

*each pair of spheres uses the same RGB values to define the colour.

Why are the shades of black for the last two pairs lighter for the circles than their equivalient sphere?

Full playground code to reproduce this images:
Creating the scene
import UIKit
import SceneKit
import PlaygroundSupport

// Constants I'm using for the darkest grey colour
let B_RED: CGFloat = 0.05
let B_GREEN: CGFloat = 0.05
let B_BLUE: CGFloat = 0.05
let B_ALPHA: CGFloat = 1.0

let BLACK_COLOUR = UIColor(red: B_RED, green: B_GREEN, blue: B_BLUE, alpha: B_ALPHA)

let scene: SCNScene = {
    let s = SCNScene()
    return s
}()

let sceneView: SCNView = {
    let v = SCNView(frame: CGRect(x: 0, y: 0, width: 600, height: 800))
    v.scene = scene
    v.backgroundColor = UIColor(white: 0.66, alpha: 1.0)
    v.allowsCameraControl = true
    v.debugOptions = [SCNDebugOptions.showLightInfluences]
    v.backgroundColor
    return v
}()

let ambientLigntNode: SCNNode = {
    let n = SCNNode()
    n.light = SCNLight()
    n.light!.type = SCNLight.LightType.ambient
    n.light!.color = UIColor(white: 1, alpha: 1.0)
    return n
}()

PlaygroundPage.current.liveView = sceneView

// a camera
var cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.simdPosition = simd_float3(0,0,8)

scene.rootNode.addChildNode(cameraNode)
scene.rootNode.addChildNode(ambientLigntNode)

The column of spheres
// ----------------------------------------------------
// White Sphere
let whiteSphere = SCNSphere(radius: 0.3)
let whiteMaterial = SCNMaterial()
whiteMaterial.diffuse.contents = simd_float3(1,1,1)

whiteMaterial.lightingModel = .constant
whiteSphere.materials = [whiteMaterial]

let whiteSphereNode = SCNNode(geometry: whiteSphere)
whiteSphereNode.simdPosition = simd_float3(-1,2,0)

scene.rootNode.addChildNode(whiteSphereNode)

// ----------------------------------------------------
// Black Sphere
let blackSphere = SCNSphere(radius: 0.3)
let blackMaterial = SCNMaterial()
blackMaterial.diffuse.contents = BLACK_COLOUR

blackMaterial.lightingModel = .constant
blackSphere.materials = [blackMaterial]

let blackSphereNode = SCNNode(geometry: blackSphere)
blackSphereNode.simdPosition = simd_float3(-1,-2,0)

scene.rootNode.addChildNode(blackSphereNode)

// ----------------------------------------------------
// Red Sphere
let redSphere = SCNSphere(radius: 0.3)
let redMaterial = SCNMaterial()
redMaterial.diffuse.contents = UIColor(
    red: 1.0,
    green: 0.0,
    blue: 0.0,
    alpha: 1.0
)

redMaterial.lightingModel = .constant
redSphere.materials = [redMaterial]

let redSphereNode = SCNNode(geometry: redSphere)
redSphereNode.simdPosition = simd_float3(-1, 1, 0)

scene.rootNode.addChildNode(redSphereNode)

// ----------------------------------------------------
// Green Sphere
let greenSphere = SCNSphere(radius: 0.3)
let greenMaterial = SCNMaterial()
greenMaterial.diffuse.contents = UIColor(
    red: 0.0,
    green: 1.0,
    blue: 0.0,
    alpha: 1.0
)

greenMaterial.lightingModel = .constant
greenSphere.materials = [greenMaterial]

let greenSphereNode = SCNNode(geometry: greenSphere)
greenSphereNode.simdPosition = simd_float3(-1, 0, 0)

scene.rootNode.addChildNode(greenSphereNode)

// ----------------------------------------------------
// Blue Sphere
let blueSphere = SCNSphere(radius: 0.3)
let blueMaterial = SCNMaterial()
blueMaterial.diffuse.contents = UIColor(
    red: 0.0,
    green: 0.0,
    blue: 1.0,
    alpha: 1.0
)

blueMaterial.lightingModel = .constant
blueSphere.materials = [blueMaterial]

let blueSphereNode = SCNNode(geometry: blueSphere)
blueSphereNode.simdPosition = simd_float3(-1, -1, 0)

scene.rootNode.addChildNode(blueSphereNode)

// ----------------------------------------------------
// Grey Sphere
let greySphere = SCNSphere(radius: 0.3)
let greyMaterial = SCNMaterial()
greyMaterial.diffuse.contents = UIColor(
    red: 0.5,
    green: 0.5,
    blue: 0.5,
    alpha: 1.0
)

greyMaterial.lightingModel = .constant
greySphere.materials = [greyMaterial]

let greySphereNode = SCNNode(geometry: greySphere)
greySphereNode.simdPosition = simd_float3(-1, -3, 0)

scene.rootNode.addChildNode(greySphereNode)

Column of circles
// ----------------------------------------------------
// Custom SCNGeometry using vertex data
struct Vertex {
    let x: Float
    let y: Float
    let z: Float
    let r: Float
    let g: Float
    let b: Float
    let a: Float
}

let vertices: [Vertex] = [
    Vertex(x: 0.0, y: 2.0, z: 0.0, r: 1.0, g: 1.0, b: 1.0, a: 1.0),  // white
    Vertex(x: 0.0, y: 1.0, z: 0.0, r: 1.0, g: 0.0, b: 0.0, a: 1.0),  // red
    Vertex(x: 0.0, y: 0.0, z: 0.0, r: 0.0, g: 1.0, b: 0.0, a: 1.0),  // green
    Vertex(x: 0.0, y: -1.0, z: 0.0, r: 0.0, g: 0.0, b: 1.0, a: 1.0), // blue
    Vertex(x: 0.0, y: -3.0, z: 0.0, r: 0.5, g: 0.5, b: 0.5, a: 1.0), // rgb
    Vertex(
        x: 0.0, y: -2.0, z: 0.0,
        r: Float(B_RED), g: Float(B_GREEN), b: Float(B_BLUE), a: Float(B_ALPHA)
    )
]

let vertexData = Data(
    bytes: vertices,
    count: MemoryLayout<Vertex>.size * vertices.count
)

let positionSource = SCNGeometrySource(
    data: vertexData,
    semantic: SCNGeometrySource.Semantic.vertex,
    vectorCount: vertices.count,
    usesFloatComponents: true,
    componentsPerVector: 3,
    bytesPerComponent: MemoryLayout<Float>.size,
    dataOffset: 0,
    dataStride: MemoryLayout<Vertex>.size
)
let colourSource = SCNGeometrySource(
    data: vertexData,
    semantic: SCNGeometrySource.Semantic.color,
    vectorCount: vertices.count,
    usesFloatComponents: true,
    componentsPerVector: 4,
    bytesPerComponent: MemoryLayout<Float>.size,
    dataOffset: MemoryLayout<Float>.size * 3,
    dataStride: MemoryLayout<Vertex>.size
)

let elements = SCNGeometryElement(
    data: nil,
    primitiveType: .point,
    primitiveCount: vertices.count,
    bytesPerIndex: MemoryLayout<Int>.size
)

elements.pointSize = 100
elements.minimumPointScreenSpaceRadius = 100
elements.maximumPointScreenSpaceRadius = 100

let spheres = SCNGeometry(
    sources: [positionSource, colourSource],
    elements: [elements]
)
let sphereNode = SCNNode(geometry: spheres)

let sphereMaterial = SCNMaterial()
sphereMaterial.lightingModel = .constant

spheres.materials = [sphereMaterial]

sphereNode.simdPosition = simd_float3(0,0,0)
scene.rootNode.addChildNode(sphereNode)

Updated based on accepted answer. Converting from sRGB to LinearRGB gives the same result
func srgbToLinear(x: Float) -> Float {
    if x <= 0.04045 {
        return x / 12.92;
    }
    return powf((x + 0.055) / 1.055, 2.4)
}

let vertices: [Vertex] = [
    Vertex(x: 0.0, y: 2.0, z: 0.0, r: 1.0, g: 1.0, b: 1.0, a: 1.0),  // white
    Vertex(x: 0.0, y: 1.0, z: 0.0, r: 1.0, g: 0.0, b: 0.0, a: 1.0),  // red
    Vertex(x: 0.0, y: 0.0, z: 0.0, r: 0.0, g: 1.0, b: 0.0, a: 1.0),  // green
    Vertex(x: 0.0, y: -1.0, z: 0.0, r: 0.0, g: 0.0, b: 1.0, a: 1.0), // blue
    Vertex(x: 0.0, y: -3.0, z: 0.0, r: srgbToLinear(x: 0.5), g: srgbToLinear(x: 0.5), b: srgbToLinear(x: 0.5), a: 1.0), // rgb
    Vertex(
        x: 0.0, y: -2.0, z: 0.0,
        r: srgbToLinear(x: Float(B_RED)),
        g: srgbToLinear(x: Float(B_GREEN)),
        b: srgbToLinear(x: Float(B_GREEN)),
        a: 1.0
    )
]

A: This would be the case if the two types of graphic are generated in different color spaces.  For example, if gray for the spheres is interpreted as being in the sRGB as the color space, and the circle are interpreted as generic RGB space then you would see a different in color values.
Consider the following playground code:
//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport
import CoreGraphics

class MyViewController : UIViewController {
    override func loadView() {
        let view = CustomView()
        view.backgroundColor = UIColor.darkGray

        self.view = view
    }
}

class CustomView : UIView {
    override func draw(_ rect: CGRect) {
        if let cgContext = UIGraphicsGetCurrentContext() {

            cgContext.saveGState()

            let gray : [CGFloat] = [0.5, 0.5, 0.5, 1.0]

            let srgbGray = CGColor(
                colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, components: gray)!

            cgContext.setFillColor(srgbGray)
            cgContext.fillEllipse(in: CGRect(x:10, y:20, width:72, height: 72))

            let genericGray = CGColor(colorSpace: CGColorSpace(name: CGColorSpace.genericRGBLinear)!, components: gray)!
            cgContext.setFillColor(genericGray)
            cgContext.fillEllipse(in: CGRect(x:110, y:20, width:72, height: 72))

            cgContext.restoreGState()

        }
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

It produces an effect almost identical to the one you are seeing.  I suspect that the circles are drawn assuming a generic color space and the spheres are drawn assuming sRGB.


text:
Q: How to solve this Real Analysis? Given that $f(x)= \sin(x + \pi/4)$   is periodic with period $2\pi$. Find the complex Fourier series.
It's quite a moderate tough question. Can someone help me out. Thanks in advance

A: Note: $\sin(x+\pi/4) = \frac{1}{2i}(e^{i(x+\pi/4)}-e^{-i(x+\pi/4)})$. Furthermore,
$$ e^{i(x+\pi/4)} = e^{ix}e^{i\pi/4}  $$
Now, use $e^{i\theta} =\cos(\theta)+i\sin(\theta)$ to find the explicit value of the coeffient $e^{i\pi/4}$. I leave the rest to you.

A: Here is your Fourier series,
$ \sin(x+\frac{\pi}{4}) = \cos(\frac{\pi}{4})\sin(x)+ \cos(\frac{\pi}{4})\cos(x)=\frac{1}{\sqrt 2} \sin(x) + \frac{1}{\sqrt 2} \cos(x)\,.$
Note that, $\sin(x+\frac{\pi}{4})$ is orthogonal to $\{ 1, \sin(mx),\cos(mx)\} \,, m=2,3,\dots $ on the $[0,2\pi]$.
Use the identities $ \sin(x) = \frac{ {\rm e}^{ix} - {\rm e}^{-ix} }{2i} $ and  $ \cos(x) = \frac{ {\rm e}^{ix} + {\rm e}^{-ix} }{2} $ to get it in the complex form
$$ \sin(x+\frac{\pi}{4}) = \left( \frac{\sqrt {2}}{4}i+\frac{\sqrt {2}}{4} \right) {{\rm e}^{-ix}}+\left( -\frac{\sqrt {2}}{4}i+\frac{\sqrt {2}}{4} \right) {{\rm e}^{ix}}
 $$


text:
Q: Build several routes,taking endpoints from array on HERE maps I'm building web app, which should build quite big amount of routes, and show their distances. Start waypoint is constant for all routes. I try to do that like this
function calculateRouteFromAtoB (platform, end) {
    var router = platform.getRoutingService(),
        routeRequestParams = {
            mode: 'fastest;truck;traffic:enabled',
            height: '7',
            weightPerAxle: '4',
            trailersCount: '1',
            routeattributes : 'sh,bb,gr',
            dirtRoad: '-3',
            tollroad:'-3',
            //tunnelCategory: 'E',
            //maneuverattributes: 'direction,action',
            'waypoint0': '50.6431675,29.9479832',
            'waypoint1': end
        };

    router.calculateRoute(
        routeRequestParams,
        onSuccess,
        onError
    );
}

var tt;
for(tt=0;tt<array_with_endpoints.length;tt++){
    calculateRouteFromAtoB(platform,array_with_endpoints[tt]);
}

Function calculateRouteFromAtoB adds route to map and its distance to panel,but the problem is that route length on panel doesn`t match real route length. I think, that endpoints are chosen randomly. If you know, how to make this code choose endpoints by order, let me know, please.

A: You might want to look into matrix routing?
https://developer.here.com/documentation/routing/topics/request-matrix-of-routes.html


text:
Q: Should we be worried by the V1 SHUTDOWN recaptcha? It looks like ye old Google RECAPTCHA is being decommissioned but we still use it on data.stackexchange.com
Google decided to warn us with this "NUCLEAR HAZARD" style image.

So, dear site owners, let me direct you to g.co/recaptcha/upgrade.


text:
Q: mask in FlannBasedMatcher::match doesn't work normally Cross post here

I note the function FlannBasedMatcher::match have a parameter mask, so I give a try with following code:
#include<opencv.hpp>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/nonfree/nonfree.hpp"
using namespace cv;
using namespace std;

int main() {
    Mat rightImg = imread("right.jpg", 0);
    Mat leanImg = imread("lean.jpg", 0);
    if (!rightImg.data || !leanImg.data) {
        cout << "Fail to read your image. Please check your path.\n";
        return -1;
    }
    resize(leanImg, leanImg, rightImg.size());
    int minHessian = 400;
    SurfFeatureDetector detector(minHessian);
    vector<KeyPoint> keypoints_right, keypoints_lean;

    detector.detect(rightImg, keypoints_right);
    detector.detect(leanImg, keypoints_lean);

    Mat med_right, med_lean;
    drawKeypoints(rightImg, keypoints_right, med_right);
    drawKeypoints(leanImg, keypoints_lean, med_lean);

    SurfDescriptorExtractor extractor;
    Mat descriptors_right, descriptors_lean;
    extractor.compute(rightImg, keypoints_right, descriptors_right);
    extractor.compute(leanImg, keypoints_lean, descriptors_lean);

    FlannBasedMatcher matcher;
    vector< DMatch > matches;

    Mat mask(descriptors_right.rows, descriptors_lean.rows, CV_8UC1, Scalar(0));

    Mat target(rightImg.size(), CV_8UC1, Scalar(255));
    ellipse(target, Point(rightImg.cols / 2, rightImg.rows / 2), Size(rightImg.cols / 2, rightImg.rows / 2), 0, 0, 360, Scalar(0), CV_FILLED);

    for (int i = 0; i < mask.rows; i++) {
        uchar* pixrow = mask.ptr<uchar>(i);
        for (int j = 0; j < mask.cols; j++) {
            if (target.at<uchar>(keypoints_right[i].pt) == 255)
                pixrow[j] = 255;
        }
    }

    matcher.match(descriptors_right, descriptors_lean, matches/*, mask*/);//use it or not to test

    Mat img_matches;
    drawMatches(rightImg, keypoints_right, leanImg, keypoints_lean,
        matches, img_matches, Scalar::all(-1), Scalar::all(-1),
        vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
    return 0;
    }

And this is my right.jpg and lean.jpg. I don't care those points in the center of right.jpg. So I make a mask for it. But I note I will get a same result totally whether I use the mask in the function FlannBasedMatcher::match. You can use the mask or not to reproduce it. Do I have missed something or the OpenCV have a bug in my 2.4.13? Can anyone tell me how to use the mask in the FlannBasedMatcher::match? I think it is a usefull parameter..

A: From the docs: "FlannBasedMatcher does not support masking permissible matches of descriptor sets because flann::Index does not support this." See the DescriptorMatcher::isMaskSupported method for a way to test if the matcher supports masking.


text:
Q: Optimization of JavaScript countdown I'm not very familiar with JavaScript but I need to set up a countdown to display days, hours, minutes and seconds separately. I found following JS code, however, I'm not sure that this code is optimal. Could you please recommend me any better solution if possible?

I would like to display individual variables from JS as:

Thank you in advance!

A: you have asked 2 questions here.

1st question: you are already using a better solution.
2nd question: I think you are asking for your countdown to be shown in a single p tag. If I'm right then try this code.

var cddate = new Date("May 31, 2019 16:55:00").getTime();
        var x = setInterval(function() {
            var now = new Date().getTime();
            var distance = cddate - now;
            var count = Math.floor(distance / (86400000)) + ' ' + (Math.floor((distance % (86400000)) / (3600000)) + 1) + ':' + Math.floor((distance % (3600000)) / (60000)) + ':' + Math.floor((distance % (60000)) / 1000);
            document.getElementById("xid").innerHTML = count;
        }, 1000);


text:
Q: App crashes when trying to run parse.com push notification application My parse push notification app seems to crash whenever I run it. I double checked to make sure that the permissions were correct and that my build.gradle  was also correct. I created a Java class (which I added to the src folder) for the Parse Application. Here is the code for the Parse Application, my Android Manifest, and the build.gradle file.
BUILD.GRADLE FILE
buildscript {
repositories {
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.2.3'
}
}
apply plugin: 'com.android.application'

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "com.example.anish.parseexample"
    minSdkVersion 19
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile files('libs/Parse-1.9.2.jar')
}

PARSEAPP.JAVA
 package com.example.anish.parseexample;

 import android.app.Application;

 import com.parse.Parse;
 import com.parse.PushService;

 public class ParseApp extends Application {
 @Override
 public void onCreate() {
    super.onCreate();
    Parse.initialize(this, "APP_ID_KEY_WAS_HERE", "CLIENT_ID_KEY_WAS_HERE");
    PushService.setDefaultPushCallback(this, MainActivity.class);
}
}

ANDROIDMANIFEST.XML
<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="ANDROID.PERMISSION.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="ANDROID.PERMISSION.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="com.google.android.c2de.permission.RECEIVE"/>

<permission android:protectionLevel="signature" android:name="com.example.ani.parseexample.ParseApp.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.example.ani.parseexample.ParseApp.permission.C2D_MESSAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:name=".ParseApp">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<service android:name="com.parse.PushService"/>
<receiver android:name="com.parse.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
        <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
        <category android:name="com.example.ani.parseexample.ParseApp"/>
    </intent-filter>
</receiver>

</manifest>

LOGCAT
Service com.android.providers.media.MtpService has leaked IntentReceiver android.mtp.MtpDatabase$1@3b5d3c26 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Service com.android.providers.media.MtpService has leaked IntentReceiver android.mtp.MtpDatabase$1@3b5d3c26 that was originally registered here. Are you missing a call to unregisterReceiver()?
        at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1003)
        at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:767)
        at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1749)
        at android.app.ContextImpl.registerReceiver(ContextImpl.java:1729)
        at android.app.ContextImpl.registerReceiver(ContextImpl.java:1723)
        at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:488)
        at android.mtp.MtpDatabase.setServer(MtpDatabase.java:619)
        at android.mtp.MtpServer.<init>(MtpServer.java:33)
        at com.android.providers.media.MtpService.manageServiceLocked(MtpService.java:259)
        at com.android.providers.media.MtpService.onStartCommand(MtpService.java:219)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3072)
        at android.app.ActivityThread.access$2100(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:155)
        at android.app.ActivityThread.main(ActivityThread.java:5696)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

If there is some information missing in the logcat, please let me know. I am using a phone to run the app, and it gives many error messages about other running processes in the system. I have turned the Parse-1.9.2.jar folder into a library, if that helps at all. I have also tried the parse example at https://parse.com/apps/quickstart#parse_push/android/native/existing but that hasn't worked either. Can someone please help?
Sincerely,
Ani

A: Firstly.
<uses-permission android:name="com.google.android.c2de.permission.RECEIVE"/>

should probably be:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>

c2dm not c2de
Also, in some places you use com.example.anish and in others you use com.example.ani. You should make sure you are consistent with the package as defined in your manifest/gradle.
In your permission, uses-permission and broadcast receiver you should be consistent. In your case your setup should be more like:
<!-- lowercase these 2 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/
<!-- end lowercase -->
...
<permission android:protectionLevel="signature" android:name="com.example.anish.parseexample.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.example.anish.parseexample.permission.C2D_MESSAGE"/>
...
<receiver android:name="com.parse.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
        <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
        <category android:name="com.example.ani.parseexample"/>
    </intent-filter>
</receiver>

I've never used parse.com however, the above is based on my understanding of the google cloud messaging setup.


text:
Q: Como utilizar operador ternário em Flutter/Dart Como fazer o if/else em uma linha em Dart/Flutter?
Tipo: variavel ? null : function() : function2()

A: Pode fazer assim:
Comparação ? Valor se verdadeiro : Valor se falso;

Ex.:
void main() {
    for (int i = 0; i < 5; i++) {
        var result = i % 2 == 0 ? print("$i - par") : print("$i - impar");
    }
}


text:
Q: Decimal Expansions - Pugh Exercise 1.18 I have been working through an exercise from Pugh's 'Real Mathematical Analysis' and although there is an answer on this site discussing the exercise (Pugh exercise 1.18) there is a part of the explanation given there that I cannot figure out. It is in the answerer's explanation of part (a): Show that each $x_k$ in the decimal expansion is an integer between $0$ and $9$.
The issue I'm having is with how to show that $$10(x-N) < x_1 + 1, \text{ given that } 0\leq x_1 \leq 9$$ and also how to prove the related statement for the induction step (which I assume uses similar reasoning): $$10^n\left(x-\left(N+\sum_{k=1}^{n-1}\frac{x_k}{10^k}\right)\right) < x_n + 1.$$
Here is my attempt for the first inequality:
Suppose that $x_1 + 1 \leq 10(x-N)$. Then since $x-N < 1$ by definition of the floor function we have $x_1 + 1 \leq 10(x-N) < 10$. Therefore $x_1 < 9$. But we know that $x_1 \leq 9$ (but this isn't a contradiction is it? since we already know $x_1<9$? Or is this a contradiction because we know that $x_1$ can equal $9$.).
I'm not sure what else to do so any hints and/or explanations are welcome. Thanks.

A: Recall the definition of $x_1$. It is the largest integer less than or equal to $10(x-N)$. So any integer larger than $x_1$ must be greater than $10(x-N)$. In particular this is true for $x_1 + 1$, i.e.,
$$x_1 + 1 > 10(x-N).$$


text:
Q: How can I see the addres being sent via axios in nodejs? I am trying to send parameters to a web API using axios in nodejs. This is the code snippet I am trying to use:
const app = require('axios');

app.get("https://api.somedomain.com/v1/", {
  headers: {
    Param1: 'value1',
    Param2: 'value2',
    Param3: 'value3'
  }
})
  .then((res) => {
    console.log("Executing 'then' block");  // never executes
  })
  .catch((err) => {
    if (err.response) {
      console.log(`response.status: ${err.response.status}`);
    } else if(err.request) {
      console.log(`request.status: ${err.request.status}`);
    }
  })

When I execute the above I always get a response code 400 from the catch block.
So my question is this:
Can I display the string which is sent to the web API?  Something that would look like this output:
https://api.somedomain.com/v1/?Param1=value1&Param2=value2&Param3=value3
Sorry if this seems naive but I have been able to make one get to retrieve a URL I will use to send the second get. The first get works and I have the URL. The second one always gives me the 400 response. (Or perhaps, is it because I have executed one get request on the app object and I have failed to clean up the app object to prepare for the next get request?)
Thanks in advance for your reply.
Peter

A: Change from headers to params in axios config:
const app = require('axios');

app.get("https://api.somedomain.com/v1/", {
  params: { // HERE IS THE CHANGE!
    Param1: 'value1',
    Param2: 'value2',
    Param3: 'value3'
  }
})
  .then((res) => {
    console.log("Executing 'then' block");  // never executes
  })
  .catch((err) => {
    if (err.response) {
      console.log(`response.status: ${err.response.status}`);
    } else if(err.request) {
      console.log(`request.status: ${err.request.status}`);
    }
  })


text:
Q: Join Two Parent tables where all children required to match I have 2 tables which share a common table of "types"
The type table is as follows:
CREATE TABLE [ModifierType](
[ModifierTypeID] [int] NOT NULL,
[Code] [varchar](10) NOT NULL,
[Name] [varchar](50) NOT NULL,)

CREATE TABLE [UserRequest](
[UserRequestID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,)

CREATE TABLE [Matrix](
[MatrixID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,)

CREATE TABLE [UserRequestModifier](
[UserRequestModifierID] [int] NOT NULL,
[UserRequestID] [int] NOT NULL,
[ModifierTypeID] [int] NOT NULL,
[Value] [varchar](50) NOT NULL,)

CREATE TABLE [MatrixModifier](
[MatrixModifierID] [int] NOT NULL,
[MatrixID] [int] NOT NULL,
[ModifierTypeID] [int] NOT NULL,
[Value] [varchar](50) NOT NULL,)

The others are a UserRequestModifier table, and a "MatrixModifier" table which contains rules for determining access a request should be provisioned. Matrix in this case just refers to a set of rules that will grant access to a specific application or group. These two tables each have a ModifierTypeID which will link the two and a value field that will be used for finding matches.
However, each UserRequest/Matrix (parents to the modifier tables) can each have multiple modifier records.
What I need to do, is find all the Matrix records for which the UserRequestModifiers meets all the MatrixModifier requirements. Basically, I want to ignore any MatrixIDs that have even 1 modifier value that does not match ANY of the UserRequestModifier values.
So far I have a query that will do it, but it seems a bit backwards to me, because I'm having to first find all the MatrixIDs that the UserRequestModifiers do not meet the requirements in a subselect. Then getting the records that are NOT IN those results as follows:
SELECT
    UR.[UserRequestModifierID]
    ,UR.[ModifierTypeID]
    ,UR.[Value] AS [URValue]
    ,MM.[Value] AS [MMValue]
    ,MM.[MatrixModifierID]
    ,MM.[MatrixID]
    ,MM.[ModifierTypeID]
    ,M.[MatrixID]
FROM
    AMP.[UserRequestModifier] AS UR
LEFT OUTER JOIN AMP.[MatrixModifier] AS MM
    ON (MM.[ModifierTypeID] = UR.[ModifierTypeID])
LEFT OUTER JOIN AMP.[Matrix] AS M
WHERE
    UR.[UserRequestID] = @UserRequestID
    AND M.[MatrixID] IS NOT NULL
    AND M.[MatrixID] NOT IN
        (SELECT
            DISTINCT MM.[MatrixID]
        FROM
            AMP.[UserRequestModifier] AS UR
        LEFT OUTER JOIN AMP.[MatrixModifier] AS MM
            ON (MM.[ModifierTypeID] = UR.[ModifierTypeID])
        WHERE
            UR.[UserRequestID] = @UserRequestID
            AND (CASE WHEN LTRIM(RTRIM(MM.[Value])) = LTRIM(RTRIM(UR.[Value])) THEN 1 ELSE 0 END) = 0
            AND MM.[MatrixID] IS NOT NULL)
ORDER BY M.[MatrixID], MM.[ModifierTypeID]

I know this is a bit hard to follow, but I'm hoping someone can point out something obvious I'm missing.

A: It's a relational division problem, as Martin Smith pointed. One way to solve it, I think, is this:
SELECT
    M.*
FROM
    Matrix AS M
  LEFT JOIN
    MatrixModifier AS MM
        ON MM.MatrixID = M.MatrixID
  LEFT JOIN
    UserRequestModifier AS URM
        ON URM.ModifierTypeID = MM.ModifierTypeID
GROUP BY
    M.MatrixID
HAVING
    COUNT(DISTINCT MM.ModifierTypeID) = COUNT(DISTINCT URM.ModifierTypeID)

A: For MS SQL Server:
-- ====================
-- sample data
-- ====================
DECLARE @ModifierType TABLE (
[ModifierTypeID] [int] NOT NULL,
[Code] [varchar](10) NOT NULL,
[Name] [varchar](50) NOT NULL)

DECLARE @UserRequest TABLE (
[UserRequestID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL)

DECLARE @Matrix TABLE (
[MatrixID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL)

DECLARE @UserRequestModifier TABLE (
[UserRequestModifierID] [int] NOT NULL,
[UserRequestID] [int] NOT NULL,
[ModifierTypeID] [int] NOT NULL,
[Value] [varchar](50) NOT NULL)

DECLARE @MatrixModifier TABLE (
[MatrixModifierID] [int] NOT NULL,
[MatrixID] [int] NOT NULL,
[ModifierTypeID] [int] NOT NULL,
[Value] [varchar](50) NOT NULL)

insert into @modifiertype
select 1, '1', 'modname1'
union all
select 2, '2', 'modname2'
union all
select 3, '3', 'modname3'
union all
select 4, '4', 'modname4'
union all
select 5, '5', 'modname5'
union all
select 6, '6', 'modname6'

insert into @userrequest
select 1, 'ureq1'
union all
select 2, 'ureq2'
union all
select 3, 'ureq3'
union all
select 4, 'ureq4'

insert into @matrix
select 1, 'm1'
union all
select 2, 'm2'
union all
select 3, 'm3'
union all
select 4, 'm4'

insert into @userrequestmodifier
select 1, 1, 1, 'val1'
union all
select 2, 1, 2, 'val2'
union all
select 3, 1, 3, 'val3'
union all
select 4, 1, 4, 'val4'
union all
select 5, 2, 5, 'val5'
union all
select 6, 1, 5, 'val5'
union all
select 7, 1, 6, 'val6'
union all
select 8, 1, 6, 'val6'

insert into @matrixmodifier
select 1, 1, 1, 'val1'
union all
select 2, 2, 2, 'val2'
union all
select 3, 3, 3, 'val'
union all
select 4, 2, 4, 'val4'
union all
select 5, 2, 5, 'val5'
union all
select 6, 3, 4, 'val4'
union all
select 7, 13, 4, 'val4'

declare @UserRequestID int
set @UserRequestID = 1

-- ====================
-- solution
-- ====================
select
    userrequestmodifierid,
    modifiertypeid,
    urvalue,
    mmvalue,
    matrixmodifierid,
    mmmatrixid,
    mmatrixid
from
(
    select
        urm.userrequestmodifierid,
        urm.modifiertypeid,
        urvalue = urm.value,
        mmvalue = mm.value,
        mm.matrixmodifierid,
        mmmatrixid = mm.matrixid,
        mmatrixid = m.matrixid,
        f = max(case when urm.value != mm.value then 1 end) over (partition by mm.matrixid)
    from @userrequestmodifier urm
    left join @matrixmodifier mm on
        urm.modifiertypeid = mm.modifiertypeid
    left join @matrix m on
        m.matrixid = mm.matrixid
    where urm.userrequestid = @userrequestid
) t
where f is null or mmatrixid is null


text:
Q: Start an activity from a listview Hi I have a listview and, I am trying to start an activity from the listview by startActivity(class.java);
public class ll2 extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] myList = new String[] {"Accrington Stanley", "Aldershot Town", "Barnet", "Bradford City", "Burton Albion", "Bury", "Cheltenham Town", "Chesterfield", "Crewe A", "Gillingham", "Hereford Utd", "Lincoln City", "Macclesfield T", "Morecombe", "Northampton T", "Oxford Utd", "Port Vale", "Rotherham Utd", "Shrewsbury T", "Southend Utd", "Stevenage", "Stockport C", "Torquay Utd", "Wycombe W"};
        ListView lv = new ListView(this);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myList));
        setContentView(lv); }

        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

        if ("Bradford City".equals(MyList()[position])){
            startActivity(Bradford.java);}
        }
}

I am getting a error with this line if("Bradford City".equals(MyList()[position]))  method myList() is undefined for the type ll2
I have tried all sorts of methods, and I cannot get anything to work.  All I want to do is for each team in the list have a separate java file(Class) With activities in them.

A: MyList()[position] should be myList[position].Next you can not start an activity like this startActivity(Bradford.java);. For starting a new activity you need to create and intent and then set the Activity class. Then you can call startActivity with that intent.Intent intent = new Intent();
intent.setClass(this, Bradford.class);
startActivity(intent);And you need to add Bradford activity to your manifest as well.

A: I struggled with this all day and thought id post it everywhere i could.
I got the a little easier answer. Basically i turned it into a string so i could just type out what i wanted where.
protected void onListItemClick(ListView l, View v, int position, long id) {
    String item = (String) getListAdapter().getItem(position);
    if (item.equals("Economy"))
        {

    Intent intent = new Intent(packages.this, economy.class);
        startActivity(intent);
}
    else if (item.equals("Basic"))
    {

Intent intent = new Intent(packages.this, basic.class);
    startActivity(intent);
}
    else if (item.equals("Professional"))
    {

Intent intent = new Intent(packages.this, professional.class);
    startActivity(intent);
}
}


text:
Q: What causes the difference of different copy method of different array length in C#? In C#, there are some different ways to copy the elements of an array to another. To the best of my knowledge, they are "For" loop, Array.CopyTo, Span<T>.CopyTo, T[].CopyTo and Buffer.BlockCopy.
Since looping to copy the elements is always the slowest way, I skip it and run benchmark test for the other four methods. However, it seems that the speed of them are related with the length of the array, which really confused me.
My code of benchmark test is shown below. My experiment environment is Windows 11, .NET 6, Intel 12700 CPU, 64bits, using "BenchmarkDotnet" as the benchmark test framework.
public class UnitTest1
{
    static readonly int times = 1000;
    static readonly int arrayLength = 8;
    int[] src = GetRandomArray(arrayLength);
    int[] dst = new int[arrayLength];
    public static int[] GetRandomArray(int length)
    {
        int[] array = new int[length];
        for (int i = 0; i < length; i++)
        {
            array[i] = new Random(DateTime.Now.Millisecond).Next(int.MinValue, int.MaxValue);
        }
        System.Threading.Thread.Sleep(2000);
        return array;
    }

    [Benchmark]
    public void TestArrayCopy()
    {
        for (var j = 0; j < times; j++)
        {
            src.CopyTo(dst, 0);
        }
    }
    [Benchmark]
    public void TestSingleSpanCopy()
    {
        var dstSpan = dst.AsSpan();
        for (var j = 0; j < times; j++)
        {
            src.CopyTo(dstSpan);
        }
    }
    [Benchmark]
    public void TestDoubleSpanCopy()
    {
        var srcSpan = src.AsSpan();
        var dstSpan = dst.AsSpan();
        for (var j = 0; j < times; j++)
        {
            srcSpan.CopyTo(dstSpan);
        }
    }
    [Benchmark]
    public void BufferCopy()
    {
        for (var j = 0; j < times; j++)
        {
            System.Buffer.BlockCopy(src, 0, dst, 0, sizeof(int) * src.Length);
        }
    }
}

Here are the test results.
times = 1000, arrayLength = 8
|             Method |     Mean |     Error |    StdDev |
|------------------- |---------:|----------:|----------:|
|      TestArrayCopy | 3.061 us | 0.0370 us | 0.0543 us |
| TestSingleSpanCopy | 1.297 us | 0.0041 us | 0.0038 us |
| TestDoubleSpanCopy | 1.113 us | 0.0190 us | 0.0203 us |
|         BufferCopy | 7.162 us | 0.1250 us | 0.1044 us |

times = 1000, arrayLength = 16
|             Method |     Mean |     Error |    StdDev |
|------------------- |---------:|----------:|----------:|
|      TestArrayCopy | 3.426 us | 0.0677 us | 0.0806 us |
| TestSingleSpanCopy | 1.609 us | 0.0264 us | 0.0206 us |
| TestDoubleSpanCopy | 1.478 us | 0.0228 us | 0.0202 us |
|         BufferCopy | 7.465 us | 0.0866 us | 0.0723 us |

times = 1000, arrayLength = 32
|             Method |      Mean |     Error |    StdDev |    Median |
|------------------- |----------:|----------:|----------:|----------:|
|      TestArrayCopy |  4.063 us | 0.0417 us | 0.0390 us |  4.076 us |
| TestSingleSpanCopy |  4.115 us | 0.3552 us | 1.0473 us |  4.334 us |
| TestDoubleSpanCopy |  3.576 us | 0.3391 us | 0.9998 us |  3.601 us |
|         BufferCopy | 12.922 us | 0.7339 us | 2.1640 us | 13.814 us |

times = 1000, arrayLength = 128
|             Method |      Mean |     Error |    StdDev |    Median |
|------------------- |----------:|----------:|----------:|----------:|
|      TestArrayCopy |  7.865 us | 0.0919 us | 0.0815 us |  7.842 us |
| TestSingleSpanCopy |  7.036 us | 0.2694 us | 0.7900 us |  7.256 us |
| TestDoubleSpanCopy |  7.351 us | 0.0914 us | 0.0855 us |  7.382 us |
|         BufferCopy | 10.955 us | 0.1157 us | 0.1083 us | 10.947 us |

times = 1000, arrayLength = 1024
|             Method |     Mean |    Error |    StdDev |   Median |
|------------------- |---------:|---------:|----------:|---------:|
|      TestArrayCopy | 45.16 us | 3.619 us | 10.670 us | 48.95 us |
| TestSingleSpanCopy | 36.85 us | 3.608 us | 10.638 us | 34.77 us |
| TestDoubleSpanCopy | 38.88 us | 3.378 us |  9.960 us | 39.91 us |
|         BufferCopy | 48.83 us | 4.352 us | 12.833 us | 53.65 us |

times = 1000, arrayLength = 16384
|             Method |     Mean |     Error |    StdDev |
|------------------- |---------:|----------:|----------:|
|      TestArrayCopy | 1.417 ms | 0.1096 ms | 0.3233 ms |
| TestSingleSpanCopy | 1.487 ms | 0.1012 ms | 0.2983 ms |
| TestDoubleSpanCopy | 1.438 ms | 0.1115 ms | 0.3287 ms |
|         BufferCopy | 1.423 ms | 0.1147 ms | 0.3383 ms |

times = 100, arrayLength = 65536
|             Method |     Mean |    Error |    StdDev |
|------------------- |---------:|---------:|----------:|
|      TestArrayCopy | 630.9 us | 47.01 us | 138.61 us |
| TestSingleSpanCopy | 629.5 us | 46.83 us | 138.08 us |
| TestDoubleSpanCopy | 655.4 us | 47.23 us | 139.25 us |
|         BufferCopy | 419.0 us |  3.31 us |   2.93 us |

When the arrayLength is 8 or 16, the Span<T>.CopyTo() is the fastest. When the arrayLength is 32 or 128, the first three way are almost the same and all faster than Buffer.BlockCopy.Ehen the arrayLength is 1024, however, the Span<T>.CopyTo and T[].CopyTo are again faster than the other two ways. When the arrayLength is 16384, these four ways are almost the same. But when the arrayLength is 65536, the Buffer.BlockCopy is the fastest! Besides, the Span<T>.CopyTo here is a bit slower than the first two ways.
I really can't understand the results. At first I guess it's the cpu cache that matters. However, the L1 Cache of my CPU is 960KB, which is larger than the space of the array of any test case. Maybe it's the different implementation that causes this?
I will appreciate it if you are willing to explain it for me or discuss with me. I will also think about it and update the question if I get an idea.

As @Ralf mentioned, the source and destination of the array in each time are all the same, which could impact on the results. I modified my code and tried the test again, as is shown below. To avoid the time consume, I just declare a new array each time instead of randomize it manually.
using System.Buffers;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

public class Program
{
    public static void Main(string[] args)
    {
        var summary = BenchmarkRunner.Run(typeof(Program).Assembly);
        Console.WriteLine(summary);
    }
}
public class UnitTest1
{
    static readonly int times = 1000;
    static readonly int arrayLength = 8;
    public static int[] GetRandomArray(int length)
    {
        int[] array = new int[length];
        //for (int i = 0; i < length; i++)
        //{
        //    array[i] = new Random(DateTime.Now.Millisecond).Next(int.MinValue, int.MaxValue);
        //}
        return array;
    }

    [Benchmark]
    public void ArrayCopy()
    {
        for (var j = 0; j < times; j++)
        {
            int[] src = GetRandomArray(arrayLength);
            int[] dst = new int[arrayLength];
            src.CopyTo(dst, 0);
        }
    }
    [Benchmark]
    public void SingleSpanCopy()
    {
        for (var j = 0; j < times; j++)
        {
            int[] src = GetRandomArray(arrayLength);
            int[] dst = new int[arrayLength];
            src.CopyTo(dst.AsSpan());
        }
    }
    [Benchmark]
    public void DoubleSpanCopy()
    {
        for (var j = 0; j < times; j++)
        {
            int[] src = GetRandomArray(arrayLength);
            int[] dst = new int[arrayLength];
            src.AsSpan().CopyTo(dst.AsSpan());
        }
    }
    [Benchmark]
    public void BufferCopy()
    {
        for (var j = 0; j < times; j++)
        {
            int[] src = GetRandomArray(arrayLength);
            int[] dst = new int[arrayLength];
            System.Buffer.BlockCopy(src, 0, dst, 0, sizeof(int) * src.Length);
        }
    }
}

times = 1000, arrayLength = 8
|         Method |      Mean |     Error |    StdDev |    Median |
|--------------- |----------:|----------:|----------:|----------:|
|      ArrayCopy |  8.843 us | 0.1762 us | 0.3040 us |  8.843 us |
| SingleSpanCopy |  6.864 us | 0.1366 us | 0.1519 us |  6.880 us |
| DoubleSpanCopy | 10.543 us | 0.9496 us | 2.7999 us | 10.689 us |
|     BufferCopy | 21.270 us | 1.3477 us | 3.9738 us | 22.630 us |

times = 1000, arrayLength = 16
|         Method |     Mean |    Error |   StdDev |   Median |
|--------------- |---------:|---------:|---------:|---------:|
|      ArrayCopy | 16.94 us | 0.952 us | 2.808 us | 17.27 us |
| SingleSpanCopy | 12.54 us | 1.054 us | 3.109 us | 12.32 us |
| DoubleSpanCopy | 13.23 us | 0.930 us | 2.741 us | 13.25 us |
|     BufferCopy | 23.43 us | 1.218 us | 3.591 us | 24.99 us |

times = 1000, arrayLength = 32
|         Method |     Mean |    Error |   StdDev |   Median |
|--------------- |---------:|---------:|---------:|---------:|
|      ArrayCopy | 24.35 us | 1.774 us | 5.229 us | 26.23 us |
| SingleSpanCopy | 20.64 us | 1.726 us | 5.089 us | 21.09 us |
| DoubleSpanCopy | 19.97 us | 1.915 us | 5.646 us | 20.08 us |
|     BufferCopy | 26.24 us | 2.547 us | 7.511 us | 24.59 us |

times = 1000, arrayLength = 128
|         Method |     Mean |    Error |   StdDev |
|--------------- |---------:|---------:|---------:|
|      ArrayCopy | 39.11 us | 0.529 us | 0.495 us |
| SingleSpanCopy | 39.14 us | 0.782 us | 1.070 us |
| DoubleSpanCopy | 40.24 us | 0.798 us | 1.398 us |
|     BufferCopy | 42.20 us | 0.480 us | 0.426 us |

times = 1000, arrayLength = 1024
|         Method |     Mean |   Error |  StdDev |
|--------------- |---------:|--------:|--------:|
|      ArrayCopy | 254.6 us | 4.92 us | 8.87 us |
| SingleSpanCopy | 241.4 us | 2.98 us | 2.78 us |
| DoubleSpanCopy | 243.7 us | 4.75 us | 4.66 us |
|     BufferCopy | 243.0 us | 2.85 us | 2.66 us |

times = 1000, arayLength = 16384
|         Method |     Mean |     Error |    StdDev |
|--------------- |---------:|----------:|----------:|
|      ArrayCopy | 4.325 ms | 0.0268 ms | 0.0250 ms |
| SingleSpanCopy | 4.300 ms | 0.0120 ms | 0.0112 ms |
| DoubleSpanCopy | 4.307 ms | 0.0348 ms | 0.0325 ms |
|     BufferCopy | 4.293 ms | 0.0238 ms | 0.0222 ms |

times = 100, arrayLength = 65536
|         Method |     Mean |    Error |   StdDev |   Median |
|--------------- |---------:|---------:|---------:|---------:|
|      ArrayCopy | 153.6 ms |  1.46 ms |  1.29 ms | 153.1 ms |
| SingleSpanCopy | 213.4 ms |  8.78 ms | 25.87 ms | 218.2 ms |
| DoubleSpanCopy | 221.2 ms |  9.51 ms | 28.04 ms | 229.7 ms |
|     BufferCopy | 203.1 ms | 10.92 ms | 32.18 ms | 205.6 ms |

@Ralf is right, there is indeed some differences. The most significant one is that when arrayLength = 65536, Array.Copy instead of Buffer.BlockCopy is the fastest.
But still, the results are very confusing..

A: Are you sure you can repeat the same benchmark and get the same results? Perhaps it was just a one time occurence, maybe caused by heat issues or another app taking processor time. When I try it on my machine, the values I get are more in line with what you'd expect.
It says Windows 10 for some reason, I'm using 11 too.
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000
11th Gen Intel Core i9-11980HK 2.60GHz, 1 CPU, 16 logical and 8 physical cores
.NET SDK=6.0.201
  [Host]     : .NET 6.0.3 (6.0.322.12309), X64 RyuJIT
  DefaultJob : .NET 6.0.3 (6.0.322.12309), X64 RyuJIT

|             Method |     Mean |   Error |  StdDev |
|------------------- |---------:|--------:|--------:|
|      TestArrayCopy | 466.6 us | 0.69 us | 0.61 us |
| TestSingleSpanCopy | 444.7 us | 1.07 us | 1.00 us |
| TestDoubleSpanCopy | 443.8 us | 0.62 us | 0.52 us |
|         BufferCopy | 447.1 us | 7.28 us | 6.08 us |

Just before posting this, I realized: Your CPU, 12700, has performance and efficiency cores. What if it ran most of the benchmark on efficiency cores and just so happened to run the BufferCopy part on performance cores? Can you try disabling your efficiency cores in BIOS?


text:
Q: Default value does not work in entity framework code first migration I stumbled upon a entity framework related question which I havn't found any answer for yet. When I try to add or alter a column while using code first migrations and set a default value for this column, I have the possibility to use either the defaultValue and/or the defaultValueSql argument.
The official MSDN documentation writes following:
ColumnModel.DefaultValue:

Gets or sets a constant value to use as the default value for this column.

ColumnModel.DefaultValueSql:

Gets or sets a SQL expression used as the default value for this column.

Since different default value related questions on stackoverflow use different approaches, can someone please tell me when to use one or another?
For my specific use-case, I want to set a constant value of 4 for my database column, like this:
public override void Up()
{
    this.AddColumn("dbo.Foo", "Bar", c => c.Int(nullable: false, defaultValue: 4));
}

Which results in the following:

Although this looks absolutely right, all the values of the data rows are set to zero...  Does anyone has any idea, why?
EDIT: Since @Vidmantas Blazevicius stated that default values will not be automatically applied, I tried to add following code to my Configuration class:
internal sealed class MigrationConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
    protected override void Seed(DatabaseContext context)
    {
        context.Database.ExecuteSqlCommand("UPDATE [dbo].[Foo] SET [Bar] = 4");
    }
}

But this also does not work. Do you guys have any idea how I set the default value after adding a new column?

A: The default values aren't retrospectively added for existing records when adding new column to an existing table.
You can use Add-Migration RunSqlScript to add a new migration step and update the values in the new column with custom Sql.


text:
Q: Both start index and end index are out of range but the substring method still works in Java I tried the code "a".substring(1, 1) and it didn't throw an exception. But the start index is 1, which is larger than 0, and because the start index is inclusive, shouldn't it throw an exception?
Similarly, "".substring(0, 0) doesn't crash either, even though 0 should be out of range for an empty string.

A: Acording to the documentation of the method:

Throws:
  IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

The length of your string is 1 and not 0, so it doens't throw and exception.

A: Essentially, the substring method returns a string (substring) whose length is equal to (end-start), param values: passed in your method.
If end-start = 0, It would return an emptry string. Please see the source code of ORACLE JDK1.7
public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
       }
        if (endIndex > count) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        if (beginIndex > endIndex) {
            throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
        }
        return ((beginIndex == 0) && (endIndex == count)) ? this :
            new String(offset + beginIndex, endIndex - beginIndex, value);
    }

It would raise an IndexOutOfBoundsException only when this happens:
*

if the beginIndex is negative, or endIndex is larger than the length
  of this String object, or beginIndex is larger than endIndex.

*


text:
Q: Create mini loop in the head to use advanced excerpt - loop to use current post ID I am using advanced excerpt plugin because there is so much more flexibility with it's options.
Though if found a drawback with the plugin, I have to remove the standard excerpt function using remove_all_filters('the_excerpt'); other wise it conflicts with the advanced excerpt options.
Problem
I want to add the except to my head in a open graph meta for facebook. Usually I would do this with a simple get_the_excerpt(); and weave this into the meta tag like so...
<meta property="og:description" content="<?php echo get_the_excerpt(); ?>" />

But this will not work - because I have removed the excerpt filter.

How to fix?
My attempt below creating WP query which gets the current ID and creates a mini loop where I can place the the advance expert call in.
But for some reason this loop breaks my site, and I cant seem to fix. Can anyone please help me fix this loop. Would very much appreciate it thanks.

<?php if ( is_single() || is_page() ) {

    $postID         = get_the_ID();
    $fbexcerpt      = new WP_Query(array( 'p' => $postID ));

    while ($fbexcerpt->have_posts()) :
    $fbexcerpt->the_post();

    echo '<meta property="og:description" content="' . the_advanced_excerpt('length=120&use_words=0') . '" />';

    unset($fbexcerpt);
    endif; wp_reset_query();

} ?>

UPDATE
If anyone has any alternative ideas that does not require 'advanced excerpt' - Then I am inserting the open graph meta via my functions.php
function insert_fb_in_head() {
    global $post;
    if ( !is_singular())
        return;

        echo '<meta property="og:description" content=" . $MyExcerptHere . "/>';

    echo "\n";
}
add_action( 'wp_head', 'insert_fb_in_head', 5 );

A: Why not simply use get_post ?
 $my_post = get_post($id);
 $excerpt = $my_post->post_excerpt;

Then use a function like this to retrieve words up to x characters:
  function extractText150char($text, $length = '150') {
    $textArr = explode(' ', $text);
    $text = '';

    // Loop through each word
    for ( $i=0; $i<count($textArr)-1; $i++ ) {
      $text .= $textArr[$i] . ' ';
      // Check string length
      if ( (strlen($text) + strlen($textArr[$i+1]) ) > $length )
        return $text;
    }
    return $text;
  }


text:
Q: UITapGestureRecognizer is not opening url I have created an action when tapping an image to open an URL in navigator but when I tap on it, nothing opens up. This is my code:
@IBAction func Anuncio(sender: UITapGestureRecognizer) {

    if let url = NSURL(string: "http://capturando.es/") {
        UIApplication.sharedApplication().openURL(url)

}
}

A: check once yourImagename.userInteractionEnabled  = true or false if it is false just enable once thereafter all other functions are automatically triggered
yourImagename.userInteractionEnabled  = true


text:
Q: Converting an SQL result into string format in Python I am trying to convert the result extracted from the execution of an SQL statement, to a string, as the output is in the tuple format. I am new to Python programming, so, I found a code in the internet that can convert a tuple to a string, but when I tried it out using the tuple gained from the SQL statement execution, the result remains unchanged. Can you please show me how to work it out as intended ? Below is the code that was used:
import functools
import operator
import mysql.connector

mydb = mysql.connector.connect(
      host='localhost',
      user='root',
      password='123456789',
      port='3307',
      database='magna'
)

def convertTuple(tup):
     str1 = functools.reduce(operator.add, (tup))
     return str1

#The converting function

mycusor = mydb.cursor()
mycusor.execute("SELECT Name FROM people WHERE ID =1")
para1 = mycusor.fetchall()

targ = para1
str2 = convertTuple(targ)
print(str2)

The result that was produced from the above code :
('Mike',)

A: para1 is a list of tuples.  To convert each tuple to a string we need to convert each element in the tuple to a string, then use str.join to combine them into a string.
Using map
joined_str = ', '.join(map(str, tup))

or a list comprehension
joined_str = ', '.join([str(elem) for elem in tup])

If you want to make the entire list into a string, you need to apply another layer of joining
joined_str = '\n'.join([', '.join(map(str, tup)) for tup in para1])

or
joined_str = '\n'.join([', '.join(str(elem) for elem in tup) for tup in para1])