text:
Q: c# Searching List inside another List How would I search for a value within a List<t> inside another List<t>
i.e.
//FooInner Class
public class FooInner {

  public int FooInnerId { get; set; }
  public String FooValue { get; set; }

}

//FooOuter Class
public class FooOuter {

  public int FooOuterId { get; set; }
  public List<FooInner> FooInnerCollection { get; set; }

}

If I just wanted to find a value in the outer class
// Working code

List<FooOuter> fooOuterCollection = GetSomeData();

var tmp = fooOuterCollection.Find( f => f.FooOuterId == 2 );

But what if I wanted the FooInner Object where FooOuterId == 2 and FooInnerCollection.FooInnerId == 4 (or contains depending how you look at it).
Hopefully that makes sense.

A: fooOuterCollection
    .Where(outer => outer.FooOuterID == 2)
    .SelectMany(outer => outer.FooInnerCollection)
    .FirstOrDefault(fooInner => fooInner.FooInnerId == 4);

First we filter the outer objects to only include those with Id == 2
Then we use SelectMany to flatten out the multiple InnerCollections that we may find
Finally we filter based on the inner Id == 4

A: You can get inner object like this-
var temp=  fooOuterCollection.Where(f => f.FooOuterId == 2)
            .SelectMany(f => f.FooInnerCollection)
            .FirstOrDefault(fi => fi.FooInnerId == 4));

If you need outer object, you need to use Any() extension method to see if inner list contains required element -
var temp = fooOuterCollection.FirstOrDefault(f => f.FooOuterId == 2 &&
               f.FooInnerCollection.Any(fi => fi.FooInnerId == 4);

A: You could just use LINQ's query syntax:
var results = from o in outerList
      where o.FooOuterId == 2
      from i in o.FooInnerCollection
      where i.FooInnerId == 4
      select i;


text:
Q: Red words only in css (SASS syntax) files with vim editor I try to remove the highlighted words with :set nospell command and I can't.
Examples:

I'm working with vim 7.4 on Archlinux with gnome-shell desktop.
Thanks! Any suggestion is accepted :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i link a submit button to my email address How do I use the submit button to send the form, when filled, to my email address?
MINIMALISTIC FORM
<form id="form" class="topBefore">

       <input id="name" type="text" placeholder="NAME">

          <input id="email" type="text" placeholder="E-MAIL">

          <textarea id="message" type="text" placeholder="MESSAGE"></textarea>

  <input id="submit" type="submit" value="GO!">

</form>

Thanks for your help!

A: You need PHP to submit the form data and send it to a specified email.
Take a look at this HTML example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Feedback Form</title>

<form action="send_simpleform.php" method="post">

Your name

<input name="sender_name" type="text" size="30" />

Email

<input name="sender_email" type="text" size="30" />

Message

<textarea name="message" cols="30" rows="5"></textarea>

<input name="submit" type="submit" value="Send This Form" />
</form>

Now take a look at this basic PHP example:
<?
if (($_POST[sender_name] == "") || ($_POST[sender_email] == "") || ($_POST[message] == "") {
    header("Location: simple_form.php");
    exit;
}

$msg = "Email sent from wwwsite\n";
$msg .= "Sender's Name:\t $_POST[senders_name]\n";
$msg .= "Sender's E-mail:\t $_POST[senders_email]\n";
$msg .= "Sender's Message:\t $_POST[message]\n";
$to = "jack@xxxxxxx.com.au";
$subject = "Website feedback message";
$mailheaders = "From: My web site <www.testwebsite.com>\n";
$mailherders .= "Reply to: $_POST[sender_email]\n";
$mail($to, $subject, $msg, $mailheaders);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Feedback Form Sent</title>

The following email has been sent

Your Name:

<? echo "$_POST[sender_name]"; ?>

Your Email Adress:

<? echo "$_POST[sender_email]"; ?>

Message:

<? echo "$_POST[message]"; ?>

Just found one here on SO to use as a quick example.
Keep in mind there are countless ways to do this, and no one is necessarily better than the other - it really just depends on the needs.
Source: HTML and PHP simple contact form

A: HTML does not have the ability to provide the server's capability of sending an email.
There are options available for your to send the mail, using an appliation server in the back end.
Currently what language/ application server are you using to listen to the request ? (Which server is sending this HTML page to be rendered on browser ?)


text:
Q: Merge 2 rows from 2 separate datagridviewrows into a new one vb.net I'm trying to merge two rows and write it to a new row on a third table:
Example:
TableA: (data is fixed)

 customer | name | last name
 1        | bob  | jansens
 2        | jan  | peeters
...       | ...  | ...

TableB: (data is fixed)

 age      | lenght | weight
 23       | 178    | 76
 75       | 165    | 86
...       | ...    | ...

Now, those two tables need to be merged like so:
TableC:

 customer | name | last name |  age   | lenght | weight
 1        | bob  | jansens   |  23    | 178    | 76
 2        | jan  | peeters   |  75    | 165    | 86
...       | ...  | ...       | ...    | ...    | ...

My code for now, even not working:
    Public Sub merge_BAK(adminis As DataGridView, kluwer As DataGridView, merged As DataGridView)
    Dim adminis_header_count As Integer = adminis.Columns.Count
    Dim kluwer_header_count As Integer = kluwer.Columns.Count
    Dim diff_header_count As Integer = kluwer.Columns.Count - adminis.Columns.Count
    Dim total_header_count As Integer = adminis_header_count + kluwer_header_count
    For Each adminis_row As DataGridViewRow In adminis.Rows
        If adminis_row.IsNewRow = False Then

            Dim btw As String = adminis_row.Cells(4).Value()

            If btw IsNot String.Empty Then
                btw = btw.Remove(0, 3)

                For Each kluwer_row As DataGridViewRow In kluwer.Rows
                    Dim venn_onderneming As String = kluwer_row.Cells(44).Value()
                    If btw = venn_onderneming Then

                        merged.ColumnCount = total_header_count

                        Dim merge_row As DataGridViewRow = CType(adminis_row.Clone(), DataGridViewRow)
                        For i As Integer = 0 To adminis_row.Cells.Count - 1
                            merge_row.Cells(i).Value = adminis_row.Cells(i).Value
                        Next

                        merged.Rows.Add(merge_row) 'somewhere here the current row (kluwer_row) needs to be placed behind the current row of the previous table (adminis_row)

                    End If
                Next kluwer_row
            End If
        End If
    Next adminis_row
End Sub

Does anybody have an idea how to achieve this?

A: You can use SQL server "VIEWs"

To achieve that, just drag and drop both tables in your pane and join them


text:
Q: Android : setAlarmManager(...) open an activity instead of delaying the opening In android, I have to set an alarm at a special hour that will ring and open an activity at the correct time of the day.
My problem is that the function "alarmManager.set(...)" OPEN INSTANTLY the targeted activity and, when the time is reached, open again the same activity.
I don't understand why this happening how can I correct it ?
Current State : I have a timepicker which help me to select the time. I also have a button which call the function alarmManager.set() when I click on it by retrieving the time from the timepicker and calculate the next alarm in ms.
Thx
Code of the button :
public void setTheAlarm(View view) {

    TimePicker tp_clock = (TimePicker) findViewById(R.id.tp_timeToRing);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int alarmHours = tp_clock.getCurrentHour();
    int alarmMinutes = tp_clock.getCurrentMinute();

    Toast.makeText(this, "Alarm set for " + alarmHours + "h" + alarmMinutes, Toast.LENGTH_LONG).show();

    Long time = calculateTime(alarmHours, alarmMinutes);
    alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}

Code of the function calculateTime :
public Long calculateTime(int alarmHours, int alarmMinutes) {

    Calendar c = Calendar.getInstance();
    int currentHours = c.get(Calendar.HOUR);
    if (c.get(Calendar.AM_PM) == 1)
        currentHours +=12;
    int currentMinutes = c.get(Calendar.MINUTE);
    int setAlarmHours = 0;
    int setAlarmMinutes = 0;
    int balanceWithMinute = 0;

    if (alarmMinutes >= currentMinutes) {

        setAlarmMinutes = alarmMinutes - currentMinutes;
    }
    else {

        setAlarmMinutes = (60 - currentMinutes) + alarmMinutes;
        balanceWithMinute = 1;
    }
    if (alarmHours > currentHours)
        setAlarmHours = alarmHours - currentHours;

    if (alarmHours < currentHours)
        setAlarmHours = (24 - currentHours) +alarmHours - balanceWithMinute;

    if (alarmHours == currentHours && balanceWithMinute == 1)
        setAlarmHours = 23;

    Long time = new GregorianCalendar().getTimeInMillis()+setAlarmHours*setAlarmMinutes*60*1000;
    return time;
}

Code of the alarmManager :
package fr.pixelcraft.victor.wackertest.SoundPackage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import fr.pixelcraft.victor.wackertest.LoginActivity;

public class AlarmReciever extends BroadcastReceiver {

    private String userToken;
    private String userId;

    @Override
    public void onReceive(Context context, Intent intent) {

        Intent i=new Intent(context, PlanASoundActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        userToken = intent.getStringExtra(LoginActivity.USER_TOKEN);
        userId = intent.getStringExtra(LoginActivity.USER_ID);

        i.putExtra(LoginActivity.USER_TOKEN, userToken);
        i.putExtra(LoginActivity.USER_ID, userId);
        context.startActivity(i);

        Toast.makeText(context, "Alarm triggered", Toast.LENGTH_LONG).show();
    }
}

A: By https://stackoverflow.com/users/2649012/frank-n-stein:
Probably you set a time which is already past. This makes the AlarmManager fire immediately. –


text:
Q: Vb.net crystal report not displaying the items I am trying to display all of the purchases in an inventory system but it is not displaying in my crystal report PS: this my first time using Crystal Report
 here's my code:
    Dim show As String = String.Empty
        show &= "select * from purchase_report "
        show &= "where buildnumber=@build"

        Using conn As New SqlConnection("Server=WIN10;database=purchase_stock;user=admin_report;password=54321")
            Using cmd As New SqlCommand
                With cmd
                    .Connection = conn
                    .CommandType = CommandType.Text
                    .CommandText = show
                    .Parameters.AddWithValue("@build", report.Text)
                End With

                Try
                    conn.Open()

                    Dim da As New SqlDataAdapter(cmd)
                    Dim ds As New DataSet
                    da.Fill(ds)

                    If ds.Tables.Count > 0 Then
                        CrystalReportViewer1.ReportSource = ds.Tables.Count
                    End If
                    conn.Close()
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            End Using
        End Using

    End Sub
End Class

A: Try this code :
Change it as per your needs
Friend Function ViewReport(ByVal sReportName As String, _
    Optional ByVal sSelectionFormula As String = "", _
    Optional ByVal param As String = "") As Boolean

    'Declaring variables
    Dim intCounter As Integer
    Dim intCounter1 As Integer

    'Crystal Report's report document object
    Dim objReport As New _
        CrystalDecisions.CrystalReports.Engine.ReportDocument

    'object of table Log on info of Crystal report
    Dim ConInfo As New CrystalDecisions.Shared.TableLogOnInfo

    'Parameter value object of crystal report
    ' parameters used for adding the value to the parameter.
    Dim paraValue As New CrystalDecisions.Shared.ParameterDiscreteValue

    'Current parameter value object(collection) of crystal report parameters.
    Dim currValue As CrystalDecisions.Shared.ParameterValues

    'Subreport object of crystal report.
    Dim mySubReportObject As _
        CrystalDecisions.CrystalReports.Engine.SubreportObject

    'Sub report document of crystal report.
    Dim mySubRepDoc As New _
        CrystalDecisions.CrystalReports.Engine.ReportDocument

    Dim strParValPair() As String
    Dim strVal() As String
    Dim index As Integer

    Try

        'Load the report
        objReport.Load(sReportName)

        'Check if there are parameters or not in report.
        intCounter = objReport.DataDefinition.ParameterFields.Count

        'As parameter fields collection also picks the selection
        ' formula which is not the parameter
        ' so if total parameter count is 1 then we check whether
        ' its a parameter or selection formula.

        If intCounter = 1 Then
            If InStr(objReport.DataDefinition.ParameterFields(_
                0).ParameterFieldName, ".", CompareMethod.Text) > 0 Then
                intCounter = 0
            End If
        End If

        'If there are parameters in report and
        'user has passed them then split the
        'parameter string and Apply the values
        'to their concurrent parameters.

        If intCounter > 0 And Trim(param) <> "" Then
            strParValPair = param.Split("&")

            For index = 0 To UBound(strParValPair)
            If InStr(strParValPair(index), "=") > 0 Then
                strVal = strParValPair(index).Split("=")
                paraValue.Value = strVal(1)
                currValue = _
                    objReport.DataDefinition.ParameterFields(_
                    strVal(0)).CurrentValues
                currValue.Add(paraValue)
                objReport.DataDefinition.ParameterFields(_
                    strVal(0)).ApplyCurrentValues(currValue)
            End If
        Next
    End If

    'Set the connection information to ConInfo
    'object so that we can apply the
    'connection information on each table in the report
    ConInfo.ConnectionInfo.UserID = <User Name>
    ConInfo.ConnectionInfo.Password = <Password>
    ConInfo.ConnectionInfo.ServerName = <Server Name>
    ConInfo.ConnectionInfo.DatabaseName = <Database Name>

    For intCounter = 0 To objReport.Database.Tables.Count - 1
        objReport.Database.Tables(intCounter).ApplyLogOnInfo(ConInfo)
    Next

    ' Loop through each section of the report then look
    ' through each object in the section
    ' if the object is a subreport, then apply login info
    ' on each table of that subreport

        For index = 0 To objReport.ReportDefinition.Sections.Count - 1
            For intCounter = 0 To _
                objReport.ReportDefinition.Sections(_
                index).ReportObjects.Count - 1
            With objReport.ReportDefinition.Sections(index)
                If .ReportObjects(intCounter).Kind = _
                CrystalDecisions.Shared.ReportObjectKind.SubreportObject Then
                    mySubReportObject = CType(.ReportObjects(intCounter), _
                      CrystalDecisions.CrystalReports.Engine.SubreportObject)
                    mySubRepDoc = _
             mySubReportObject.OpenSubreport(mySubReportObject.SubreportName)
                 For intCounter1 = 0 To mySubRepDoc.Database.Tables.Count - 1
                       mySubRepDoc.Database.Tables(_
                           intCounter1).ApplyLogOnInfo(_
                           ConInfo)sp;
                       mySubRepDoc.Database.Tables(_
                           intCounter1).ApplyLogOnInfo(ConInfo)
                 Next
                 End If
             End With
         Next
     Next
    'If there is a selection formula passed to this function then use that
    If sSelectionFormula.Length > 0 Then
        objReport.RecordSelectionFormula = sSelectionFormula
    End If
    'Re setting control
    rptViewer.ReportSource = Nothing

    'Set the current report object to report.
    rptViewer.ReportSource = objReport

    'Show the report
    rptViewer.Show()
        Return True
    Catch ex As System.Exception
        MsgBox(ex.Message)
    End Try
End Function


text:
Q: Putting mechanism in-between multiple implementations of the abstract class I am working in .NET 4.5 WPF application I have 3 views that are using containers with questions. 2 views have one set of questions and I am now working on adding another one that has 2 containers of questions as it is for two customers at once.
Class structure:
QuestionItem that is any question that is placed into the viewModel.
public abstract class QuestionItemViewModel : ValidatingScreen, IHandle<ValidatingEventArgs>,
    IEquatable<QuestionItemViewModel>{
public event QuestionAnsweredEventHandler AnsweredHandler;
public abstract string GetQuestionAnswer();
public abstract bool HasAnswer { get; }
public virtual void OnAnswered(EventArgs e)
    {
        if (this.AnsweredHandler != null)
            this.AnsweredHandler(this, e);
    }
}

then 4 types of questions, I am going to show 1 to save space but they all look the same.
Concrete implementation of question that is placed into viewModel (this is dropdown)
public class QuestionDropDownViewModel : QuestionItemViewModel, IEquatable<QuestionDropDownViewModel>
{
public string SelectedAnswer
    {
        get
        {
            if (this._selectedAnswer.IsNullOrEmpty())
                this._selectedAnswer = this.QuestionAnswerList.FirstOrDefault();

            return this._selectedAnswer;
        }
        set
        {
            if (this._selectedAnswer != value)
            {
                this._selectedAnswer = value;

                if (this._isInitialised)
                {
                    this.IsDirty = true;
                    this.NotifyOfPropertyChange(() => this.SelectedAnswer);
                    this._eventAggregator.Publish(new QuotePropertyChangedEvent(true));
                    this.OnAnswered(EventArgs.Empty);
                }
            }
        }
    }

    public override string GetQuestionAnswer()
    {
        return this.SelectedAnswer;
    }

    public override bool HasAnswer
    {
        get { return !string.IsNullOrWhiteSpace(this.SelectedAnswer) && this.SelectedAnswer != "please select an item"; }
    }

in two views that have one set of questions QuestionItemViewModel are being placed in  this.QuestionItems = new CustomerQuestionCollection(){CustomerId = this.CurrentTransactionDetail.TransactionMain.CustomerID};.
Since view I am working on must have 2 collections there's additional collection this.QuestionItemsForSecondCustomer = new CustomerQuestionCollection() {CustomerId = this.CurrentTransactionDetail.TransactionWill.SecondCustomerId};
Questions are not being asked all at once but rather when question is answered dropdownQuestion.AnsweredHandler += Quesion_AnsweredHandler; is being fired on viewModel to look for next question based on previous answer.
protected override void Quesion_AnsweredHandler(object sender, EventArgs e)
    {
        var questionViewModel = sender as QuestionItemViewModel;
        if (questionViewModel != null)
        {
            this.EvaluateAndAddNextQuestion(questionViewModel);
            this.NotifyParent();
        }
    }

The problem: to start filling in second container I am checking if last question of first container has been answered and if it is I switch to second container
private void EvaluateAndAddNextQuestion(QuestionItemViewModel questionViewModel)
    {
        var collectionToBeFilled = this.IsWifForSecondCustomerVisible
            ? this.QuestionItemsForSecondCustomer
            : this.QuestionItems;

        this.ClearNextQuestions(collectionToBeFilled, questionViewModel);

        if (!(questionViewModel is QuestionDropDownViewModel) || (questionViewModel.HasAnswer))
        {
            this.AddNextQuestion(collectionToBeFilled, questionViewModel);
        }

        NotifyOfPropertyChange(() => IsVisibleQuestionItemsForSecondCustomer);
        NotifyOfPropertyChange(() => QuestionItems);
        NotifyOfPropertyChange(() => QuestionItemsForSecondCustomer);
    }

however after I started filling in QuestionItemsForSecondCustomer if first container(QuestionItems) then gets modified I am unable to tell if it was the item from first or second container that fired Quesion_AnsweredHandler. This requires me to introduce some coupling between container and item inside container, loosest in my eyes is introducing CustomerId to QuestionItemViewModel, as I have CustomerId in container already and could identify if it was question from this.QuestionItems or this.QuestionItemsForSecondCustomer.
Question: Is there a way to introduce additional class out of QuestionItemViewModel like CustomerQuestionItemViewModel (or some other mechanism) that would have CustomerId that could sit inbetween 4 types of questions (QuestionDropDownViewModel,QuestionRadioGroupViewModel,..) that would not require me to make duplicates of those 4 classes e.g QuestionDropDownViewModel to CustomerQuestionDropDownViewModel but would still allow me to have CustomerId on them.
Immediate solution would be to add CustomerId to QuestionItemViewModel but it would leak the implementation of submechanism that doesn't belong here to base class, which I would like to avoid. Question is complicated if some part is unclear please let me know I will do my best to add missing detail.


text:
Q: Java: system.out.println concatenating something within a string (really easy question) I want my output to be Candy[1].
counterInt = 1
But my compiler isn't taking this code:
   System.out.println("Candy["+counterInt"]");

What can I do to have this variable appear within the string Candy[]?
Candy[] is not an array, it's a string.

A: You must put a + after counterInt:
System.out.println("Candy["+counterInt+"]");

A: System.out.println("Candy["+counterInt+"].counterInt="+counterInt);

A: you should have  System.out.println("Candy[" + counterInt + "].counterInt = " + counterInt); to get Candy[1]. counterInt = 1;

A: You are missing a + after CounterInt.

A: System.out.println("Candy["+counterInt+"]");


text:
Q: Probability with real number There are two sets of real numbers: $S_1 = [0, N_1]$, $S_2 = [0, N_2]$, where $N_1$ and $N_2$ are positive integers.
From $S_1$ a value $x_1$ and from $S_2$ a value $x_2$ is chosen.
What will be the probability that $x_1 + x_2 < y$, where $y$ is an integer number?

A: Compute the area $A(y)$ of the polygon $Q(y)$ defined by the equations $0\leqslant x_1\leqslant N_1$, $0\leqslant x_2\leqslant N_2$, $x_1+x_2\leqslant y$. The answer is $A(y)/(N_1N_2)$.
Note that $Q(y)$ is:

*

*a triangle for $0\leqslant y\leqslant\min\{N_1,N_2\}$, with area $A(y)=\frac12y^2$,

*a quadrilateral if $\min\{N_1,N_2\}\lt y\leqslant\max\{N_1,N_2\}$,

*a pentagon if $\max\{N_1,N_2\}\lt y\lt N_1+N_2$,

*the whole rectangle $[0,N_1]\times[0,N_2]$ if $y\geqslant N_1+N_2$, with area $A(y)=N_1N_2$.


text:
Q: Hazelcast Spring integration issue I am integrating Hazelcast and Spring. Its giving me error regarding the Schema.
Checked the spring and hazelcast version, still not sure why.

Spring Version : 3.2.8 HazelCast Version : 3.5

My applicationContext:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:hz="http://www.hazelcast.com/schema/spring"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.hazelcast.com/schema/spring http://hazelcast.com/schema/spring/hazelcast-spring-3.5.xsd">

    <context:component-scan base-package="com.hazel.hazelcastSpringBasic" />

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:/hazelcast-config.properties</value>
            </list>
        </property>
    </bean>

    <bean class="hazelcastSrpingBasic.TestBean" name="springTestBean">
        <property name="result" value="${value}" />
    </bean>

    <hz:hazelcast id="instance">
        <hz:config>
            <hz:group name="${name}" password="${password}" />
            <hz:properties>
                <hz:property name="hazelcast.merge.first.run.delay.seconds">5</hz:property>
                <hz:property name="hazelcast.merge.next.run.delay.seconds">5</hz:property>
            </hz:properties>
            <hz:network port="${defaultPort}" port-auto-increment="true">
                <hz:join>
                    <hz:multicast enabled="true" />
                </hz:join>
            </hz:network>
        </hz:config>
    </hz:hazelcast>

    <hz:client id="client">
        <hz:group name="${name}" password="${password}" />
        <hz:network>
            <hz:member>127.0.0.1:5705</hz:member>
        </hz:network>
    </hz:client>

    <hz:map id="map" instance-ref="instance" name="Map" lazy-init="false" />
    <hz:multiMap id="multiMap" instance-ref="instance" name="Multimap" />
    <hz:replicatedMap id="replicatedMap" instance-ref="instance"
        name="ReplicatedMap" />
    <hz:queue id="queue" instance-ref="instance" name="Queue" />
    <hz:topic id="topic" instance-ref="instance" name="Topic"
        depends-on="instance, client" />
    <hz:set id="set" instance-ref="instance" name="Set" />
    <hz:list id="list" instance-ref="instance" name="List" />
    <hz:executorService id="executorService"
        instance-ref="instance" name="ExecutorService" />
    <hz:idGenerator id="idGenerator" instance-ref="instance"
        name="IdGenerator" />
    <hz:atomicLong id="atomicLong" instance-ref="instance"
        name="atomicLong" />
    <hz:atomicReference id="atomicReference"
        instance-ref="instance" name="atomicReference" />
    <hz:countDownLatch id="countDownLatch" instance-ref="instance"
        name="countDownLatch" />
    <hz:semaphore id="semaphore" instance-ref="instance" name="semaphore" />
    <hz:lock id="lock" instance-ref="instance" name="lock" />
</beans>

Error I am getting while compilation :
Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 2 in XML document from class path resource [applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; systemId: http://hazelcast.com/schema/spring/hazelcast-spring-3.5.xsd; lineNumber: 2; columnNumber: 35; s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw '301 Moved Permanently'.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
    at org.springframework.context.support.GenericXmlApplicationContext.load(GenericXmlApplicationContext.java:115)
    at org.springframework.context.support.GenericXmlApplicationContext.<init>(GenericXmlApplicationContext.java:69)
    at hazelcastSpringBasic.SpringClient.main(SpringClient.java:26)
Caused by: org.xml.sax.SAXParseException; systemId: http://hazelcast.com/schema/spring/hazelcast-spring-3.5.xsd; lineNumber: 2; columnNumber: 35; s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw '301 Moved Permanently'.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.xs.opti.SchemaDOMParser.characters(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanContent(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.impl.xs.opti.SchemaParsingConfig.parse(Unknown Source)
    at org.apache.xerces.impl.xs.opti.SchemaParsingConfig.parse(Unknown Source)
    at org.apache.xerces.impl.xs.opti.SchemaDOMParser.parse(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.getSchemaDocument(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.parseSchema(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaLoader.loadSchema(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.findSchemaGrammar(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)
    ... 9 more

Thanks in advance.

A: Does it work for you if you change the last line of the schema instance
from
http://www.hazelcast.com/schema/spring http://hazelcast.com/schema/spring/hazelcast-spring-3.5.xsd">

to
http://www.hazelcast.com/schema/spring https://hazelcast.com/schema/spring/hazelcast-spring-3.5.xsd">
?
The xsi:schemaLocation section is problematic.
The line referenced above is missing www for the second URL.
The second URL in the XML file is
http://hazelcast.com/schema/spring/hazelcast-spring-3.5.xsd
and should be
http://www.hazelcast.com/schema/spring/hazelcast-spring-3.5.xsd

A: You need to add hazelcast-spring project to your classpath.
<dependency>
   <groupId>com.hazelcast</groupId>
   <artifactId>hazelcast-spring</artifactId>
   <version>3.5</version>
</dependency>


text:
Q: Upgrade address pymodbus How can I update the address of a server configured in pymodbus, if the program is running? I tried to stop the server and start it again but an error occurs.
Any suggestions?

A: If you are working in Linux and killing your server without proper shutdown you have to write exit in your console for the socket get flushed.
For windows you will probably have to close the console windows completely.
It would help if you handle how you close the connection, or maybe even reuse your socket, see here:
How to close socket connection on Ctrl-C in a python programme


text:
Q: Connecting to Oracle12C database using standalone java client Vs Connecting through Websphere Connection to Oracle 12c from a standalone java application succeeds when ojdbc6.jar or ojdbc5.jar is used.
Connection String : jdbc:oracle:thin:@serverName:port:sid
Whereas the same connection string fails when connecting through Websphere with the following exception.

java.sql.SQLException: ORA-28040: No matching authentication protocol
  DSRA0010E: SQL State = 99999, Error Code = 28,040

Note : Tried ojdbc8.jar and ojdbc6.jar

A: The ORA-28040: No matching authentication protocol error generally indicates that you are using an older JDBC driver with a newer database.  You should either update your JDBC driver so that it is the same version as the database or update your sqlnet.ora file with the appropriate SQLNET.ALLOWED_LOGON_VERSION_SERVER/SQLNET.ALLOWED_LOGON_VERSION_CLIENT values. See Oracle's SQLNET documentation for more information.
Note that if you think you are using the same version JDBC driver as the database it is possible that a different JDBC driver is being picked up in the WebSphere environment. If that is the case:

*

*Check that there are no additional JDBC drivers packaged with your application.

*Check if there are other Oracle JDBC Providers configured in WebSphere using an older JDBC driver. If so either modify your configuration so all of your providers are using the same version Oracle JDBC driver or you will need to Isolate your JDBC Providers.


text:
Q: gevent not valid running Docker Registry I am attempting to run a Docker registry on Ubuntu 14 using the following command:
sudo gunicorn --access-logfile - --debug -k gevent -b 0.0.0.0:5000 -w 1 docker_registry.wsgi:application

Unfortunately, when I attempt this I get the following failure message:
Error: class uri 'gevent' invalid or not found:

[Traceback (most recent call last):

  File "/usr/local/lib/python2.7/dist-packages/gunicorn/util.py", line 139, in load_class

    mod = import_module('.'.join(components))

  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module

    __import__(name)

  File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/ggevent.py", line 24, in <module>

    from gevent.server import StreamServer

  File "/usr/local/lib/python2.7/dist-packages/gevent/server.py", line 6, in <module>

    from gevent.socket import EWOULDBLOCK, socket

  File "/usr/local/lib/python2.7/dist-packages/gevent/socket.py", line 659, in <module>

    from gevent.ssl import sslwrap_simple as ssl, SSLError as sslerror, SSLSocket as SSLType

  File "/usr/local/lib/python2.7/dist-packages/gevent/ssl.py", line 386, in <module>

    def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):

NameError: name 'PROTOCOL_SSLv3' is not defined

I did some searching and discovered something that told me to install python-gevent in order to get the gevent:
sudo apt-get install python-gevent

I did this and a subsequent invocation of dpkg:
dpkg -l|grep python

shows that python-gevent is installed.
Unfortunately, the install has not resolved the problem. I am still getting the same failure message saying that gevent isn't valid or found.
Does anyone know how to resolve this problem??? Please advise...

A: re-Install python-gevent
apt-get install python-gevent
pip install --upgrade gevent

A: try it:
1.find your python gevent package folder:
$ cd /usr/local/lib/python2.7/dist-packages/gevent

2.update ssl.py
from:
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):

to:
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):

3.try again:
$sudo gunicorn --access-logfile - --debug -k gevent -b 0.0.0.0:5000 -w 1 docker_registry.wsgi:application

A: If you're getting this in late 2022 or later, know that gevent versions 20.9.0 and earlier depend on greenlet, without specifying an upper bound on that version. greenlet has just released a breaking change in v2.x.x, and gevent doesn't work with it.
Pinning greenlet=1.1.3 fixed it for me. More details about this issue here: https://github.com/python-greenlet/greenlet/issues/178


text:
Q: Constraining dynamic sized views to bottom of a view in ConstraintLayout I have a layout with design requirement like :

The close button has to be on top, and below it are the ImageView and TextView. The TextView's size is dynamic, depending on what was saved in the database. Both ImageView and TextView has to be below close button like the first image, and :

If it were the other way around, I can just use Barrier with bottom direction and refer the ids of ImageView and TextView for the close button to position itself to, but it's the other way around now.
Is there any way to do this view without nesting ImageView and TextView in another layout, say, LinearLayout? Trying to achieve non nested views as I am using ConstraintLayout..
Thanks in advance!
EDIT :
Here's a testlayout
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingTop="20dp"
    android:paddingRight="16dp">

    <ImageView
        android:id="@+id/waste_type_close"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:src="@drawable/ic_account_alert_grey600_24dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/waste_type_image"
        android:layout_width="84dp"
        android:layout_height="84dp"
        android:layout_marginLeft="20dp"
        android:src="@drawable/ic_account_alert_black_48dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/waste_type_close" />

    <TextView
        android:id="@+id/waste_type_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="12dp"
        android:text="name"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/waste_type_image"
        app:layout_constraintLeft_toRightOf="@+id/waste_type_image"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/waste_type_image" />

</ConstraintLayout>

EDIT :
This is another testlayout :
<ImageView
    android:id="@+id/waste_type_close"
    android:layout_width="24dp"
    android:layout_height="24dp"
    android:src="@drawable/ic_account_alert_grey600_24dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/waste_type_barrier"/>

<ImageView
    android:id="@+id/waste_type_image"
    android:layout_width="84dp"
    android:layout_height="84dp"
    android:layout_marginLeft="20dp"
    android:src="@drawable/ic_account_alert_black_48dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/waste_type_close" />

<TextView
    android:id="@+id/waste_type_name"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="12dp"
    android:text="nameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    android:textSize="30sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="@+id/waste_type_image"
    app:layout_constraintLeft_toRightOf="@+id/waste_type_image"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/waste_type_image" />

<android.support.constraint.Barrier
    android:id="@+id/waste_type_barrier"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:barrierDirection="top"
    app:constraint_referenced_ids="waste_type_image, waste_type_name"/>

Which yields :

A: Placing a barrier constrained to below close button and placing a constraint where below items(imageview and textview) are constrained to the bottom of the barrier should do it.  For the dynamic textview just create a constraint on Imageview with respect to start of textview.

A: I believe that this layout is not possible using only a ConstraintLayout with three children.
Despite the fact that "the point" of ConstraintLayout is to avoid nested views, sometimes that's the only way to get what you want. Here, I think you should wrap waste_type_image and waste_type_name in a LinearLayout.
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="20dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <ImageView
        android:id="@+id/waste_type_close"
        android:layout_width="24dp"
        android:layout_height="24dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:srcCompat="@drawable/ic_delete_24dp"/>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        app:layout_constraintTop_toBottomOf="@+id/waste_type_close"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

        <ImageView
            android:id="@+id/waste_type_image"
            android:layout_width="84dp"
            android:layout_height="84dp"
            android:layout_marginLeft="20dp"
            app:srcCompat="@drawable/ic_share_24dp"/>

        <TextView
            android:id="@+id/waste_type_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="12dp"
            android:textSize="30sp"
            android:textStyle="bold"
            android:text="name"/>

    </LinearLayout>

</android.support.constraint.ConstraintLayout

A: You can use SequenceLayout to achieve this.
There is already a sample there for a similar problem. (Check Use Android's ConstraintLayout to create table-like view)
Following is how you get to do it:
<com.yashoid.sequencelayout.SequenceLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:pgSize="360"
    app:sequences="@xml/sequences">

    <ImageView
        android:id="@+id/waste_type_close"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:src="@drawable/ic_account_alert_grey600_24dp"/>

    <View
        android:id="@+id/helper"
        android:layout_width="0dp"
        android:layout_height="0dp"/>

    <ImageView
        android:id="@+id/waste_type_image"
        android:layout_width="84dp"
        android:layout_height="84dp"
        android:src="@drawable/ic_account_alert_black_48dp"/>

    <TextView
        android:id="@+id/waste_type_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="name"
        android:textSize="30sp"
        android:textStyle="bold"/>

</com.yashoid.sequencelayout.SequenceLayout>

Your @xml/sequences will be like this:
<Sequences>
    <Horizontal>

    </Horizontal>

    <Horizontal>

    </Horizontal>

    <Vertical>

    </Vertical>

    <Vertical start="start@helper" end="end@helper">

    </Vertical>

    <Vertical id="waste_type_name_sequence" start="start@helper" end="end@helper">

    </Vertical>
</Sequences>


text:
Q: Azure Logic Apps, SQL Update Row v2 I am trying to add an additional task to update a row in SQL Server after sending an email via sendgrid.
The options for updating a row seem to be missing the column name and value. The only additional parameter that can be added is called 'raw inputs' which isn't in the MS documentation.
Completing the available fields and running the process it correctly recognises the rowid that I would expect but I get this error:

A value must be provided for item.

I can't see where I could provide that value or the column in the row it should be applied to.
Has anyone got this working?
https://learn.microsoft.com/en-gb/connectors/sql/#update-row-(v2)

A: Yes it will only show the Row id, you need to choose Add new parameter then it will show Raw inputs, it's used to define the value you want to update.
Like the below pic, in my table there are visit_id and test two property, and then I update the test value with visit_id equal to 2.

In the Raw inputs I use the json data .
{"test":"123"}

Below is my test result, hope this could help you.


text:
Q: error in if-statement, requires scalar logical expression Within a subroutine I try to create a statement, however it will only work if I enter a number directly, as soon as I replace the number with a variable, it will give the error:
||Error: IF clause  requires a scalar LOGICAL expression|

In this example var is a real number between 0 and 1.
    if ( var%type3 < 0.5) then
            test = 1
    end if

where the type3 component is declared as
    real, dimension(1,1) :: type3

Does someone maybe know what we are doing wrong. Because the error does not give us any clues which part of the statement is wrong.

A: You try to use a DIMENSION(1, 1) type as a REAL.
You shoul add (1, 1) to access to yout REAL contained in the DIMENSION(1, 1)
Use :
  IF ( var%type3(1, 1) < 0.5 ) THEN
     print *, 'IT WORKS'
  END IF

Exemple to get this error :
MODULE vardef
  TYPE vartype
     REAL :: type3(1, 1)
  END TYPE vartype
END MODULE vardef

PROGRAM test
  USE vardef

  TYPE(vartype) var

  var%type3(1, 1) = 0

  IF ( var%type3 < 0.5 ) THEN
     print *, 'IT WORKS'
  END IF
  RETURN

END PROGRAM test

A: From your comment var%type3 is a real, dimension(1,1).  This isn't scalar, and var%type3 < 0.5 will be an array of the same shape.
As the error message states, the test condition for the if should be scalar logical.  Depending on what you want to do your test condition can be one of a non-exhaustive list:

*

*var%type3(1,1) < 0.5

*ALL(var%type3 < 0.5)

*ANY(var%type3 < 0.5)
The first case seems natural as it is a scalar condition, but I leave the others as you may well be expanding to cases where it isn't a (1,1) array.


text:
Q: How many iterations does the scram-sha-256 setting use in PostgreSQL 10? How many iterations does the scram-sha-256 setting use in PostgreSQL 10?
The docs just say

Setting this parameter to scram-sha-256 will encrypt the password with SCRAM-SHA-256.

The build log reads.

Add SCRAM-SHA-256 support for password negotiation and storage (Michael Paquier, Heikki Linnakangas) This proves better security than the existing md5 negotiation and storage method.

A: It's a compile-time variable in scram-common.h known as SCRAM_ITERATIONS_DEFAULT. Currently it's set to 4096.
That's substantially under the specs "rule of thumb" which is cited in Nov 2015 as being 15,000. It's currently the lowest value for permissible iterations. From RFC-7677

The strength of this mechanism is dependent in part on the hash
iteration-count, as denoted by "i" in [RFC5802].  As a rule of thumb,
the hash iteration-count should be such that a modern machine will
take 0.1 seconds to perform the complete algorithm; however, this is
unlikely to be practical on mobile devices and other relatively low-
performance systems.  At the time this was written, the rule of thumb
gives around 15,000 iterations required; however, a hash iteration-
count of 4096 takes around 0.5 seconds on current mobile handsets.
This computational cost can be avoided by caching the ClientKey
(assuming the Salt and hash iteration-count is stable).  Therefore,
the recommendation of this specification is that the hash iteration-
count SHOULD be at least 4096, but careful consideration ought to be
given to using a significantly higher value, particularly where
mobile use is less important.


text:
Q: How to set the searchBar as the global focus for Siri on the Search Page? Description
In my tvOS application, I have a search page with on top a Search Bar and under a Table View with the eventual list of results.
While we are focusing the searchBar and the user presses the voice for Siri, the results get inserted into the Search Bar (as expected). However, when the user is scrolling down through the results and is unable to find what they're looking for, they have to scroll up (all the way back up) to the searchBar to use Siri again.
If the user attempts to use Siri while the searchBar is NOT in focus, a global Siri starts looking for results in different apps (which is not what I want)
Question:
How to set the searchBar as the global focus for Siri on the Search Page?
What I've tried:
To be honest I have no idea how to go about this..
A function is called in AppDelegate.swift to create the Search View Controller and add it to the Tab Bar Controller.
I've thought about trying preferedFocusView but after reading the documentation, I doubt that's going to work.
func configueSearchController() -> UIViewController {

        let storyboard = UIStoryboard(name: "Search", bundle: nil)
        guard let searchResultsController = storyboard.instantiateViewController(withIdentifier: SearchViewController.storyboardIdentifier) as? SearchViewController else {
            fatalError("Unable to instatiate a SearchResultViewController from the storyboard.")
        }

        /*
         Create a UISearchController, passing the `searchResultsController` to
         use to display search results.
         */

        let searchController = UISearchController(searchResultsController: searchResultsController)
        searchController.searchResultsUpdater = searchResultsController
        searchController.searchBar.placeholder = NSLocalizedString("Enter keyword (e.g. Gastric Bypass)", comment: "")
        searchController.view.backgroundColor = Constants.Color.backgroundcolor
        searchController.searchBar.keyboardAppearance = UIKeyboardAppearance.dark
        searchController.searchBar.tintColor = Constants.Color.backgroundcolor
        searchController.searchBar.backgroundColor = Constants.Color.backgroundSearchBarColor
        searchController.searchBar.setTextColor(color: .white)
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.obscuresBackgroundDuringPresentation = true
        searchController.searchBar.searchBarStyle = .minimal
        searchController.searchBar.sizeToFit()
        searchController.searchBar.focus

        //TODO: Check if this works
        searchController.searchBar.accessibilityLanguage = "en"

        //searchResultsController.tableView.tableHeaderView = searchController.searchBar

        // Contain the `UISearchController` in a `UISearchContainerViewController`.
        let searchContainer: UISearchContainerViewController = UISearchContainerViewController(searchController: searchController)

        // Finally contain the `UISearchContainerViewController` in a `UINavigationController`.
        let searchNavigationController = UINavigationController(rootViewController: searchContainer)
        searchNavigationController.navigationBar.isTranslucent = true
        searchNavigationController.navigationBar.tintColor = Constants.Color.backgroundcolor
        searchNavigationController.tabBarItem.title = "Search"
        return searchNavigationController

}

A: Please read http://nerds.airbnb.com/tvos-focus-engine/ to make controls focusable.


text:
Q: Organizing Cloud Functions for Firebase I want to organize my firestore cloud function so that every function in a separate file, i found a great article here
and i use this code
const files = glob.sync('./**/*.f.js', { cwd: __dirname, ignore: './node_modules/**' })
for (let f = 0, fl = files.length; f < fl; f++) {
    const file = files[f]
    const functionName = camelCase(file.slice(0, -5).split('/').join('_')) // Strip off '.f.js'
    if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === functionName) {
        console.log(functionName+": "+file)
        // tslint:disable-next-line: no-var-requires
        exports[functionName] = require(file)
    }
}

I organized my functions in this way and work correctly but in console shows something that i don't understand why this happened.
in the console shows that every function are exported multiple times
for example i have 2 functions inside dbID folder when deployed it shows something like that
https://i.stack.imgur.com/sUrNW.png
if you see that every function also export all other functions inside other directory
My question is this can make problem ? or any performance issue ? or any better way to organize functions without grouping ?
thanks

A: What you're looking at is just the output of console.log() in your code.  For all code that executes at the global scope of your functions, it will get executed for every function executed in your index.js.  If you don't want to see that output in the log, just remove the call to console.log().

A: I wrote a simple module / npm package called better-firebase-functions
Simply npm i better-firebase-functions, and then:
import exportCloudFunctions from 'better-firebase-functions'
exportCloudFunctions(__dirname, __filename, exports, './', './**/*.js')

It does everything automatically and will speed up your cold boot, without you having to worry about implementation details.
Read the docs for details on how to organise your function files (must export default in TS and module.exports.default = in JS) as it may change from the time of writing this.

A: If you're deploying to Node 10, you will probably want to change your statements to include the new environment variables. FUNCTION_TARGET instead of FUNCTION_NAME
https://cloud.google.com/functions/docs/env-var#nodejs_10_and_subsequent_runtimes

The Node.js 10 runtime automatically sets fewer environment variables than previous runtimes supported by Cloud Functions.

if (!process.env.FUNCTION_TARGET || process.env.FUNCTION_TARGET === functionName) {
    console.log(functionName+": "+file)
    // tslint:disable-next-line: no-var-requires
    exports[functionName] = require(file)
}


text:
Q: Rust way to design a storage struct and readonly struct users tl;dr What is the best "Rust way" to create some byte storage, in this case a Vec<u8>, store that Vec<u8> in struct field that can be accessed with a  key value (like a BTreeMap<usize, &Vec<u8>>), and later read those Vec<u8> from some other structs?
      Can this be extrapolated to a general good rust design for similar structs that act as storage and cache for blobs of bytes (Vec<u8>, [u8; 16384], etc.) accessible with a key (an usize offset, a u32 index, a String file path, etc.)?
Goal
I'm trying to create a byte storage struct and impl functions that:

*

*stores 16384 bytes read from disk on demand into "blocks" of Vec<u8> of capacity 16384

*other struct will analyze the various Vec<u8> and may need store their own references to those "blocks"

*be efficient: have only one copy of a "block" in memory, avoid unnecessary copying, clones, etc.

Unfortunately, for each implementation attempt, I run into difficult problems of borrowing, lifetime ellision, mutability, copying, or other problems.
Reduced Code example
I created a struct BlockReader that

*

*creates a Vec<u8> (Vec<u8>::with_capacity(16384)) typed as Block

*reads from a file (using File::seek and File::take::read_to_end) and stores 16384 of u8 into a Vec<u8>

*stores a reference to the Vec<u8> within a BTreeMap typed as Blocks
(playground code)
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Read;
use std::fs::File;
use std::collections::BTreeMap;

type Block = Vec<u8>;
type Blocks<'a> = BTreeMap<usize, &'a Block>;

pub struct BlockReader<'a> {
    blocks: Blocks<'a>,
    file: File,
}

impl<'a> BlockReader<'a> {
    /// read a "block" of 16384 `u8` at file offset
    /// `offset` which is multiple of 16384
    /// if the "block" at the `offset` is cached in
    /// `self.blocks` then return a reference to that
    /// XXX: assume `self.file` is already `open`ed file
    ///      handle
    fn readblock(& mut self, offset: usize) -> Result<&Block, std::io::Error> {
        // the data at this offset is the "cache"
        // return reference to that
        if self.blocks.contains_key(&offset) {
            return Ok(&self.blocks[&offset]);
        }
        // have not read data at this offset so read
        // the "block" of data from the file, store it,
        // return a reference
        let mut buffer = Block::with_capacity(16384);
        self.file.seek(SeekFrom::Start(offset as u64))?;
        self.file.read_to_end(&mut buffer);
        self.blocks.insert(offset, & buffer);
        Ok(&self.blocks[&offset])
    }
}

example use-case problem
There have been many problems with each implementation. For example, two calls to BlockReader.readblock by a struct BlockAnalyzer1 have caused endless difficulties:
pub struct BlockAnalyzer1<'b> {
   pub blockreader: BlockReader<'b>,
}

impl<'b> BlockAnalyzer1<'b> {
    /// contrived example function
    pub fn doStuff(&mut self) -> Result<bool, std::io::Error> {
        let mut b: &Block;
        match self.blockreader.readblock(3 * 16384) {
            Ok(val) => {
                b = val;
            },
            Err(err) => {
                return Err(err);
            }
        }
        match self.blockreader.readblock(5 * 16384) {
            Ok(val) => {
                b = val;
            },
            Err(err) => {
                return Err(err);
            }
        }
        Ok(true)
    }
}

results in
error[E0597]: `buffer` does not live long enough
  --> src/lib.rs:34:36
   |
15 | impl<'a> BlockReader<'a> {
   |      -- lifetime `'a` defined here
...
34 |         self.blocks.insert(offset, & buffer);
   |         ---------------------------^^^^^^^^-
   |         |                          |
   |         |                          borrowed value does not live long enough
   |         argument requires that `buffer` is borrowed for `'a`
35 |         Ok(&self.blocks[&offset])
36 |     }
   |     - `buffer` dropped here while still borrowed

However, I ran into many other errors for different permutations of this design, another error I ran into, for example
error[E0499]: cannot borrow `self.blockreader` as mutable more than once at a time
   --> src/main.rs:543:23
    |
463 | impl<'a> BlockUser1<'a> {
    |      ----------- lifetime `'a` defined here
...
505 |             match self.blockreader.readblock(3 * 16384) {
    |                   ---------------------------------------
    |                   |
    |                   first mutable borrow occurs here
    |                   argument requires that `self.blockreader` is borrowed for `'a`
...
543 |                 match self.blockreader.readblock(5 * 16384) {
    |                       ^^^^^^^^^^^^^^^^ second mutable borrow occurs here

In BlockReader, I've tried permutations of "Block" storage using Vec<u8>, &Vec<u8>, Box<Vec<u8>>, Box<&Vec<u8>>, &Box<&Vec<u8>>, &Pin<&Box<&Vec<u8>>, etc. However, each implementation permutation runs into various confounding problems with borrowing, lifetimes, and mutability.
Again, I'm not looking for the specific fix. I'm looking for a generally good rust-oriented design approach to this general problem: store a blob of bytes managed by some struct, have other struct get references (or pointers, etc.) to a blob of bytes, read that blob of bytes in loops (while possibly storing new blobs of bytes).
The Question For Rust Experts
How would a rust expert approach this problem?
How should I store the Vec<u8> (Block) in BlockReader.blocks, and also allow other Struct to store their own references (or pointers, or references to pointers, or pinned Box pointers, or etc.) to a Block?
Should the other structs copy or clone a Box<Block> or a Pin<Box<Block>> or something else?
Would using a different storage like a fixed sized array; type Block = [u8; 16384]; be easier to pass references for?
Should other Struct like BlockUser1 be given &Block, or Box<Block>, or &Pin<&Box<&Block>, or something else?
Again, each Vec<u8> (Block) is written once (during BlockReader.readblock) and may be read many times by other Structs by calling BlockReader.readblock and later by saving their own reference/pointer/etc. to that Block (ideally, maybe that's not ideal?).

A: You can put the Vec<u8> behind an Rc<RefCell<...>> or simply a Rc<..> if they're immutable.
If you need thread-safe access you'll need to use an Arc<Mutex<...>> or Arc<RwLock<...>> instead.
Here's a converted version of your code. (There were a few typos and bits that needed changing to get it to compile - you should really fix those in your example, and give us something that nearly compiles...)
You can also see this in the playground
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Read;
use std::fs::File;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::BTreeMap;

type Block = Vec<u8>;
type Blocks = BTreeMap<usize, Rc<RefCell<Block>>>;

pub struct BlockReader {
    blocks: Blocks,
    file: File,
}

impl BlockReader {
    /// read a "block" of 16384 `u8` at file offset
    /// `offset` which is multiple of 16384
    /// if the "block" at the `offset` is cached in
    /// `self.blocks` then return a reference to that
    /// XXX: assume `self.file` is already `open`ed file
    ///      handle
    fn readblock(& mut self, offset: usize) -> Result<Rc<RefCell<Block>>,std::io::Error> {
        // the data at this offset is the "cache"
        // return reference to that
        if self.blocks.contains_key(&offset) {
            return Ok(self.blocks[&offset].clone());
        }
        // have not read data at this offset so read
        // the "block" of data from the file, store it,
        // return a reference
        let mut buffer = Block::with_capacity(16384);
        self.file.seek(SeekFrom::Start(offset as u64))?;
        self.file.read_to_end(&mut buffer);
        self.blocks.insert(offset, Rc::new(RefCell::new(buffer)));
        Ok(self.blocks[&offset].clone())
    }
}

pub struct BlockAnalyzer1 {
   pub blockreader: BlockReader,
}

impl BlockAnalyzer1 {
    /// contrived example function
    pub fn doStuff(&mut self) -> Result<bool,std::io::Error> {
        let mut b: Rc<RefCell<Block>>;
        match self.blockreader.readblock(3 * 16384) {
            Ok(val) => {
                b = val;
            },
            Err(err) => {
                return Err(err);
            }
        }
        match self.blockreader.readblock(5 * 16384) {
            Ok(val) => {
                b = val;
            },
            Err(err) => {
                return Err(err);
            }
        }
        Ok(true)
    }
}


text:
Q: Getting rid of the margin at the end of the HTML file (attached) I want to convert an SVG file to a PDF file using a tool that we have at the office. The SVG file is the size of a A4 sheet and when we specify the page size in the arguments to the aforementioned tool, it will make a PDF file with that page size.
However, the input to the tool is HTML. The tool is using some version of Webkit.
So I have to embed the SVG file on an HTML file and input it to the tool. The actual embedding part is just fine. But I get a thin border at the end of each page which I don't know how to get rid of. That border also gets printed into the PDF file.
Note: There is a cunning trick. If I remove the !DOCTYPE HTML declaration at the top, it will go away. This might be a clue to some people but not to me. I want to keep it adhered to standards as this will be a module that will go into production.
The following are the sample HTML and SVG files I have created. I have colored the background of the HTML file as RED so that the border at the very end is noticeable.
First the HTML file.
<!DOCTYPE HTML>
<html>
   <head>
      <title>Sample</title>
      <style>
         body
         {
            text-align:center;
            margin: 0px;
         }
      </style>
   </head>
   <body bgcolor="red">
    <object id="svg1" data="svg.svg" type="image/svg+xml"></object>
   </body>
</html>

Now, the SVG file
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg viewBox="0 0 595.32 841.32" xmlns="http://www.w3.org/2000/svg" version="1.1">
   <rect
      x           ="0"
      y           ="0"
      width       ="595.32"
      height      ="841.32"
      fill        ="green"
      stroke      ="green"
      stroke-width="0.01"
   />
</svg>

Can anyone think of a way to get rid of this border? It might be a very simple trick, but I am not familiar with HTML so bear with me.
Thanks in advance.
-Anusha

A: This worked for me. Tested on Chrome Version 35.0.1916.153 m
  <style>
     body
     {
        text-align:center;
        margin: 0px;
     }
     object
     {
        display: block;
     }
  </style>


text:
Q: Python not catching UnicodeEncodeError from emojis Previously translating the name with a non-bmp map prevented emojis in names from crashing the script, but suddenly it doesn't work and i don't know why.
I tried adding a try/except block to see what the problem is, but the except doesn't catch the exception at all. I used the debugger and the code just jumps to the line after the except block (!?)
Here is the problematic code:

The line
logger.info(f"Liking tweet from user {name}")

throws the following exception:
--- Logging error ---
Traceback (most recent call last):
  File "C:\Users\JGC\anaconda3\lib\logging\__init__.py", line 1028, in emit
    stream.write(msg + self.terminator)
  File "C:\Users\JGC\anaconda3\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\ufffd' in position 40: character maps to <undefined>
Call stack:
  File "C:\Users\JGC\anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\JGC\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\Users\JGC\.vscode\extensions\ms-python.python-2020.6.91350\pythonFiles\lib\python\debugpy\__main__.py", line 45, in <module>
    cli.main()
  File "c:\Users\JGC\.vscode\extensions\ms-python.python-2020.6.91350\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
    run()
  File "c:\Users\JGC\.vscode\extensions\ms-python.python-2020.6.91350\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 267, in run_file
    runpy.run_path(options.target, run_name=compat.force_str("__main__"))
  File "C:\Users\JGC\anaconda3\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\JGC\anaconda3\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\JGC\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\Users\JGC\Desktop\Python\Templates de bots\Twitter Template\posting-bot\machado.py", line 169, in <module>
    stream.filter(track=HASHTAGS, languages=["pt"])
  File "C:\Users\JGC\anaconda3\lib\site-packages\tweepy\streaming.py", line 474, in filter
    self._start(is_async)
  File "C:\Users\JGC\anaconda3\lib\site-packages\tweepy\streaming.py", line 389, in _start
    self._run()
  File "C:\Users\JGC\anaconda3\lib\site-packages\tweepy\streaming.py", line 289, in _run
    self._read_loop(resp)
  File "C:\Users\JGC\anaconda3\lib\site-packages\tweepy\streaming.py", line 351, in _read_loop
    self._data(next_status_obj)
  File "C:\Users\JGC\anaconda3\lib\site-packages\tweepy\streaming.py", line 323, in _data
    if self.listener.on_data(data) is False:
  File "C:\Users\JGC\anaconda3\lib\site-packages\tweepy\streaming.py", line 54, in on_data
    if self.on_status(status) is False:
  File "c:\Users\JGC\Desktop\Python\Templates de bots\Twitter Template\posting-bot\machado.py", line 59, in on_status
    logger.info(f"Liking tweet from user {name}")
Message: 'Liking tweet from user maya | �; aridante'
Arguments: ()


text:
Q: VBA replace a string EXCEL 2019 I cannot extract the postal/zip code of a given address cell that comes like this :
"108, avenue du Grand Sud  37 170 CHAMBRAY les TOURS".
I have used :
=RECHERCHE(9^9;--("0"&STXT(A2;MIN(CHERCHE({0.1.2.3.4.5.6.7.8.9};A2&"0 123456789"));LIGNE($1:$100))))

Which sometimes works, sometimes not depending on the street number starting the address (here "108,").
The problem is the space of the pattern "37 170". I would like to remove the blank space in the pattern. Is there a regex way to search this pattern "## ###", and then to remove this poisonous blank space?
Thank you for your tricks.
I have tried this piece of code :
Function toto(r, Optional u = 0)
Application.Volatile
Dim i%, j%, adr$, cp$, loca$, x
  x = Split(r)
  For i = 0 To UBound(x)
    If x(i) Like "#####" Then Exit For
  Next
  If i > UBound(x) Then
    adr = r.Value 'facultatif
  Else
    cp = x(i)
    For j = 0 To i - 1: adr = adr & x(j) & " ": Next
    adr = Left$(adr, Len(adr) + (Len(adr) > 1))
    For j = i + 1 To UBound(x): loca = loca & x(j) & " ": Next
    loca = Left$(loca, Len(loca) + (Len(loca) > 1))
  End If
  x = Array(adr, cp, loca)
  If 0 < u And u < 4 Then toto = x(u - 1) Else toto = x
End Function

The above code works fine for splitting addresses including street number, zip code, and city name. But it does not work when the zip code is ## ### = 2 digit integer - space - 3 digit integer.
Edit: 01 June 2021
Since it seems my question is not clear enough, let's rephrase :
Given an Excel worksheet containing in each cell of column A, from saying A1 down to A10000, complete addresses like this one :
"2 rue Rene cassin Centre Commercial Châlon 2 Sud 71 100 CHALON SUR SAONE"
or this one :
"15, Rue Emile Schwoerer  68 000 COLMAR"
Where "71 100" and "68 000" are a zip code in incorrect format because of the extra space between the 2 first digits and 3 last digits.
I need to split the Ai cell content in order to obtain :

*

*in cell Bi : the text (street, etc.) placed left before the 2 first digits of the "wrong" zip code,

*in cell Ci : the zip code with its correct format ("71100" and not "71 100"),

*in cell Di : the text (city name) after the zip code.

It's a kind of left and right extraction around the zip code.
The above code that I have posted does not work.
In order to obtain the correct zip code format, I have tried the regex following function :
Function FindReplaceRegex(rng As Range, reg_exp As String, replace As String)
    Set myRegExp = New RegExp
    myRegExp.IgnoreCase = False
    myRegExp.Global = True
    myRegExp.Pattern = reg_exp

    FindReplaceRegex = myRegExp.replace(rng.Value, replace)
End Function

But I am unable to determine the correct regular expression pattern to get rid of the space in the zip code.
PEH gave me the following pattern :
(.*)([0-9]{2} ?[0-9]{3})(.*)
When using the function, I have tried to define the replacement pattern by:
(.*)([0-9]{2}[0-9]{3})(.*)
But it would not work. Hope this will clarify my question.
Any idea is welcome. Thanks

A: If these input strings always have the same pattern, try:
=CONCAT(FILTERXML("<t><s>"&SUBSTITUTE(A1," ","</s><s>")&"</s></t>","//s[.*0=0]"))

Depending on your needs/edge-cases, you could add more xpath expressions.

A: If this is VBA, I have a fix for you (please forgive the crappy naming convention, I'm scribbling this down in work while waiting for SQL to refresh):
Sub test1()

a0 = Cells(1, 1)  'Get the text, in this case "108, avenue du Grand Sud 37 170 CHAMBRAY les TOURS"
aa = Replace(a0, ",", " ")  'Make all delimiters of same type, so removing commas, you may need to add more replace work here?
ab = Application.Trim(aa)  'Reduce all whitespace to single entries, i.e. " " rather than "  "
ac = Split(ab, " ", -1)  'Now split by that single whitespace entry

Dim txt()

i2 = 0
lastIsNumeric = False
For i1 = 0 To UBound(ac) - 1  'Step through each entry in our "split" list

    If IsNumeric(ac(i1)) = True And IsNumeric(ac(i1 + 1)) = True Then
        'Two numbers back to back, join
        ReDim Preserve txt(i2)
        txt(i2) = ac(i1) + ac(i1 + 1)
        i2 = i2 + 1
        i1 = i1 + 1
    Else
        'Not two numbers back to back, don't join
        ReDim Preserve txt(i2)
        txt(i2) = ac(i1)
        i2 = i2 + 1

    End If

Next i1

If IsNumeric(ac(UBound(ac))) = False Then
    'Need to add last entry to txt()
    ReDim Preserve txt(UBound(txt) + 1)
    txt(UBound(txt)) = ac(UBound(ac))
End If

End Sub

edit 2021-06-01:
The above will generate a list (txt) of all the entries within your address. You can then reassemble if you wish, or extract out the postcode only.
If you want it as a function, then it would be:
Public Function getPostcode(a0)

aa = Replace(a0, ",", " ")
ab = Application.Trim(aa)
ac = Split(ab, " ", -1)

Dim txt()

i2 = 0
lastIsNumeric = False
For i1 = 0 To UBound(ac) - 1
    If IsNumeric(ac(i1)) = True And IsNumeric(ac(i1 + 1)) = True Then
        'Two numbers back to back, join
        ReDim Preserve txt(i2)
        txt(i2) = ac(i1) + ac(i1 + 1)
        i2 = i2 + 1
        i1 = i1 + 1
    Else
        'Not two numbers back to back, don't join
        ReDim Preserve txt(i2)
        txt(i2) = ac(i1)
        i2 = i2 + 1

    End If

Next i1

If IsNumeric(ac(UBound(ac))) = False Then
    'Need to add last entry to txt()
    ReDim Preserve txt(UBound(txt) + 1)
    txt(UBound(txt)) = ac(UBound(ac))
End If

'Re-assemble string for return
rtnTxt = ""
For i1 = 0 To UBound(txt)
    rtnTxt = rtnTxt & " " & txt(i1)
Next i1

getPostcode = rtnTxt

End Function


text:
Q: Get data from 2 tables based on comma separated values Join I am an average in database operation but I never deal with a database having values in comma separated manner. As I want the result from both table.
I have one table "Form table"
+------+-----------------+
| id   | Fname           |
+------+-----------------+
| 1    | BH01101,BH01102 |
| 2    | f_934_tarun2    |
| 3    | f_934,T_3234    |
+------+-----------------+

2nd table "user assigned form table"
+------+--------------------------------+
| u_id | Fname                          |
+------+--------------------------------+
| 1    | BH01102,BH16101,BH16102,BH16   |
| 2    | f_934_tar,f_934_fhh            |
| 3    | f_934_ttt,T_3234               |
| 4    | f_934_a1,BH01102               |
+------+--------------------------------+

I want to get all user ids who has any of form listed in form table. So here the output will be:
+------+
| u_id |
+------+
| 1    |
| 3    |
| 4    |
+------+

Every help will be appreciated.

A:
I am an average in database operation ...

Clearly this table was designed by someone of below average ability.

... I never deal with a database having values in comma separated manner.

Nor should you.  This "design" is just plain wrong.
Your tables should look more like this:
select * from forms ;

+------+--------------+
| id   | Fname        |
+------+--------------+
| 1    | BH01101      |
| 1    | BH01102      |
| 2    | f_934_tarun2 |
| 3    | f_934        |
| 3    | T_3234       |
+------+--------------+

select * from user_forms ;

+------+-----------+
| u_id | Fname     |
+------+-----------+
| 1    | BH01102   |
| 1    | BH16101   |
| 1    | BH16102   |
| 1    | BH16      |
| 2    | f_934_tar |
| 2    | f_934_fhh |
| 3    | f_934_ttt |
| 3    | T_3234    |
| 4    | f_934_a1  |
| 4    | BH01102   |
+------+-----------+

Then your query becomes
select uf.id id
from forms f
inner join user_forms uf
      on f.if = uf.u_id
     and f.fname = uf.fname
group by uf.id
order uf.id ;

+----+
| id |
+----+
|  1 |
|  3 |
|  4 |
+----+

Go back to whoever dumped you with this rubbish and get them to sort it out.


text:
Q: UIActivityViewController background color and nav bar color In my iOS 6 iPad app I am using the new UIActivityViewController. I would like the popup containing the options (facebook,twitter,email,etc...) to be black instead of the blue color it is normally. I have seen it done so I know it is possible but I'm not sure how to get it.
My code is:
UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:@[string,url] applicationActivities:nil];

shareOptions = [[UIPopoverController alloc] initWithContentViewController:activity];

[shareOptions presentPopoverFromBarButtonItem:actionBarButton permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

doing activity.view setBackgroundColor provides a weird looking popup... any ideas?
My second problem with UIActivityViewController is that when I chose to share via email the navigation bar for the email sharing controller is the default. I would like this to be black as well. I am trying to use the newish [UINavigationBar appearance] class. I can get it to be black using
[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];

but this is not the UIBarStyleBlackOpaque that I am after.
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlackOpaque];

does not work
Thanks!

A: Inside the event that opens the UIActivityViewController
- (IBAction)openShareDialog:(id)sender {
[[UINavigationBar appearance] setBackgroundImage:[YOUR UIImage] forBarMetrics:UIBarMetricsDefault];

//Init UIActivityViewController
}


text:
Q: pip install jnius - Exception: Unable to determine JDK_HOME I tried to install jnius Python module by typing 'pip install jnius' in CMD. This is the message I got:
pip install jnius
Collecting jnius
  Using cached jnius-1.1.0.tar.gz (28 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [6 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "\AppData\Local\Temp\pip-install-cu76yk3e\jnius_b318fcf7024d4f059fc0a7ebe16dd25c\setup.py", line 111, in <module>
          raise Exception('Unable to determine JDK_HOME')
      Exception: Unable to determine JDK_HOME
      [end of output]

I have tried adding a system variable of JDK_HOME and the value "C:\Program Files\OpenJDK\jdk-11.0.15.10-hotspot" but that didn't work


text:
Q: How to implement the Toolbar and Status bar of Google play store app in my app? If you go into the Google Play store, and open the details page for an app, the banner image is visible even up to behind the status bar. How do I  implement the same effect in my app (an image going up into the status bar)?
I have tried the following layout XML code in my app, but it doesn't make the status bar completely transparent:
<item name="android:windowTranslucentStatus">true</item>

A: This question I think is essentially the same as this one: Lollipop : draw behind statusBar with its color set to transparent and there are some good answers there.


text:
Q: HTML/CSS Mutiple menu image buttons rollover in CSS I have this problem with my navigation bar. I have 5 .png buttons horizontaly aligned. I want to give them rollover in CSS, not JAVA.
I tried so many things but just can't seem to control it. Al the ways I tried, it wont even load the images... I don't know what to do :) I already placed them in 1 big div. Here's my code:

A: I suggest you look into CSS sprites. Here's an example tutorial for a menu: http://praveenfrancis.com/tutorials/create-a-simple-menu-with-css-sprite/

A: Try putting images inside of a  then in CSS declare something like this:
a hover{
background://what you want;
}


text:
Q: Eclipse plug-in: how to activate terminate button in Debug view I am writing a plug-in to extend Eclipse for a custom programming language. I have all the launch configuration working and any program in the custom language launches correctly but I cannot seem to activate the Terminate button in the Debug view.
From what I have researched, I know that implementing the Debugger framework provides for the Terminate action but say, I do not want to implement the framework at this stage and would just like to have the option of terminating the program instead of having to cancel via the Task Manager. Is that possible to do? Or is the Debugger Framework the only way to do this?
Here is the code from the LaunchConfigurationDelegate class,
public void launch(ILaunchConfiguration configuration, String mode,
        ILaunch launch, IProgressMonitor monitor) throws CoreException {

    // getting the resource from the workspace
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();

    List<String> filenames = configuration.getAttribute(RELATIVE_PATH,
            Collections.EMPTY_LIST);
    List<String> rawPaths = configuration.getAttribute(RAW_PATH,
            Collections.EMPTY_LIST);
    List<String> projPaths = configuration.getAttribute(PROJECT_PATH,
            Collections.EMPTY_LIST);

    //CustomRunner is the interface to manage the custom language execution
    CustomRunner runner = null;
    try {
        CustomOutputHandler outHand = new CustomOutputHandler();
        runner = new CustomRunner(new File(projPaths.get(0)));
        runner.setOutputHandler(outHand);

        for (int i = 0; i < filenames.size(); i++) {
            IPath temp = new Path(filenames.get(i));
            IResource CustomFile = root.findMember(temp);

            if (CustomFile == null) {
                String msg = "The file "
                        + "<"
                        + temp.toString()
                        + ">"
                        + " could not be found in the workspace.\nIt may have been deleted or renamed.";
                throw new FileNotFoundException(msg);
            }
            CustomFile.deleteMarkers(IMarker.PROBLEM, false,
                    IResource.DEPTH_INFINITE);
            CustomErrorHandler errHand = new CustomErrorHandler(CustomFile);

            runner.setErrorHandler(errHand);

            //Runs the custom language file
            runner.run(rawPaths.get(i));
        }

After that there is just a bunch of catch blocks.
I need to be able to now terminate this launch via the Debug view and in the case of Run mode via the Run menu's terminate command.
I do not have any DebugTarget right now at this stage. And my question is: Is there another way to terminate this launch without extending the Debug Framework?
I did try launch.Terminate() in this launch method but that did not work.

A: Unless you extend the Platform-debug support you cannot hook into the Terminate button in the Debug view - at least there isn't an API for that. You can hack into the internals of the debug framework to add support without extending, but extending might be lot easier than that and will work in the future versions of Eclipse


text:
Q: Prove that R is a ring under 'special' definitions of multiplication and addition Question:
Let R be a ring with a 1. Define $\bar R$ to have the same elements of R with addition
$$\oplus: a \oplus b = a +b +1$$ andmultiplication $$\otimes: a \otimes b = ab + a +b$$ Prove that $\bar R$ is a ring under $\oplus$ and $\otimes$ and has a 1.
My Attempt:
My understanding of a ring is it should be a non-empty set together with operations addition and multiplication satisfying the following conditions:

*

*R is an Abelian group under multiplication

*R must be closed and associative under multiplication

*Multiplication must be distributive over addition i.e. $a(b+c) = ab + ac$ and $(a+b)c= ac +bc$

So I try to show that all those conditions are satisfied:
$$1$$
$$ a \otimes b = ab + a + b$$
$$ b \otimes a = ba + b +a $$
In order for $a \otimes b$ to be equal to $b \otimes a$ it must be that $ba = ab$ (how do I prove this? - do I even need to prove this?)
$$2$$
Closed: $$ a \otimes b = ab + a + b$$ if $a, b \in \bar R$ then $ab, \in \bar R$, $(a + b) \in \bar R$ and therefore $ab + a + b$ must be in $ \bar R$. (Do I need to prove this? Or is that pattern of thought good enough?)
Associative: let's introduce an element $c \in \bar R$ and examine the associativity property.
$$ \begin{align}
(a \otimes b) \otimes c & = \ (ab + a + b) \otimes c\\
& = \ abc + ac + bc + ab + a + b + c \\
& = \ a \otimes (bc + b + c) \\
& = \ a \otimes (b \otimes c) \\
& = \ a \otimes b \otimes c \\
\end{align} $$
So it is indeed associative under multiplication.
$$3$$
$$ \begin{align}
a \otimes (b \oplus c) & = \ a \otimes (b + c + 1) \\
& = \ ab + ac + a + a + b + c + 1 \\
& = \ ab + b + a + ac + a + c + 1 \\
& = \ a\otimes b \oplus \ a \otimes c \\
\end{align} $$
And I'm sure if I tinker around with the $(a + b)c = ac + bc$ equation I will find that it is also true so it does satisfy the distributive law.
The second part of the question demands that I show that $ \bar R$ has a 1. I understand a 1 to have the property: $a\times1= a$.
So considering it in this ring we're looking for a $x$ that does this:
$$a \otimes x = a$$
$$ a \otimes x = ax + x + a = a$$
Just from looking at the equation and using my intuition one can see that when $x=0$ the equation is true. So I would say that x=0 is the 1 of this ring. 0 is the multiplicative identity of $\bar R$
My Concerns:
Can I conclude after having done all this that $\bar R$ is in fact a Ring?
Have I answered the question sufficiently enough?

A: It seems you are mistaking the axioms in your definition : the first axiom should state that $\bar{R}$ is an abelian group under addition, not multiplication. So you need to prove that addition is closed, associative and commutative (this is trivial), find an identity for addition, and prove that every element has an inverse.
Then, with your proof for axioms 2 and 3, you'll have proved that $\bar{R}$ is indeed a ring.

A: Let (R,+,x) be a ring.
In general, let $p:R→R$ be a bijection, then define $A(m,n)=p^{−1}(p(m)+p(n))$ and define $M(m,n)=p^{−1}(p(m)p(n))$. The structure (R,A,M) is a ring. Moreover the bijection $p:R→R$ is a ring isomorphism from (R,A,M) to (R,+,x).
In fact, by Letting p(n)=n+1 we find that $M(m,n)=p^{−1}(p(m)p(n))=mn+m+n$ and $A(m,n)=m+n+1$.
Thus, $1_{(R,A,M)}=p^{-1}(1_{(R,+,x)})=1-1=0$ .
Check: $M(a,0)=(a)(0)+a+0=a$


text:
Q: how are javascript based websites different? I am trying to scrape the content of a website which seems to be working on javascript or some other technology. I am using xpath to find the content on the page. I can see the content using firebug in the browser but if i save the source or download the source code via curl/wget, content is missing from the page. How is this possible ?
thanks in advance

A: Some content are loaded via JS dynamically. You need to run the JS somehow, like in a headless browser like PhantomJS for several seconds in order to load dynamic content. Then run through the DOM, similar to how .html() in jQuery does it, to get the rendered content.
As far as I know, this is similar to how Opera Mini does it in their proxies before they re-encode and send it to your device:

The server sends the response back as normal — when this is received by the Opera transcoding servers, they parse the markup and styles, execute the JavaScript, and transcode the data into Opera Binary Markup Language (OBML). This OBML data is progressively loaded by Opera Mini on the user's device.

Opera Mini's entry from Wikipedia:

JavaScript will only run for a couple of seconds on the Mini server before pausing, due to resource constraints.
According to the documentation for Opera Mini 4, before the page is sent to the mobile device, its onLoad events are fired and all scripts are allowed a maximum of two seconds to execute. The setInterval and setTimeout functions are disabled, so scripts designed to wait a certain amount of time before executing will not execute at all. After the scripts have finished or the timeout is reached, all scripts are stopped and the page is compressed and sent to the mobile device.

A: Typically the page loads and then requests the content (ajax) which is returned as json or jsonp. This is usually pretty handy for scraping because json is even easier to parse than html.
But if you haven't done it before, it can be a challenge to figure out how to make the right ajax request.


text:
Q: Blogger API - Get URL After Create Post I am creating a post on my blogger blog using the blogger API.
This is based on the sample code here:
http://framework.zend.com/svn/framework/standard/trunk/demos/Zend/Gdata/Blogger.php
I can successfully create a post and I get the postid returned.
I was wondering how I can get the URL (permalink, or non permalink) of the newly created post from the returned postid?
Any help appreciated.

A: Just after I posted my comment I found the solution.
The $createdPost variable in the example will have a method named getAlternateLink. Use it like this:
$altLink = $createdPost->getAlternateLink();
$url = $altLink->getHref();

What I did to find this was a simple loop:
foreach (get_class_methods($createdPost) AS $method) {
  echo '<br>' . $method;
  try {
    if (strpos($method, 'get') !== FALSE) { echo ': '; var_dump($createdPost->$method()); }
  } catch (Exception $e) {

  }
}

This will echo out the result of each method that contains get in it. There are lots of set methods but that isn't what you need here. There are other get methods that will give you the link to edit, comment


text:
Q: SQL query: multiple count group by date I have 2 tables in my mySQL database:
Table Sensor
_id    Name
1      Sensor1
2      Sensor2

Table History
_id    Sensor_fk    Date
1      1            2015-05-24
2      2            2015-05-27
3      1            2015-05-28
4      1            2015-05-28
5      2            2015-05-28
...

I need a query that return something like this:
Date          Sensor1    Sensor2
2015-05-24    1          0
2015-05-27    0          1
2015-05-28    2          1

that is the count of my 2 sensors grouped by date. I will populate a bar chart with this data.
Someone can help me?

A: You need to do a UNION on two individual GROUP BY clauses for each Sensor. Like
(Select count(*) as Sensor1 from History h
     where h.Sensor_FK = 1
     group by DateField
)

Union

(Select Count(*) as Sensor2 from History h
    whre h.Sensor_FK = 2
    group by DateField
   )

A: I got it.
SELECT h.date as Date,
count(CASE WHEN h.sensor_fk = 1 THEN h.sensor_fk END) as 'Sensor1',
count(CASE WHEN h.sensor_fk = 2 THEN h.sensor_fk END) as 'Sensor2'
FROM history h
GROUP BY Date


text:
Q: Strange profiling results: definitely non-bottleneck method pops up I'm profiling a program using sampling profiling in YourKit and JProfiler, and also "manually" (I launch it and press Ctrl-Break several times to get thread dumps).
All three methods give me extremely strange results: some tens of percents of time spent in a 3-line method that does not even do any allocation or synchronization and doesn't have loops etc. Moreover, after I made this method into a NOP and even removed its invocation completely, the observable program performance didn't change at all (although it got a negligible memory leak, since it was a method for freeing a cheap resource).
I'm thinking that this might be because of the constraints that JVM puts on the moments at which a thread's stacktrace may be taken, and it somehow turns out that in my program it is exactly the moments where this method is invoked, although there is absolutely nothing special about it or the context in which it is invoked.
What can be the explanation for this phenomenon?
What are the aforementioned constraints?
What further measurements can I take to clarify the situation?

A: To my minds, these results only show that this method gets called a huge number of times. Since its code is quite small, and it may be called as an invocation tree leaf, its impact on your profiling results seems neglectable. However, I had many time that kind of weird results.

A: When you did the Ctrl-Break several times and got thread dumps, I'm curious what you saw. The call stacks are, to my mind, the most useful information. If your 3-liner is on the stack a large % of time, then you can see why by looking at where it is called from, and where that is called from, etc. Those call sites are just as responsible for the time being spent as the 3-liner is.
If the stack traces seem to make no sense, it may be because they are being delayed until after something completes. If that is so, look up the stack to see what has just completed, because the break could have occurred within that.

A: Some 3rd party libraries cause the heap dumps to go completely haywire due to unexpected usage patterns, for example if cglib is used, it will mask away the actual cause of the issues and instead show a lot of Proxy objects (if I remember correctly) filling up the VM instead.
So in short, code generation and reflection may cause the stats to go wrong.