text:
Q: How can I achieve four spaced buttons on an iPhone that fill the screen and on bigger than an iPhone that fill half the screen? I would like to have four buttons like this:
<Grid x:Name="buttonGrid" Grid.Row="3" Grid.Column="0" HorizontalOptions="FillAndExpand" VerticalOptions="Center" Padding="20, 0">
    <Button x:Name="zeroButton" Text="0" HeightRequest="60" BackgroundColor="#2D7BF7" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"/>
    <Button x:Name="oneButton" Text="1" HeightRequest="60" BackgroundColor="#2D7BF7" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"/>
    <Button x:Name="twoButton" Text="2" HeightRequest="60" BackgroundColor="#2D7BF7" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"/>
    <Button x:Name="fiveButton" Text="5" HeightRequest="60" BackgroundColor="#2D7BF7" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"/>
</Grid>

On an iPhone or a small mobile I would like to have these fill 90% of the screen width.  But on a bigger screen I would like the buttons to only fill 50% of the screen width.
Can anyone suggest to me how I can do this?

A: Explanation
If you need to create layouts that reference the ContentPage.Width or ContentPage.Height properties, the best way to do it is by using a RelativeLayout.
If you try referencing the ContentPage.Width or ContentPage.Height properties directly, you will find that Xamarin.Forms returns -1. This is because -1 is the default value that Xamarin.Forms uses when it hasn't instantiated the control yet.
RelativeLayout uses Funcs to dynamically reference the page's Height and Width properties and will return the true value of the Height and Width properties once the ContentPage has been instantiated.
Code
using Xamarin.Forms;

namespace HorizontalButtonSampleApp
{
    public class ButtonPage : ContentPage
    {
        public ButtonPage()
        {
            const int relativeLayoutHorizontalSpacing = 5;
            const int numberOfButtons = 4;

            double screenUsePercentage;
            if (Device.Idiom.Equals(TargetIdiom.Phone))
                screenUsePercentage = 0.9;
            else
                screenUsePercentage = 0.5;

            var zeroButton = new StyledButton { Text = "0" };
            var oneButton = new StyledButton { Text = "1" };
            var twoButton = new StyledButton { Text = "2" };
            var fiveButton = new StyledButton { Text = "5" };

            var relativeLayout = new RelativeLayout();
            relativeLayout.Children.Add(zeroButton,
                                        Constraint.RelativeToParent(parent => parent.Width * (1 - screenUsePercentage) / 2),
                                        Constraint.Constant(0),
                                        Constraint.RelativeToParent(parent => (parent.Width * screenUsePercentage - relativeLayoutHorizontalSpacing * (numberOfButtons - 1)) / numberOfButtons));
            relativeLayout.Children.Add(oneButton,
                                        Constraint.RelativeToView(zeroButton, (parent, view) => view.X + view.Width + relativeLayoutHorizontalSpacing),
                                        Constraint.Constant(0),
                                        Constraint.RelativeToParent(parent => (parent.Width * screenUsePercentage - relativeLayoutHorizontalSpacing * (numberOfButtons - 1)) / numberOfButtons));
            relativeLayout.Children.Add(twoButton,
                                        Constraint.RelativeToView(oneButton, (parent, view) => view.X + view.Width + relativeLayoutHorizontalSpacing),
                                        Constraint.Constant(0),
                                        Constraint.RelativeToParent(parent => (parent.Width * screenUsePercentage - relativeLayoutHorizontalSpacing * (numberOfButtons - 1)) / numberOfButtons));
            relativeLayout.Children.Add(fiveButton,
                                        Constraint.RelativeToView(twoButton, (parent, view) => view.X + view.Width + relativeLayoutHorizontalSpacing),
                                        Constraint.Constant(0),
                                        Constraint.RelativeToParent(parent => (parent.Width * screenUsePercentage - relativeLayoutHorizontalSpacing * (numberOfButtons - 1)) / numberOfButtons));

            Content = relativeLayout;

            Padding = new Thickness(0, 20);

            Title = $"Button Page on a {Device.Idiom}";
        }
    }

    public class App : Application
    {
        public App()
        {
            MainPage = new NavigationPage(new ButtonPage());
        }
    }

    public class StyledButton : Button
    {
        public StyledButton()
        {
            TextColor = Color.Black;
            HeightRequest = 60;
            BackgroundColor = Color.FromHex("2D7BF7");
            HorizontalOptions = LayoutOptions.FillAndExpand;
            VerticalOptions = LayoutOptions.CenterAndExpand;
        }
    }
}

Tablet Screen Shot

Phone Screen Shot


text:
Q: Compose string query in postgresql function with NULL argument I have a postgresql function with this signature:
ver_hijos(
    IN cod character varying,
    IN idpadre integer,
    IN idhijo integer)

Into the body of the function I have the next:
     FOR var_r IN EXECUTE 'SELECT ' ||
    ...........
    ' FROM '||....
     ' WHERE '||....
     ' AND
        CASE WHEN ' || idpadre || ' IS NULL
        THEN '||tabla_relacion||'.id_padre IS NULL
        ELSE '||tabla_relacion||'.id_padre = '||idpadre||'
        END
        AND '||tabla_relacion||'.id_hijo = '||tabla_conceptos||'.id'

Function works fine when idpadre is not null, but if not, the  query string concatenate with a null string and it is invalidate, getting the next error:
ERROR:  query string argument of EXECUTE is null
CONTEXT:  PL/pgSQL function ver_hijos(character varying,integer,integer) line 10 at FOR over EXECUTE statement

********** Error **********

ERROR: query string argument of EXECUTE is null
SQL state: 22004
Context: PL/pgSQL function ver_hijos(character varying,integer,integer) line 10 at FOR over EXECUTE statement

¿How can I build the function properly for accept NULL values and don't damage the string?
Edit:
If I use format() for build the query:
     FOR var_r IN EXECUTE format('SELECT ' ||
            ...........
            ' FROM '||....
             ' WHERE '||....
             ' AND
                CASE WHEN ' || idpadre || ' IS NULL
                THEN '||tabla_relacion||'.id_padre IS NULL
                ELSE '||tabla_relacion||'.id_padre = '||idpadre||'
                END
                AND '||tabla_relacion||'.id_hijo = |tabla_conceptos||'.id'
                ,idpadre,idpadre)

and I use null argument idpadre=null I get this error:
ERROR:  null values cannot be formatted as an SQL identifier
CONTEXT:  PL/pgSQL function ver_hijos(character varying,integer,integer) line 10 at FOR over EXECUTE statement
********** Error **********

ERROR: null values cannot be formatted as an SQL identifier
SQL state: 22004
Context: PL/pgSQL function ver_hijos(character varying,integer,integer) line 10 at FOR over EXECUTE statement

It's my workaround for resolve it:
DECLARE
........
str_null_case character varying;
........
BEGIN
........
IF idpadre IS NULL THEN
    str_null_case := tabla_relacion||'.id_padre IS NULL';
ELSE
    str_null_case := tabla_relacion||'.id_padre = '||idpadre;
END IF;
........
BODY
.......
' WHERE '||tabla_conceptos||'.id ='|| idhijo ||
 ' AND '||str_null_case||
 ' AND '||tabla_relacion||'.id_hijo = '||tabla_conceptos||'.id'
.......

A: You could solve it like this:
EXECUTE '... CASE WHEN ' || (idpadre IS NULL) || ' THEN ...';

For the ELSE branch, you can use coalesce(idpadre, '').
But it would be much better to write the whole thing as
EXECUTE format('... WHERE %I.id_padre IS NOT DISTINCT FROM $1',
               tabla_relacion)
USING idpadre;

This is simpler and avoids the danger of SQL injection.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exclude duplicated products from query I have products table (products can be duplicated by name but have unique id), as example:
products
id, name, isfolder
1, Product1, 0
2, Product2, 0
3, Product3, 0
4, Product1, 0

In result query I want have:
1, Product1, 0
2, Product2, 0
3, Product3, 0

It is possible?
Сlarification. ID is uniqueidentifier, and I need ID in result set.

A: You can use group by:
select min(id), name, isfolder
from products p
group by name, isfolder;


text:
Q: Extend URL with input field text basically what I'm trying to achieve should be quit simple, but my skills are limited. In the end I want to create a 'fake' search bar on my website. It's an input field which should go to the URL
mysite.com/search?q=INPUT

As this is another sites search field and the 'INPUT' should be the input from my site. This way I can have 'fake' search bar for another page.
Hope this makes sense.
If you take a look at this code, can we from here?

<FORM ACTION="JavaScript:gotoURL()"
      METHOD="GET"
      NAME="GotoForm">
URL:
<INPUT   TYPE="text"
          NAME="theURL"
          SIZE="50"
          VALUE="INPUT TXT"
     MAXLENGTH="100">
<INPUT TYPE="submit"
      VALUE="Goto">
</FORM>

And how can  manage special characters?
(space = +) (? = %3F)
Best, T

A: You can update your function as below :
function gotoURL(){
  var newURL = encodeURIComponent(document.GotoForm.theURL.value);
  document.location.href= 'http://testsite.com/search?q='+newURL
}

The encodeURIComponent() function encodes a URI component. This
  function encodes special characters. In addition, it encodes the
  following characters: , / ? : @ & = + $ #


text:
Q: FFmpeg with mp4 file, segment and concatenate doesn't recreate the original video, why? I'm trying to segment and concatenate mp4 file with FFmpeg.
First I segment the video file:
ffmpeg -i input.mp4 -c copy -map 0 -f segment -reset_timestamps 1 output%03d.mp4

Then I concatenate
ffmpeg -f concat -safe 0 -i list.txt -c copy -movflags faststart done.mp4

My expectation is that the videos should be the exact same, however a lot of differences appear, the bytes size is slightly different, then with FFprobe I find differences in streams, as both video streams and audio streams have different starting times and durations.
The reason I'm asking this, because I want to first segment the file, then reencode several parts of the video with different program, and then concatenate back, but this will not work if timestamps are messed up in the process.


text:
Q: Why is my quizzcount doubling its value I'm having a problem with this code in that the quizzcount variable is not outputting the correct value, it doubles the value.
I found a work around by diving the quizzcount by 2 and it works but i would really like to figure out why its doubling the value.
So for example, without dividing quizzcount by 2, if the user gets 7 out of the 10 questions correct the messagedialog will display that the user got 14 out of 10 correct.
What is causing this?
Thanks guys, any help would be appreciated.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidClassException;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.*;
import java.util.*;

import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.Image;
import java.lang.*;

public class MathFiles extends JFrame implements ActionListener
{
private ObjectOutputStream toFile;
private String name;
private boolean open;
private static String response;
private static int menuOption = 0;
private static int numberOfMaths = 0;
private FileInputStream fis;
private ObjectInputStream fromFile;
Math aMath = null;
private int quizcount =0;
String checkbutton = "";
private static int tracker =1;
int count = 0;
int fimage =0;

JRadioButton questA, questB, questC, questD, questE;
ButtonGroup  questGroup;
JPanel       questPanel;

JLabel       question;
JPanel       questionPanel;

JTextField   resultText;
JLabel       resultLabl;
JPanel       resultPanel;

JButton      nextButton;
JPanel       quizPanel;

ImageIcon    image;
JLabel       imageLabl;
JPanel       imagePanel;

JTextArea    questionText;
JScrollPane  scrollPane;

Random       rand;

/** @param fileName is the desired name for the binary file. */
public MathFiles()
{
    setTitle( "Math Quiz Competition" );

    rand = new Random();
    toFile = null;
    //tracker =  rand.nextInt(5)+1;
    tracker = 1;

    name = "Quiz"+tracker+".txt";
    open = false;

    //openFile(); //Use only when creating file
    //writeMathsToTextFile(name);
    setLayout( new FlowLayout() );
    inputFile();
    beginquiz();
    showquestions();
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

} // end MathFiles constructor

/** Writes all Maths from a text file and writes them to a binary file.
    @param fileName the text file */
public void writeMathsToTextFile(String fileName)
{
    Scanner inputFile = null;
    Math nextMath = null;
    String question_num;
    String question;
    String answera;
    String answerb;
    String answerc;
    String answerd;
    String answer_cor;
    String file_name;
    String SENTINEL ="DONE";

    try
    {
        inputFile = new Scanner(new File(fileName));
    }
    catch(FileNotFoundException e)
    {
        System.out.println("Text file " + fileName + " not found.");
        System.exit(0);
    }

    Scanner keyboard = new Scanner(System.in);

    System.out.print("Question number: ");
    question_num = keyboard.nextLine();
    while (!question_num.equalsIgnoreCase(SENTINEL))
    {

     System.out.print("Question: ");
     question = keyboard.nextLine();

     System.out.print("Answer A: ");
     answera = keyboard.nextLine();

     System.out.print("Answer B: ");
     answerb = keyboard.nextLine();

     System.out.print("Answer C: ");
     answerc = keyboard.nextLine();

     System.out.print("Answer D: ");
     answerd = keyboard.nextLine();

     fimage = rand.nextInt(30)+1;
     file_name = "image"+fimage+".gif";
     System.out.print(file_name);

     System.out.print("Correct Answer: ");
     answer_cor = keyboard.nextLine();

     nextMath = new Math(question_num, question, answera, answerb,
                answerc, answerd, answer_cor, file_name);
     writeAnObject(nextMath);
     numberOfMaths++;

     System.out.print("\nQuestion number: ");
     question_num = keyboard.nextLine();
    } // end while

    System.out.println("successfully created = " + name);
} // end readMathsFromTextFile

/** Opens the binary file for output. */
public void openFile()
{
    try
    {
        FileOutputStream fos = new FileOutputStream(name);
        toFile = new ObjectOutputStream(fos);
        open = true;
    }
    catch (FileNotFoundException e)
    {
        System.out.println("Cannot find, create, or open the file " + name);
        System.out.println(e.getMessage());
        open = false;
    }
    catch (IOException e)
    {
        System.out.println("Error opening the file " + name);
        System.out.println(e.getMessage());
        open = false;
    }
    //System.out.println("successfully opened = " + name);
} // end openFile

/** Writes the given object to the binary file. */
public void writeAnObject(Serializable anObject)
{
    try
    {
        if (open)
            toFile.writeObject(anObject);
    }
    catch (InvalidClassException e)
    {
        System.out.println("Serialization problem in writeAnObject.");
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch (IOException e)

    {
        System.out.println("Error writing the file " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
} // end writeAnObject

public void result()
{
    System.out.println("Your score is");

}

public void inputFile()
{

    try
    {
        fromFile = new ObjectInputStream(new FileInputStream(name));

    }

    catch(StreamCorruptedException e)
    {
        System.out.println("Error in input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(IOException e)
    {
        System.out.println("Error reading input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
} // end displayFile

/** Closes the binary file. */
public void closeFile()
{
    System.out.println("closed name = " + name);
    try
    {
        toFile.close();
        open = false;
    }
    catch (IOException e)
    {
        System.out.println("Error closing the file " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
} // end closeFile

/** @return the fileís name as a string */
public String getName()
{
    return name;
} // end getName

/** @return true if the file is open */
public boolean isOpen()
{
    return open;
} // end isOpen

public void beginquiz()
{

    try
    {
        aMath = (Math)fromFile.readObject();
    }
    catch (ClassNotFoundException e)
    {
        System.out.println("The class Math is not found.");
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(StreamCorruptedException e)
    {
        System.out.println("Error in input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(IOException e)
    {
        System.out.println("Error reading input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }

}

void showquestions()
{

    //question group
    /*question  = new JLabel();
    question.setText(aMath.getquestion());
    question.setFont(new Font("Arial", Font.BOLD, 20));
    question.setForeground(Color.BLUE);
    questionPanel = new JPanel();
    questionPanel.add( question );*/

    questionText  = new JTextArea(5,20);
    questionText.setWrapStyleWord(true);
    questionText.setLineWrap(true);
    questionText.setText(aMath.getquestion());
    questionText.setFont(new Font("Arial", Font.BOLD, 20));
    questionText.setForeground(Color.BLUE);
    questionPanel = new JPanel();
    questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.PAGE_AXIS));
    questionPanel.add( questionText );

    // quest group
    questA = new JRadioButton(aMath.getanswera(), false );
    questB = new JRadioButton(aMath.getanswerb(), false );
    questC = new JRadioButton(aMath.getanswerc(), false );
    questD = new JRadioButton(aMath.getanswerd(), false );

    questGroup = new ButtonGroup();
    questGroup.add( questA );
    questGroup.add( questB );
    questGroup.add( questC );
    questGroup.add( questD );

    questPanel = new JPanel();
    questPanel.setLayout( new BoxLayout( questPanel, BoxLayout.Y_AXIS ) );
    questPanel.add( new JLabel("Choose the Correct Answer") );
    questPanel.add( questA );
    questPanel.add( questB );
    questPanel.add( questC );
    questPanel.add( questD );

    // result panel
    //resultText  = new JTextField(20);
    //resultText.setEditable( false );
    //resultLabl  = new JLabel("Result");
    //resultPanel = new JPanel();
    //resultPanel.add( resultLabl );
    //resultPanel.add( resultText );

    //button
    nextButton = new JButton("Next");
    quizPanel = new JPanel();
    quizPanel.add(nextButton);

   //Image image1 = new ImageIcon("image/image1.gif").getImage();
    image = new ImageIcon("image1.gif");
    imageLabl=new JLabel(image);
    imagePanel = new JPanel();
    imagePanel.add(imageLabl);

    // frame:  use default layout manager
    add( imagePanel);
    add( questionPanel);
    add( questPanel);
    //add( resultPanel);

    questA.setActionCommand(aMath.getanswera());
    questB.setActionCommand(aMath.getanswerb());
    questC.setActionCommand(aMath.getanswerc());
    questD.setActionCommand(aMath.getanswerd());

    questA.addActionListener(this);
    questB.addActionListener(this);
    questC.addActionListener(this);
    questD.addActionListener(this);

    nextButton.setActionCommand( "next" );   // set the  command

    // register the buttonDemo frame
    // as the listener for both Buttons.
    nextButton.addActionListener( this );
    add(quizPanel);

}

public void actionPerformed( ActionEvent evt)
{
  //evt.getActionCommand() = aMath.getanswer_cor();

if (questA.isSelected()&&
    aMath.getanswera().equalsIgnoreCase(aMath.getanswer_cor().trim()))
    quizcount++;

if (questB.isSelected()&&
    aMath.getanswerb().equalsIgnoreCase(aMath.getanswer_cor().trim()))
    quizcount++;

if (questC.isSelected()&&
    aMath.getanswerc().equalsIgnoreCase(aMath.getanswer_cor().trim()))
    quizcount++;

if (questD.isSelected()&&
   aMath.getanswerd().equalsIgnoreCase(aMath.getanswer_cor().trim()))
   quizcount++;

if(questA.isSelected() || questB.isSelected() || questC.isSelected() || questD.isSelected())

 if ( evt.getActionCommand().equals( "next" ))
{

   try
    {
        aMath = (Math)fromFile.readObject();
        questionText.setText(aMath.getquestion());
        questA.setText(aMath.getanswera());
        questB.setText(aMath.getanswerb());
        questC.setText(aMath.getanswerc());
        questD.setText(aMath.getanswerd());
        imageLabl.setIcon(new ImageIcon(aMath.getfile()));

        questGroup.clearSelection();

        repaint();

    }
    catch (ClassNotFoundException e)
    {
        System.out.println("The class Math is not found.");
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(StreamCorruptedException e)
    {
        System.out.println("Error in input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(IOException e)
    {
        if (count<=0)
           count = 0;
        else
           count--;
        JOptionPane.showMessageDialog(null,"Your score is "+quizcount/2 +" out of 10");
        try{
          Thread.sleep(2000);
          System.exit(0);
        }catch (InterruptedException em) { }
    }

}

}

public static void main ( String[] args )
{
    MathFiles mat = new MathFiles();
    mat.setSize( 450, 550 );
    mat.setLocationRelativeTo(null);
    mat.setResizable( false );
    mat.setVisible( true );
}

} // end MathFiles

class Math implements java.io.Serializable
{
private String question_num;
private String question;
private String answera;
private String answerb;
private String answerc;
private String answerd;
private String answer_cor;
private String file_name;

public Math(String quesno, String quest, String ansa, String ansb, String ansc,
         String ansd, String ans_cor, String file)
{

   question_num = quesno;
   question = quest;
   answera = ansa;
   answerb = ansb;
   answerc = ansc;
   answerd = ansd;
   answer_cor = ans_cor;
   file_name = file;
}

public void setquestion(String lName)
{
    question = lName;
} // end setquestion

public void setquestion_num(String fName)
{
    question_num = fName;
} // end setquestion_num

public void setanswera(String add)
{
    answera = add;
} // end setanswera

public void setanswerb(String cty)
{
    answerb = cty;
} // end setanswerb

public void setanswerc(String st)
{
    answerc = st;
} // end setanswerc

public void setanswerd(String z)
{
    answerd = z;
} // end setanswerd

public void setanswer_cor(String phn)
{
    answer_cor = phn;
} // end setanswer_corr

public String getquestion_num()
{
    return question_num;
} // end getquestion_num

/** @return the question */
public String getquestion()
{
    return question;
} // end getquestion

/** @return the answera*/
public String getanswera()
{
    return answera;
} // end getanswera

/** @return the answerb */
public String getanswerb()
{
    return answerb;
} // end getanswerb

public String getanswerc()
{
    return answerc;
} // end getanswerc

public String getanswerd()
{
    return answerd;
} // end getanswerd

public String getanswer_cor()
{
    return answer_cor;
} // end getanswer_corr

public String getfile()
{
    return file_name;
} // end getanswer_corr

/** @return the Math information */
public String toString()
{
    String myMath = getquestion_num() + " " + getquestion() + "\n";
    myMath += getanswera() + "\n";
    myMath += getanswerb() + " " + getanswerc() + " " + getanswerd() + "\n";
    myMath += getanswer_cor() + "\n";
    myMath += getfile() + "\n";

    return myMath;
} // end toString

} // end Math

A: It looks like your problem is that you've registered ActionListeners on the radio buttons. This means the event fires when you select an answer as well as clicking the 'next' button. With that in mind it should be obvious why your score is doubling itself.
As far as I can tell you don't need ActionListeners for the radio buttons. You should only be checking the answer when the user has indicated they are done with their selection. That the score is exactly doubling itself also suggests that you basically haven't tested the program besides naively selecting a radio button and clicking 'next'. Before commenting out the lines where you add the listeners to the radio buttons, try changing your answer. Open the program, select the correct answer, then select an incorrect answer, then select the correct answer again and click 'next'. See what happens.
This kind of error can also be easily found with a debugger. Just insert a breakpoint inside actionPerformed and it will be obvious it's being called by more than one action.


text:
Q: Access 2007 Forecasting Date range I'm looking for some help / guidance on implementing some kind of forecasting form in my access database. What i'd like to achieve is for the user to pick out a project from a drop down list (which i have) and then select a from & to date from two date pickers. When the dates are selected - e.g Jan 2016 - Jan 2017, the database creates 12 blank entries where the user can input various amounts in each cell.
The database has the set up where a single project can have multiple calendar dates. I've tried using a cross tab query in the first instance however, as I quickly found out, it's non-updateable. I've looked into using a 'temp' table and then possibly using an update function from the temp table and inserting new records however, I'm really hoping there is a simpler way.. Has any one encountered a similar issue / any advice on the best approach?
Update:
Table structure of the temp table (if this is the best way?) would look something like:
Ideally, if the user selects the range Jan 15 - Jan 16, then the database 'fills in' the remaining months. In the db the table would then look like:
[Project Id] [Month] [Year]
[1]            [1]    [2015]
[1]            [2]    [2015]
[1]            [3]    [2015]
etc..
I'm unsure how to implement this; i.e on selection of starting and end months, create the entries in between.

A: As we must assume the forecast should be persisted, the first choice in Access will be to use a table to hold the forecast data. I can't see what "simpler way" there could be.

A: This may differ from your set up, but I'd create a table to store all your forecast data permanently.. e.g. in this illustration I've created tblForecast with these fields:

I've then created a form with a combo box to select the Project, 2 text boxes to provide the From and To dates and then a command button to run some VBA that will create the records as you've described. Below these controls is a subform that uses tblForecast as its RecordSource; this will be used to display the records that the form will create and allow users to put their own data against fields ForecastData1 and ForecastData2:

Here's the annotated VBA code on the click event on that command button:
Private Sub cmdCreate_Click()

    Dim db As DAO.Database
    Dim rs As DAO.Recordset
    Dim newRecs As Integer
    Dim i As Integer

    ' Open tblForecast so we can add new records to it
    Set db = CurrentDb
    Set rs = db.OpenRecordset("tblForecast")

    ' Find out how many records we need to add based on the number of months between
    ' the From and To dates supplied on the form
    newRecs = DateDiff("m", Me.txtFromDate, Me.txtToDate)

    ' Initialise our counter for the loop
    i = 1

    ' Start a loop that will create a new record for each of the months needed
    Do While i <= newRecs

        With rs

            .AddNew

            ' Pre-poulate the ProjectID, ForecastMonth and ForecastYear fields with
            ' the relevant data
            !ProjectID = Me.cboProject
            !ForecastMonth = Month(DateAdd("m", i - 1, Me.txtFromDate))
            !ForecastYear = Year(DateAdd("m", i - 1, Me.txtFromDate))

            .Update

            ' Increment the counter before next loop iteration
            i = i + 1

        End With

    Loop

    ' Requery subform to see the new records that have been added
    Me.tblForecast_sub.Form.Requery

    ' Tidy-up memory
    rs.Close
    Set rs = Nothing
    Set db = Nothing

End Sub

So, if you provide a Project and From and To dates...

...and then click the command button:

The VBA code creates a record for each month between the From and To dates supplied and pre-populates the ProjectID, ForecastMonth and ForecastYear fields with appropriate data. It's then up to the user to complete the remaining ForecastData1 and ForecastData2 fields.
Here's a link to the Access mock-up file so you can have a closer look if you like.


text:
Q: How can I solve these two simultanious trigonometric equations?? $\sin x \cos y=\frac{1}{4}$ and $3\tan x=\tan y$ I have two trigonometric equations and I have to find for x and y.

$\sin x \cos y=\frac{1}{4}$ and $3\tan x=\tan y$.

I tried to make it of the form of compound/ allied angles like $\sin(x+y)$ but failed.
Please give me some hint.
Thanks.

A: As you asked for the hint, here is the one:
$\sin x \cos y=\frac{1}{4}$ and $3\tan x=\tan y$.
If you transform the second equation, you willl get:
$$3\tan x=\tan y \implies 3\sin x \cos y-\sin y\cos x=0$$
Using $\sin x \cos y=\frac{1}{4}$, you will get $\sin y\cos x=\frac{3}{4}$ and $\sin x \cos y=\frac{1}{4}$.
$\implies \sin(x+y)=1 $ and $\sin(x-y)=\frac{1}{2}$.

A: Hint:
$3\tan x = \tan y$
$\Rightarrow3\sin x\cos y=\cos x\sin y$
$\Rightarrow\cos x\sin y=\frac{3}{4}$
$sin(x+y)=\sin x\cos y+\cos x\sin y =1$
$sin(x-y)=\sin x\cos y-\cos x\sin y =\frac{1}{2}$

A: Hint...you can write the second equation in terms of $\sin$ and $\cos$ and use the first equation to obtain $$\cos x\sin y=\frac 34$$
Can you take it from there?


text:
Q: Python pip install proxy 407 issue I am using Python 3.8.1 on Windows and I have pip 19.2.3 from c:\python381\lib\site-packages\pip (python 3.8).
In cmd when I enter 'pip install django' I get:
 WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required'))': /simple/django/

I looked into the proxy error and tried to fix it using:
:\set http_proxy=http://username:password@proxyAddress:port
I'm using the username and password that I use to log into the system. I'm using a port number which i found in the LAN settings under 'Proxy server'. I am supposed to update proxy address as well? This is greyed out.
I get the same error message when running the above. Does anyone know how to fix this?

A: Try this :
Open CMD as administrator and export proxy settings
:\set http_proxy=http://username:password@proxyAddress:port
:\set https_proxy=https://username:password@proxyAddress:port
Then install your package

A: As I do not have access to admin in powershell I'll post an update of how I fixed this proxy issue here:

*

*go to the control centre

*type env in the search box

*select 'edit environment variables'

*under http_proxy and https_proxy I updated my password by selecting the relevant line and clicking edit

Once I followed those steps I was able to import packages using pip install on the command line


text:
Q: Questions about Advertising I recently viewed an advertisement, and I wanted to ask someone knowledgeable in marketing a question about it. Is there a site appropriate for that on Stack Exchange?

A: There's an Area51 proposal for a Marketing site, but it's still  in the "definition" phase. You could help it reach beta by voting and adding example questions to it.

A: If your question is about graphical aspects, such as composition, colours, font choice, etc., it could be appropriate for Graphic Design.


text:
Q: In SSMS, apply AT TIME ZONE to all DateTimeOffset columns in query? For an ad-hoc query in SSMS, is it possible to specify AT TIME ZONE to be applied to all DateTimeOffset columns in the query?  Sometimes for diagnostic purposes it's easy to pop into SSMS and do a "select *" query to look at the data, but if the DateTimeOffset values are all in different time zones it's hard to convert between them for mental comparisons.
I've already found this question which shows how to display each column in the timezone, but it's cumbersome if there are multiple columns.


text:
Q: WPF MediaElement on Remote Desktop I have a simple WPF application that all it has is a media element:
<MediaElement Name="TheMedia" Stretch="Fill" LoadedBehavior="Play"/>

I initialize the source in the code behind:
public MainWindow()
{
    InitializeComponent();
    string file = string.Format(@"{0}\{1}", Environment.CurrentDirectory, "movie.mp4");
    Uri uri = new Uri(file);
    TheMedia.Source = uri;
}

When I run it on my computer it works
when I run it on a remote desktop it does one of the 2 things dependent on the RD Sesion Host Configuration -> RDP-Tcp -> Properties -> Client Settings -> Audio and video playback:
if it is checked, I see the video with no sound
if it is not checked, I hear the video but no display
Any ideas?


text:
Q: Determine Version of iOS
Possible Duplicate:
Check iPhone iOS Version

I am trying to setup some code that is different on iOS 5.0.1 than it is one iOS 5.1 and higher.  Is there an if statement to determine it or not?

A: float version = [[[UIDevice currentDevice] systemVersion] floatValue];

A:    if ( [[[UIDevice currentDevice] systemVersion] floatValue] == 5.0)
{
// Do something
}

else if ( [[[UIDevice currentDevice] systemVersion] floatValue] == 5.1)
{
// Do something
}
else
{
// Do something
}


text:
Q: Do I have to reload RevMob Ads? I want to use both fullscreen and banner ads in one of my games. Do I have to load the fullscreen ad everytime before showing it?

A: No, if you don't call the SDK will call it for you.
But if you load some time earlier than you need to show, it will be much more faster to show it.


text:
Q: How to use Using the HtmlAgilityPack to get table value http://www.dsebd.org/latest_PE_all2_08.php

i work on asp.net C# web.Above url contain some information ,i need to save them in my database and also need to save then in specified location as xml format.This url contain a table.I want to get this table value but how to retrieve value from this html table.
HtmlWeb htmlWeb = new HtmlWeb();

            // Creates an HtmlDocument object from an URL
            HtmlAgilityPack.HtmlDocument document = htmlWeb.Load("http://www.dsebd.org/latest_PE_all2_08.php");

I need help to get table information from this document .How to save this table value.Show me some syntax

A: public partial class WebForm3 : System.Web.UI.Page
    {
        private byte[] aRequestHTML;
        private string myString = null;
        protected System.Web.UI.WebControls.Label Label1;
        private ArrayList a = new ArrayList();

        protected void Page_Load(object sender, EventArgs e)
        {
            WebClient objWebClient = new WebClient();

            aRequestHTML = objWebClient.DownloadData("http://www.dsebd.org/latest_PE_all2_08.php");
            // creates UTf8 encoding object
            UTF8Encoding utf8 = new UTF8Encoding();
            // gets the UTF8 encoding of all the html we got in aRequestHTML
            myString = utf8.GetString(aRequestHTML);

            string html = @"

sno	sname

111	abcde

213	ejkll

adress	phoneno	note

asdlkj	121510	none

asdlkj	214545	none

        ";

            HtmlDocument htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(myString);

            DataTable addressAndPhones;
            foreach (var table in ParseAllTables(htmlDoc))
            {
                if (table.Columns.Contains("Trading Code") && table.Columns.Contains("Close Price"))
                {
                    // You found the address and phone number table
                    addressAndPhones = table;
                }
            }

        }

        private static DataTable[] ParseAllTables(HtmlDocument doc)
        {
            var result = new List<DataTable>();
            foreach (var table in doc.DocumentNode.Descendants("table"))
            {
                result.Add(ParseTable(table));
            }
            return result.ToArray();
        }

        private static DataTable ParseTable(HtmlNode table)
        {
            var result = new DataTable();

            var rows = table.Descendants("tr");

            var header = rows.Take(1).First();
            foreach (var column in header.Descendants("td"))
            {
                result.Columns.Add(new DataColumn(column.InnerText, typeof(string)));
            }

            foreach (var row in rows.Skip(1))
            {
                var data = new List<string>();
                foreach (var column in row.Descendants("td"))
                {
                    data.Add(column.InnerText);
                }
                result.Rows.Add(data.ToArray());
            }
            return result;
        }

    }

In this way u can easily create a DataTable and then can save is DataBase.


text:
Q: Python - print statements not going into sys.stdout file after a certain point I have a small PyQt5 GUI that uses Youtube_dlc. I want to put a few print statements into an external log file for testing.
However, after a certain point (After i store the videos metadata into a variable) my programm no longer saves the print statements into the file. Only when i press X on my app and it closes it saves all the lines at once.
HOWEVER, when i dont redirect stdout into a file, it prints like normally.
This is my code:
import youtube_dlc
from audioclipextractor import AudioClipExtractor
from PyQt5 import QtWidgets
import Output
import sys
import os
import datetime

ffmpegpath = "ffmpeg.exe"
sys.stdout = open("test.txt", "w")
open("test.txt", "w").truncate(0)

class youtubeDownloader(QtWidgets.QMainWindow, Output.Ui_MainWindow):
    def __init__(self, parent=None):
        super(youtubeDownloader, self).__init__(parent)
        self.setupUi(self)
        self.button_download.clicked.connect(lambda: self.add_youtubeaudio(url=self.textbox_url.toPlainText(), start=self.textbox_start.toPlainText(), end=self.textbox_end.toPlainText(), file=self.textbox_filename.toPlainText()))

    def add_youtubeaudio(self, url, start=None, end=None, file=None):
        ydl_opts = {

            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }
        with youtube_dlc.YoutubeDL(ydl_opts) as ydl:
            print("{} # Downloading Youtube video {}".format(datetime.datetime.now(),url))
            ydl.download([url])
            print("{} # Downloading Youtube video {} complete".format(datetime.datetime.now(),url))
            self.textBrowser_Output.setPlainText("{} wurde heruntergeladen".format(file))
            print("{} # Downloading Metadata {}".format(datetime.datetime.now(), url))
            video_info = (ydl.extract_info(url))['id']
            print("{} # Downloading Metadata {} complete".format(datetime.datetime.now(), url))
            for x in os.listdir(os.curdir):
                if str(video_info)+".mp3" in x:
                    videokeep = x
            print("{} # Checking altarnative arguments".format(datetime.datetime.now()))
            if start and end:
                print("{} # Cutting video {} from {} to {}".format(datetime.datetime.now(),url,start,end))
                ext = AudioClipExtractor(str(videokeep), ffmpegpath)
                specs = str(start) + " " + str(end)
                ext.extract_clips(specs)
                print("{} # Cutting video {} from {} to {} complete".format(datetime.datetime.now(),url, start, end))
                try:
                    print("{} # Renaming file to {}".format(datetime.datetime.now(),file))
                    os.rename('clip1.mp3',str(file)+".mp3")
                    print("{} # Renaming file to {} complete".format(datetime.datetime.now(),file))
                    self.textBrowser_Output.setPlainText("{} wurde in clip geschnitten".format(file))
                except:
                    print("{} # Output file {} already exists".format(datetime.datetime.now(),file))
                    self.textBrowser_Output.setPlainText("{} existiert bereits".format(file))
            else:
                try:
                    print("{} # Renaming file to {}".format(datetime.datetime.now(),file))
                    os.rename(videokeep, str(file)+".mp3")
                    print("{} # Renaming file to {} complete".format(datetime.datetime.now(),file))
                except:
                    print("{} # Output file {} already exists".format(datetime.datetime.now(),file))

        if self.checkBox_deletevid.isChecked():
            try:
                os.remove(videokeep)
            except:
                pass

def main():
    app = QtWidgets.QApplication(sys.argv)
    form = youtubeDownloader()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

(Full rep at https://github.com/FlyingThunder/YoutubeDownloader)
Running it like this and using the default input saves this into the file:
[youtube] C0DPdy98e4c: Downloading webpage
2020-10-28 16:33:05.376083#Downloading Youtube video https://www.youtube.com/watch?v=C0DPdy98e4c
[download] Destination: TEST VIDEO-C0DPdy98e4c.m4a

[download]   0.4% of 274.02KiB at 167.00KiB/s ETA 00:01
[download]   1.1% of 274.02KiB at 501.01KiB/s ETA 00:00
[download]   2.6% of 274.02KiB at  1.14MiB/s ETA 00:00
[download]   5.5% of 274.02KiB at  2.10MiB/s ETA 00:00
[download]  11.3% of 274.02KiB at  1.38MiB/s ETA 00:00
[download]  23.0% of 274.02KiB at  1.67MiB/s ETA 00:00
[download]  46.3% of 274.02KiB at  2.22MiB/s ETA 00:00
[download]  93.1% of 274.02KiB at  3.08MiB/s ETA 00:00
[download] 100.0% of 274.02KiB at  3.27MiB/s ETA 00:00
[download] 100% of 274.02KiB in 00:00
[ffmpeg] Correcting container in "TEST VIDEO-C0DPdy98e4c.m4a"
[ffmpeg] Destination: TEST VIDEO-C0DPdy98e4c.mp3
Deleting original file TEST VIDEO-C0DPdy98e4c.m4a (pass -k to keep)
[youtube] C0DPdy98e4c: Downloading webpage
2020-10-28 16:33:07.722789#Downloading Youtube video https://www.youtube.com/watch?v=C0DPdy98e4c complete
2020-10-28 16:33:07.722789#Downloading Metadata https://www.youtube.com/watch?v=C0DPdy98e4c
[download] Destination: TEST VIDEO-C0DPdy98e4c.m4a

[download]   0.4% of 274.02KiB at 143.29KiB/s ETA 00:01
[download]   1.1% of 274.02KiB at 429.88KiB/s ETA 00:00
[download]   2.6% of 274.02KiB at 1003.04KiB/s ETA 00:00
[download]   5.5% of 274.02KiB at  1.84MiB/s ETA 00:00
[download]  11.3% of 274.02KiB at 878.15KiB/s ETA 00:00
[download]  23.0% of 274.02KiB at  1.24MiB/s ETA 00:00
[download]  46.3% of 274.02KiB at  1.76MiB/s ETA 00:00
[download]  93.1% of 274.02KiB at  2.64MiB/s ETA 00:00
[download] 100.0% of 274.02KiB at  2.75MiB/s ETA 00:00
[download] 100% of 274.02KiB in 00:00
[ffmpeg] Correcting container in "TEST VIDEO-C0DPdy98e4c.m4a"
[ffmpeg] Destination: TEST VIDEO-C0DPdy98e4c.mp3
Deleting original file TEST VIDEO-C0DPdy98e4c.m4a (pass -k to keep)

When commenting out the sys.stdout line, i get this in the console:
2020-10-28 16:46:57.879111 # Downloading Youtube video https://www.youtube.com/watch?v=C0DPdy98e4c
[youtube] C0DPdy98e4c: Downloading webpage
[download] Destination: TEST VIDEO-C0DPdy98e4c.m4a
[download] 100% of 274.02KiB in 00:00
[ffmpeg] Correcting container in "TEST VIDEO-C0DPdy98e4c.m4a"
[ffmpeg] Destination: TEST VIDEO-C0DPdy98e4c.mp3
Deleting original file TEST VIDEO-C0DPdy98e4c.m4a (pass -k to keep)
2020-10-28 16:47:00.811446 # Downloading Youtube video https://www.youtube.com/watch?v=C0DPdy98e4c complete
2020-10-28 16:47:00.811446 # Downloading Metadata https://www.youtube.com/watch?v=C0DPdy98e4c
[youtube] C0DPdy98e4c: Downloading webpage
[download] Destination: TEST VIDEO-C0DPdy98e4c.m4a
[download] 100% of 274.02KiB in 00:00
[ffmpeg] Correcting container in "TEST VIDEO-C0DPdy98e4c.m4a"
[ffmpeg] Destination: TEST VIDEO-C0DPdy98e4c.mp3
Deleting original file TEST VIDEO-C0DPdy98e4c.m4a (pass -k to keep)
2020-10-28 16:47:02.566841 # Downloading Metadata https://www.youtube.com/watch?v=C0DPdy98e4c complete
2020-10-28 16:47:02.566841 # Checking altarnative arguments
2020-10-28 16:47:02.566841 # Cutting video https://www.youtube.com/watch?v=C0DPdy98e4c from 5 to 7
2020-10-28 16:47:02.715639 # Cutting video https://www.youtube.com/watch?v=C0DPdy98e4c from 5 to 7 complete
2020-10-28 16:47:02.715639 # Renaming file to test
2020-10-28 16:47:02.717630 # Renaming file to test complete

Why do the last couple of print statements not get saved into the file immediatly, but get printed out normally when im not using sys.stdout?

A: I haven't analyzed your code, but it sounds like you are being bitten by the buffering behaviour of files. Stuff that goes to a terminal is normally line buffered, but when you open a disk file, it gets buffered in larger chunks.
See the buffering argument to open


text:
Q: XCode: Where to put image resources I'm trying to add some App Icons and Launch Images for my App. My code-files are organized in groups inside Xcode and the same in the File System. I tried to drag a folder named Resources with my PNG images into my App and afterwards trying to add them as the App Icons and Launch Images for my App, but Xcode then gave me an warning and copied the file to the root of my project -- both in Xcode and File System.
Is it normal, that the Image are put in the root (in same level as the xcodeproj file)?

A: Yes it's OK. What can I suggest you is not to worry about filesystem and organize your files/directories within the project.
It's same as with iTunes: you don't care what and where your files are, but you have a nice interface to work with them.


text:
Q: Extracting the fitted terms in the local polynomial function of a loess (in R) (NOT predict()) How can I extract what the parameters that the loess function fitted for the polynomial function it uses, for a particular x of my data?
For example, in:
 cars.lo <- loess(dist ~ speed, cars)
 cars.lo

What did it fit for when cars.lo$x == 5 ?
Update: I want the parameters of the polynomial function, not the prediction (predict) of the loess.
I am asking for it to get an estimate of the slope in that point.
Thanks,
Tal

A: I would compute the predicted values at x, x+eps, x-eps, and then fit a quadratic to the results. It's not very efficient in computer time, but if you haven't got to do it very often, it is very efficient in programmer time.

A: I would say
predict(cars.lo, data.frame(speed=5))
[1] 7.797353

A: I think you're going to be on your own for this one.  I'd start by reading the references in lowess, and then read the source for the C lowess function.  I'd recommend starting there instead of with loess because it's an older and slightly simpler algorithm that you might find easier to adapt for your needs.


text:
Q: Container size is not the same as content when I use 'transform' I have a div called 'imgSlide' with a image inside. I set the image width to 100% cause I need it to rescale with the navigator size. Now, the problem comes when I use the 'transform' property, I move up the image but then it leaves a space.
Image to explain better my problem even more
I want to know how can I delete the space so the section below (yellow bar) can move up.
I would like a pure css solution but, if there is absolutely no way to make it possible with only css, I like to know how can I solve this in other ways.
PD: I don't want to use pixels or ems in container height because i need the container rescale when I shrink the navigator.
Edit: I uploaded new image, I think it explains correctly what I'm looking for.

#slide{
 transform: translateY(-20%);
}
#imgSlide img{
 display:block;
 width:100%;
}
#content{
 height:50px;
 background:yellow;
}

A: If I understand your question, you could wrap both the image and the content in a "container". Then apply the transform on this new container. That means you would transform the container containing BOTH the image and the content. I made an example fiddle for you: https://jsfiddle.net/7ye5q8ke/2/
HTML:

CSS:
#slide{

}
#imgSlide img{
    display:block;
    width:100%;
}
#content{
    height:50px;
    background:yellow;
}

#container{
  transform: translateY(-20%);
}

Edit:
Noticed the fiddle was not working. Updated fiddle

Edit 2:
In your comment you're asking if it's semantically correct, it's not. If the section "content" actually is meant for image title, image description and so on, they should be inside the same section. The section attribute is meant for grouping together thematically related content. Meaning the section "content" should be inside the section "slide". Like so:

      ...

Now both the image content and the image are in the same section. Should be semantically correct. Check out this link http://oli.jp/2009/html5-structure1/


text:
Q: C++ string swap character places is there a way to swap character places in a string? For example if I have "03/02" I need to get "02/03".
Any help is appreciated!

A: Sure:
#include <string>
#include <algorithm>

std::string s = "03/02";
std::swap(s[1], s[4]);

A: std::swap(str[1], str[4]);

A: There is. :)
std::swap(str[i], str[j])

A: Wait, do you really want such a specific answer? You don't care about if the string is 2/3 instead of 02/03?
#include <string.h>
#include <iostream>

bool ReverseString(const char *input)
{
    const char *index = strchr(input, (int) '/');
    if(index == NULL)
        return false;

    char *result = new char[strlen(input) + 1];

    strcpy(result, index + 1);
    strcat(result, "/");
    strncat(result, input, index - input);

    printf("%s\r\n", result);
    delete [] result;

    return true;
}

int main(int argc, char **argv)
{
    const char *test = "03/02";
    ReverseString(test);
}


text:
Q: Magento 2 Field dependency in ui form I have created a ui component form. I want to display some fields based on status value. Display other fields only if status is 1.  How Can I achieve it?
Here is my code
<field name="status">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Status</item>
                <item name="visible" xsi:type="boolean">true</item>
                <item name="dataType" xsi:type="string">number</item>
                <item name="formElement" xsi:type="string">select</item>
                <item name="source" xsi:type="string">status</item>
                <item name="dataScope" xsi:type="string">status</item>
                <item name="validation" xsi:type="array">
                    <item name="required-entry" xsi:type="boolean">true</item>
                </item>
                <item name="options" xsi:type="array">
                        <item name="0" xsi:type="array">
                            <item name="label" xsi:type="string">Pending</item>
                            <item name="value" xsi:type="string">0</item>
                        </item>
                        <item name="1" xsi:type="array">
                            <item name="label" xsi:type="string">Allowed</item>
                            <item name="value" xsi:type="string">1</item>
                        </item>
                        <item name="2" xsi:type="array">
                            <item name="label" xsi:type="string">Not Allowed</item>
                            <item name="value" xsi:type="string">2</item>
                        </item>
                </item>
            </item>
        </argument>
    </field>
    <field name="title">
         <argument name="data" xsi:type="array">
             <item name="config" xsi:type="array">
                 <item name="label" xsi:type="string">Title</item>
                 <item name="visible" xsi:type="boolean">true</item>
                 <item name="dataType" xsi:type="string">text</item>
                 <item name="formElement" xsi:type="string">textarea</item>
                 <item name="source" xsi:type="string">title</item>
                 <item name="required" xsi:type="boolean">true</item>
                 <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                 </item>
             </item>
         </argument>
    </field>
    <field name="category_ids">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Magento\Catalog\Ui\Component\Product\Form\Categories\Options</item>
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Category</item>
                    <item name="componentType" xsi:type="string">field</item>
                    <item name="formElement" xsi:type="string">select</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="component" xsi:type="string">Magento_Catalog/js/components/new-category</item>
                    <item name="elementTmpl" xsi:type="string">ui/grid/filters/elements/ui-select</item>
                    <item name="filterOptions" xsi:type="boolean">true</item>
                    <item name="showCheckbox" xsi:type="boolean">true</item>
                    <item name="disableLabel" xsi:type="boolean">true</item>
                    <item name="multiple" xsi:type="boolean">true</item>
                    <item name="levelsVisibility" xsi:type="number">1</item>
                    <item name="required" xsi:type="boolean">false</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">false</item>
                    </item>
                    <item name="listens" xsi:type="array">
                        <item name="${ $.namespace }.${ $.namespace }:responseData" xsi:type="string">setParsed</item>
                    </item>
                </item>
            </argument>
        </field>
        <field name="custom_field">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Custom Field</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="dataType" xsi:type="string">number</item>
                    <item name="formElement" xsi:type="string">select</item>
                    <item name="source" xsi:type="string">custom_field</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">false</item>
                    </item>
                    <item name="options" xsi:type="array">
                        <item name="0" xsi:type="array">
                            <item name="label" xsi:type="string">No</item>
                            <item name="value" xsi:type="string">0</item>
                        </item>
                        <item name="1" xsi:type="array">
                            <item name="label" xsi:type="string">Yes</item>
                            <item name="value" xsi:type="string">1</item>
                        </item>
                    </item>
                </item>
            </argument>
        </field>

A: I have added a js component in the status field
  <field name="status">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Statu

    s</item>
                        <item name="visible" xsi:type="boolean">true</item>
                        <item name="dataType" xsi:type="string">number</item>
                        <item name="formElement" xsi:type="string">select</item>
                        <item name="source" xsi:type="string">status</item>
                        <item name="dataScope" xsi:type="string">status</item>
                        <item name="component" xsi:type="string">NameSpace_Modulename/js/form/element/options</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                        <item name="options" xsi:type="array">
                                <item name="0" xsi:type="array">
                                    <item name="label" xsi:type="string">Pending</item>
                                    <item name="value" xsi:type="string">0</item>
                                </item>
                                <item name="1" xsi:type="array">
                                    <item name="label" xsi:type="string">Allowed</item>
                                    <item name="value" xsi:type="string">1</item>
                                </item>
                                <item name="2" xsi:type="array">
                                    <item name="label" xsi:type="string">Not Allowed</item>
                                    <item name="value" xsi:type="string">2</item>
                                </item>
                        </item>
                    </item>
                </argument>
            </field>
            <field name="title">
                 <argument name="data" xsi:type="array">
                     <item name="config" xsi:type="array">
                         <item name="label" xsi:type="string">Title</item>
                         <item name="visible" xsi:type="boolean">true</item>
                         <item name="dataType" xsi:type="string">text</item>
                         <item name="formElement" xsi:type="string">textarea</item>
                         <item name="source" xsi:type="string">title</item>
                         <item name="required" xsi:type="boolean">true</item>
                         <item name="validation" xsi:type="array">
                                <item name="required-entry" xsi:type="boolean">true</item>
                         </item>
                     </item>
                 </argument>
            </field>
           ................

NameSpace/Modulename/view/adminhtml/web/js/form/element/options.js
define([
    'underscore',
    'uiRegistry',
    'Magento_Ui/js/form/element/select',
    'Magento_Ui/js/modal/modal'
], function (_, uiRegistry, select, modal) {
    'use strict';
    return select.extend({

        initialize: function (){

            var field1 = uiRegistry.get('index = title');
            var field2 = uiRegistry.get('index = custom_field');
            var status = this._super().initialValue;
            if (status == 1) {
                field1.show();
                field2.show();
            } else{
               field2.hide();
               field1.hide();
            }
            return this;

        },

        /**
         * On value change handler.
         *
         * @param {String} value
         */
        onUpdate: function (value) {

            var field1 = uiRegistry.get('index = title');
            var field2 = uiRegistry.get('index = custom_field');
            var field3 = uiRegistry.get('index = category_ids');
            if (value == 1) {
                field1.show();
                field2.show();
                field3.show();

            } else {
                field1.hide();
                field2.hide();
                field3.hide();

            }
            return this._super();
        },
    });
});


text:
Q: Find and replace a pattern after last space I need to replace any matching pattern after the last space. I've an ssh certificate file like:
ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgePsBdieYnkI6dvMLG5qAl+UnOXo8mV0JmthWTNZ7+REAAAADAQABAAABAQC0aFhFni8pfoRiwt5O1ZVU6G0Xb+iX3D+A7uEItzLAygf7V/Se6tUg3SlUWf85G4S5vceZzbzTXbNso+vCaYc+RA0xwaxDBDHomdJVzpK/TUL+lV63V51vhvaM2redU+fYDGuUHUbVjt0Y4qaHBr6R4Rh0GujbL6U+/eq1yQ52VGD34f1eldt56xvykP1HAfs158oDcCL1lnJ26SPMzN38X6RCl/vAZn8UmOntmpa2LVT+j8kf1lKAQdpGYGbwZybo8LCYL2lyv3LTw1slULZsoKnazuZOKoaTxEziJfvr79jS9sNctqxBMPkeTDxUuLdd3URpiCCfpRcmKH+owAz3AAAAAAAAAAAAAAACAAAAGHZtdHN0aWlxMS5jZWRlbGdyb3VwLmNvbQAAACkAAAAYdm10c3RpaXExLmNlZGVsZ3JvdXAuY29tAAAACXZtdHN0aWlxMQAAAABfaeD6AAAAAGFxvY= ssh_host_rsa_key.pub

Here, at the end of the file I've ssh_host_rsa_key.pub or it can be something different like /home/user/ssh_host_rsa_key.pub. I want to find it and replace by another string.
How can I find and replace everything starting from last space? With sed or awk or anything else...
Thanks in advance.

A: You could try
sed -E 's/(^.*) [^ ]+$/\1 replacement_text/' file.txt

This will match

*

*"anything from the start of the line" (the ^.* pattern, placed in a "capture group" ( ... )),

*then a space,

*and then "anything but a space ([^ ]) up to the end of the line" (the + behind the [...] means "one or more such characters", and the $ is an anchor that indicates "end-of-line"),

and replace the latter part with your replacement text. The former part is replaced "with itself" thanks to the capture group \1.

A: This works when there are two space delimited fields at the start of the line. The third field is allowed to be absent.
awk '{print $1 " " $2 " new text"}' < file

This replaces after the last space no matter how many spaces there are in the line:
sed 's/ [^ ]*$/ new text/' < file


text:
Q: make the scope values same after location.path() On click of a button I want to change the template with the same model value. I am using location.path to change the template.
Plunk- http://plnkr.co/edit/FVkSj2vs8WDAt1eifBpF?p=preview
app.js
var app = angular.module('includeExample', ['ngRoute']);

   app.config(function($routeProvider) {
        $routeProvider

            // route for the about page
            .when('/template2', {
                templateUrl : 'template2.html',
                controller  : 'ExampleController'
            })

    });

app.controller('mainController', [function($scope) {

}]);

  app.controller('ExampleController', [function($location, $scope) {

    $scope.locationChange = function(){
      $location.path('/template2');

    }

  }]);

template1.html
Content of template1.html

<input ng-model="x"/>
<button ng-click='locationChange()'> Submit</button>
{{x}}

A: Consider using the ngSwitch directive. You could use it like this:

And then maintain scope.location (set it to either template1 or template2) when clicking your button.

A: Create a service that caches the $scope.
.factory('appData', [function() {
  var cache = {};
  return {
    set: function(location, payload) {
      cache[location] = payload;
    },
    get: function(location) {
      return cache[location];
    },
    clear: function() {
      cache = {};
    }
  };
});

Then in your controller/directive, simply include appData as a dependency and call
appData.set('cacheScope', $scope);

And to retrieve it:
$scope = appData.get('cacheScope');


text:
Q: Count MySQL results in PHP with filters I currently have 12 SQL queries (all are COUNT (*) ones) per team member and there are around 100 team members running on a database to pull out some live stats for the managers, however this is killing the system it's running on whenever the page is loaded, what I'd like to do is do 1 query and then filter those results using PHP to take the load off the database but I cannot figure out how to do this.
current query:
select count(*) from opencall use index (logdatex)
where closedby = '$UsersName' and priority = 'P2' and withinfix = 0
and logdatex between $startOfLastMonth and $endOfLatMonth
and status IN (6, 16, 18)

we run this for 2 different time periods (last month & yesterday) each with 3 different priorities and 2 withinfix per user. What I'd like to do is something like this
select logdatex, closedby, withinfix, suppgroup
from opencall use index (logdatex)
where closedby = '$UsersName'
and logdatex between $startOfLastMonth and $midnightYesterday
and status IN (6, 16, 18)

and then in PHP do a count where username = XXXX && withinfix = 1 && logdatex => yesterday morning && logdatex <= midnightyesterday.

A: Try this:
SELECT
    closedby, priority, withinfix
FROM
    opencall
WHERE
    -- Specify the list of users if you want to limit them
    closedby IN ('user1', 'user2', 'user99', 'user100') AND

    -- Specify the possible priorities here
    priority IN ('P1', 'P2', 'P3') AND

    -- Specify the allowed withinfix here
    withinfix IN (0, 1, 2) AND

    logdatex between '$startOfLastMonth' AND '$endOfLastMonth' AND
    status IN (6, 16, 18)

    -- This is where you need the grouping of the results
    GROUP BY closedby, priority, withinfix;

That should group your result set by the filters you need.
I'm not sure what you mean by the two time periods so I left that out from the combined query. However, I'm sure we can put that in if needed.
For your reference: MySQL documentation on GROUP BY.


text:
Q: How to maintain page position on window.location change? var scroll = $(window).scrollTop();
        $('html').scrollTop(scroll);

Whenever i use the code beow, the position of my page will move to the top. I tried using the code above but it will only maintain position on refresh. How can i do so with window.location?
$myid = $(this).val();

window.location = '?myid=' + myid;

A: You can do by adding id element to html element based on id which you are passing in url like below.
for example in url myid is 7. Add id to any html element like
<div id="section-<?ph echo (isset($_GET['myid']) && $_GET['myid'] != '') ? $_GET['mid'] : ''; ?>">
....
</div>

and in end of the file add below js code like below.
<?php
if(isset($_GET['myid']) && $_GET['myid'] != ''){
echo "<script>$('#section-'<?php echo $_GET['myid'];?>).animate({ scrollTop: $(hashText).offset().top }, 1000);</script>";
}
?>

after page load, page will scroll to that particular section. Hope this will help you.


text:
Q: PHP RewriteRule detect if url contain "string" and replace This may be a basic question regarding RewriteRule but I just counldn't make it work.
What I want to do is detect urls like:
mydomain/myapp/id/some/random/url.html?param=somethingThatIdoUse
mydomain/myapp/id/other/randomabc/perrito.php?param=somethingThatIdoUse
...

The part that I need to discart is from the /id/[all this]?param=somethingIdoUse and use the param if is possible or send the complete url as param so I can regex to get the param.
And have a rule that detect that /id/ exist and redirect to something like:
mydomain/myapp/other/manageRequest.php?params=somethingThatIdoUse

(the params I could get the whole url and strip it as string is no problem)
As well the application have different modules like:
mydomain/myapp/moduleOne/index.php
mydomain/myapp/moduleTwo/index.php

This have to keep working the same.
As far I've tried some of them like:
RewriteEngine On
RewriteCond %{THE_REQUEST} ^GET /.*;.* HTTP/
RewriteCond %{QUERY_STRING} !^$
RewriteRule .* http://localhostdev/app/index.php %{REQUEST_URI}? [R=301,L]

RewriteEngine On
RewriteBase /spt/
RewriteCond %{REQUEST_FILENAME} !^id$ [NC]
RewriteRule ^(.*)$ index.php [R=301,L]

RewriteEngine On
RewriteCond %{REQUEST_URI} !/campaings/response\.php$
RewriteRule ^/something/(.*) /other/manageRequest.php? [L]

But nothing seamed to do kind of what I needed.
Thanks in advice

A:
mydomain/myapp/id/some/random/url.html?param=somethingThatIdoUse

Here is an example using the above URL:
RewriteRule ^id/some/random/url.html/?  /myapp/other/manageRequest.php [L,NC]

The query will be passed through unchanged to the substitution URL

A: well actually end up being really basic it worked with:
RewriteRule ^.*id.*$ handleRequest.php [NC,L]

I do get the params as they are sent!


text:
Q: How do i write a shell script for checking website live or not I am writing a shell script to monitor website live or not and send an email alert below is my code
#!/bin/bash
if [[ curl -s --head  --request GET http://opx.com/opx/version | grep "200 OK" > /dev/null] && [ curl -s --head --request GET http://oss.com/version | grep "200 OK" > /dev/null ]]
then echo "The HTTP server on opx.com and oss.com is up!" #> /dev/null
else
msg="The HTTP server  opx.com Or oss.com is down "
email="opx-noc@opx.com"

curl --data "body=$msg &to=$email &subject=$msg" https://opx.com/email/send
fi;

if i run this code i got
./Monitoring_Opx_Oss: line 2: conditional binary operator expected
./Monitoring_Opx_Oss: line 2: syntax error near `-s'
./Monitoring_Opx_Oss: line 2: `if [[ curl -s --head  --request GET http://opx.com/opx/version | grep "200 OK" > /dev/null] && [ curl -s --head --request GET http://oss.com/version | grep "200 OK" > /dev/null ]] '

Please correct me...

A: Change it do this:
if [ $(curl -s --head  --request GET http://opx.opera.com/opx/version | grep "200 OK" > /dev/null) ] && [ $(curl -s --head --request GET http://oss.opera.com/version | grep "200 OK" > /dev/null) ]

To check the status of a command inside an if, you have to do it like
if [ $(command) ]

while you were using
if [ command]

note also the need of spaces around [ ]: if [_space_ command _space_ ]
Update
Based on Ansgar Wiechers's comment, you can also use the following:
if curl -s --head  --request GET http://opx.com/opx/version | grep "200 OK" > /dev/null && curl -s --head --request GET http://oss.com/version | grep "200 OK" > /dev/null;

That is,
if command && command


text:
Q: como arreglar sopa de letras No puedo solucionar este error que me marca al realizar mi matriz/sopa de letras

Traceback (most recent call last):   File
"c:\Users\Usuario\Desktop\menu.py", line 15, in
matriz_alfabeto[i][j] = alfabeto[random.randint(0,25)] TypeError: 'NoneType' object does not support item assignment PS
C:\Users\Usuario\Desktop\p>

y este es el codigo:
import random

alfabeto = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

matriz_alfabeto = [None] * 10

palabra_1 = ["p","r","o","g","r","a","m","a"]
palabra_2 = ["v","a","r","i","a","b","l","e"]

for i in range(0,10):
    matriz_alfabeto = [None] * 10

for i in range(0,10):
    for j in range(0,10):
        matriz_alfabeto[i][j] = alfabeto[random.randint(0,25)]

for i in range(8):
    matriz_alfabeto[i][0] = palabra_1[i]
    matriz_alfabeto[9][i] = palabra_2[i]

print(matriz_alfabeto)

A: Tu error se encuentra en este sector:
for i in range(0,10):
    matriz_alfabeto = [None] * 10

Aqui lo que haces es establecer el valor de matriz_alfabeto a [None]*10 cada vez que el for se ejecuta.
Leyendo tu comentario, supongo que lo que buscabas hacer era asignar [None]*10 a cada item de matriz_alfabeto. Para eso tendrías que hacer así:
for i in range(0,10):
    matriz_alfabeto[i] = [None] * 10


text:
Q: Redux updating nested immutable data I have an issue with updating the immutable redux and quite nested data. Here's an example of my data structure and what I want to change. If anyone could show me the pattern of accessing this update using ES6 and spread operator I would be thankful.
My whole state is an object with projects (key/value pairs - here as an example only one project) that are objects with its own key (and the keys are ids as well), arrays of procedures and inside the tasks:
{ 1503658959473:
  { projectName: "Golden Gate",
    projectLocation": "San Francisco",
    start:"22/09/1937",
    id:1503658959473,
    procedures:[
      { title: "Procedure No. 1",
        tasks:[
          {name: "task1", isDone: false},
          {name: "task2", isDone: false},
          {name: "task3", isDone: false}
        ]
      }
    ]
  }
 }

What I'm willing to do is to update one single task 'isDone' property to 'true'. It's some kind of toggling the tasks. How can I return this state with that information updated?
The action creator pass this information to reducer:
export function toggleTask(activeProject, task, taskIndex) {
 return {
    type: TOGGLE_TASK,
    payload: {
        activeProject,
        task,
        taskIndex
    }
 };

}

A: You've run into a common issue with Redux. The docs recommend that you flatten your data structure to make it easier to work with, but if that's not what you want to do, I'd refer to this part of their docs.
Because both Object.assign() and the ...spread operator create shallow copies, you must go through each level of nest in your object and re-copy it.
Your code might look something like this...
function updateVeryNestedField(state, action) {
    return {
        ...state,
        procedures : {
            ...state.procedures,
            tasks : {
               return tasks.map((task, index) => {
                 if (index !== action.taskIndex) {
                   return task
                 }
                 return {
                   ...task,
                   task.isDone: !task.isDone
                 }
               }
            }
        }
    }
}

A: I myself would create a new class called ProjectModel, which has a public method toggleTask that is able to update its task's status. The reducer state would be an object whose keys are project IDs and values are ProjectModel instances.


text:
Q: qemu error while running my boot I wrote a short boot code and tried to run it with Qemu with:

qemu-system-arm.exe -M versatilepb -cpu cortex-a9 -kernel boot.bin

I expected the code to be loaded to address 0x8400000 but qemu returned me the error

Trying to execute code outside RAM or ROM at 0x84000000
  This usually means one of the following happened:
(1) You told QEMU to execute a kernel for the wrong machine type, and it crashed on startup (eg trying to run a raspberry pi kernel on a versatilepb QEMU machine)
  (2) You didn't give QEMU a kernel or BIOS filename at all, and QEMU executed a ROM full of no-op instructions until it fell off the end
  (3) Your guest kernel has a bug and crashed by jumping off into nowhere
This is almost always one of the first two, so check your command line and that you are using the right type of kernel for this machine.
  If you think option (3) is likely then you can try debugging your guest with the -d debug options; in particular -d guest_errors will cause the log to include a dump of the guest register state at this point.
Execution cannot continue; stopping here.

So I guess my code has not yet started running because it is not loaded into the right place
What am I wrong about?
Thanks

A: You say "I expected the code to be loaded to address 0x8400000" but QEMU's error message says "0x84000000" which is not the same number (it has an extra 0). This suggests that you have a typo in your linker script or whatever is creating your boot.bin file. (I am assuming that boot.bin is an ELF file, which QEMU loads at the addresses the ELF file specifies, because otherwise it will be loaded into RAM anyhow on the assumption that it's a Linux kernel image capable of self-relocation.)


text:
Q: Source for Esri sample data from 911 Hot Spot Analysis I was trying to replicate the Hot Spot Analysis (Getis-Ord Gi*) from Esri, but cannot find the shapefile, like the "911Count.shp", "911HotSpots.shp", etc. Can somebody tell me where I can download these shapefiles?

A: For reference, the 911Count.shp you're asking about is from the tool help, specifically within the Python snippets.
Eg.
arcpy.HotSpots_stats("911Count.shp", "ICOUNT", "911HotSpots.shp",
                     "GET_SPATIAL_WEIGHTS_FROM_FILE", "EUCLIDEAN_DISTANCE",
                     "NONE", "#", "#", "euclidean6Neighs.swm", "NO_FDR")

These python snippets have been produced to show how the tool can be used. The data referenced here in this is made up / non-existent. The person who documented the tool may have the actual dataset when they wrote the snippet, but the data is not part of some master database available for download. The 911count.shp input data could have said purpleMonkeyDishWasher.shp if the document author was so inclined.
The link that @smiller references in the comment (https://www.arcgis.com/home/item.html?id=02b7dddf672f40c4b0129aa7420105d9) provides similiar data (911 calls) and will work with the tool in question (Hot Spot Getis-Ord Gi*). I will point out though, that this dataset on ArcGIS.com and the 911Count from the Python snippet are merely coincidental. I don't believe the attributes found inside the arcgis.com data will match the python snippet. You'll need to update those.


text:
Q: Repayments of a loan with compound interest Suppose I have a loan of M dollars. At the end of each year, I am charged interest at rate R and make a repayment of P. The loan is repaid after n years.

*

*How long (n) does it take to repay the loan if I am given the other variables?

*How much are the repayments of P if I am given the other variable?

*Suppose that the payments were at the start of the year. How would this change the problem?

A: Basic Theory
The way to solve this problem is to calculate how much each payment reduces your debt after you have been repaying your loan for $n$ years. Let $r=1+R/100$, ie. this converts the interest rate from a percentage to a value you can multiply your debt by to calculate how much you owe after adding one time period's interest.
If I make a payment of $P$ at the end of the $k$th year, then we avoid paying interest on this money $n-k$ times and so we reduce our debt by $Pr^{n-k}$. We sum up the future values of all our payments:
$\sum\limits_{k=1}^n Pr^{n-k}$
If we reverse this, it is equivalent to:
$\sum\limits_{k=0}^{n-1} Pr^k$
This is a geometric series, which can be solved using the formula $\frac{ar^{n-1}}{r-1}$ where $a$ is the first term, $r$ is the factor and $n$ is the number of terms being summed. We then attempt to equate this with the debt owed after $n$ years, which is $Mr^n$.
We now compare the two equations:
$\frac{Pr^{n-1}}{r-1} = Mr^n$
Calculating $n$
We group the $r^n$ terms:
$\frac{P}{r-1} = r^n\frac{M-P}{r-1}$
$r^n = \frac{P}{M(r-1)-P}$
So we just take the $n$th log of the right hand side.
Calculating repayments
Given the principal ($M$) and the interest rate ($r$), what will my payment-per-term ($P$) be over $n$ accruation terms?
$P=\frac{Mr^n(r-1)}{r^{n-1}}$
Payments made at the start of the year
In this case, the future values of our interest payment simply become:
$\sum\limits_{k=1}^n Pr^k$
We proceed as we did before.
Notes
We could also solve this problem using present value instead of future value.

A: Suggest you look into amortization calculators.


text:
Q: Change the value of a json object in Node.js with process.env I'm learning Node.js atm and am trying to change the response of an app request, depending on certain parameters. For instance if I set the MESSAGE_STYLE to uppercase I want the value of the (single) key in the json object to become uppercase. However I can't seem to change the object. I'm not reading the value as a string it seems, so to toUpperCase() doesn't work.
After reading this article I tried JSON.parse and then JSON.dump but that didn't work either (unless I did it wrong). Help is much appreciated!
THIS DOESN'T WORK
process.env.MESSAGE_STYLE='uppercase';

app.get('/json', function(req, res){
var response = res.json({
  "message": "Hello json"
});

if(process.env.MESSAGE_STYLE==='uppercase'){
  response.message.toUpperCase();
  return response;
} else {
  return response;
  };
});

BUT THIS DOES
process.env.MESSAGE_STYLE='uppercase';

app.get('/json', function(req, res){

if(process.env.MESSAGE_STYLE==='uppercase'){
  res.json({
  "message": "HELLO JSON"
})
} else {
    res.json({
  "message": "Hello json"
})
  };
});

A: You have assigned the response object but it needs to be overridden to get your latest changes in response.message attribute.
process.env.MESSAGE_STYLE='uppercase';

app.get('/json', function(req, res){
// Variable assignment as object
var response = {
  "message": "Hello json"
};

if(process.env.MESSAGE_STYLE==='uppercase'){
  //Override message attribute value based on condition
  response.message = response.message.toUpperCase();
}

return res.json(response);
});


text:
Q: Return data AJAX PHP By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.

This is my AJAX call:

 $("#botao-filtrar").click(function(){
  $(".mask-loading").fadeToggle(1000);
  $.ajax({
    url: 'datacenter/functions/filtraDashboardGeral.php',
    type: 'POST',
    data: {rede: $("#dropdown-parceria").val()},
  })
  .done(function(resposta){
    console.log(resposta);
  })
  .always(function(){
    $(".mask-loading").fadeToggle(1000);
  })
});

And this is what I got from trying to filter some data to return it,
  but nothing worked:

<?php
    require_once('../../includes/conecta.php');

    $rede = $_POST['rede'];

    function buscaDados($conexao){
        $dados = array();

        $resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");

        while($valores = mysqli_fetch_assoc($resultado)){
            array_push($dados, $valores);
        }
    }

Any idea?
Thanks!

A: You should add echo at the end :
echo json_encode($dados);

So the $dados array will be sent back to the ajax request as JSON response.
Parse the response to json uisng $.parseJSON() :
.done(function(resposta){
     resposta = $.parseJSON(resposta);

     console.log(resposta);
})

Hope this helps.

A: in your ajax code u add a success.
$("#botao-filtrar").click(function(){
  $(".mask-loading").fadeToggle(1000);
  $.ajax({
    url: 'datacenter/functions/filtraDashboardGeral.php',
    type: 'POST',
    dataType: 'json',
    data: {rede: $("#dropdown-parceria").val()},
    success: function (data) {

    //You do not need to use  $.parseJSON(data).  You can immediately process data as array.
    console.log(data)

    //if you have a array you use the following loop

     for (var j =0;j < data.length;j++) {

    console.log(data[j]);
    // u can use data[j] and write to any fields u want.
    // e.g.
    $('.somediv').html(data[j].myarraykey);

     }

  })
  .done(function(resposta){
    console.log(resposta);
  })
  .always(function(){
    $(".mask-loading").fadeToggle(1000);
  })
});

And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.

$rede = $_POST['rede'];

    $dados = array();

    $resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");

    while($valores = mysqli_fetch_assoc($resultado)){
        array_push($dados, $valores);
    }
    echo json_encode($dados);
    die();


text:
Q: Create several new variables using a vector of names and a vector for computation within dplyr::mutate I'd like to create several new columns. They should take their names from one vector and they should be computed by taking one column in the data and dividing it by another.
mytib <- tibble(id = 1:2, value1 = c(4,6), value2 = c(42, 5), total = c(2,2))
myvalues <- c("value1", "value2")
mynames  <- c("value1_percent", "value2_percent")

mytib %>%
     mutate({{ mynames }} := {{ myvalues }}/total)

Here, I get the error message, which makes me think that the curly-curly operator is misplaced

Error in local_error_context(dots = dots, .index = i, mask = mask) : promise already under evaluation: recursive default argument reference or earlier problems?

I'd like to calculate the percentage columns programmatically (since I have many such columns in my data).
The desired output should be equivalent to this:
mytib %>%
    mutate( "value1_percent" = value1/total, "value2_percent" = value2/total)

which gives
# A tibble: 2 × 6
     id value1 value2 total value1_percent value2_percent
  <int>  <dbl>  <dbl> <dbl>          <dbl>          <dbl>
1     1      4     42     2              2           21
2     2      6      5     2              3            2.5

A: You could use across and construct the new names in its .names argument:
library(dplyr)

mytib %>%
    mutate(across(starts_with('value'),
                  ~ .x / total,
                  .names = "{.col}_percent"
                  ))

A: I prefer mutate(across(...)) in this case. To make your idea work, try reduce2() from purrr.
library(dplyr)
library(purrr)

reduce2(mynames, myvalues,
        ~ mutate(..1, !!..2 := !!sym(..3)/total), .init = mytib)

# # A tibble: 2 x 6
#      id value1 value2 total value1_percent value2_percent
#   <int>  <dbl>  <dbl> <dbl>          <dbl>          <dbl>
# 1     1      4     42     2              2           21
# 2     2      6      5     2              3            2.5

The above code is actually a shortcut of:
mytib %>%
  mutate(!!mynames[1] := !!sym(myvalues[1])/total,
         !!mynames[2] := !!sym(myvalues[2])/total)


text:
Q: Weird Identities with Scalar Product & Transpose: $\vec{a}\cdot\vec{b} = \vec{b}^T \cdot {a}^T$, $\vec{a}^T \cdot \vec{b} = \vec{b}^T \cdot \vec{a} $? Let's say I have a row vector $\vec{a}$ and a column vector $\vec{b}$:
\begin{align}
\vec{a}= \begin{pmatrix}4 & 5 & 6\end{pmatrix} \qquad \vec{b} = \begin{pmatrix}1\\2\\3\end{pmatrix}
\end{align}
Now if I want to calculate a scalar product, it is easy for $\vec{a} \cdot \vec{b}= \begin{pmatrix}4 & 5 & 6\end{pmatrix}\begin{pmatrix}1\\2\\3\end{pmatrix} = \begin{pmatrix}4\cdot1+ 5\cdot 2 + 6\cdot 3\end{pmatrix} = 32.$
but it is not as easy for $\vec{b}\cdot \vec{a}$ where the scalar product is undefined:
\begin{align}
\vec{b}\cdot \vec{a} = \begin{pmatrix}1\\2\\3\end{pmatrix} \begin{pmatrix}4 & 5 & 6\end{pmatrix} \qquad{\scriptsize\text{Not defined!}}
\end{align}
So if I take a transpose of both of the vectors I get:
\begin{align}
\vec{b}{\hspace{0.4mm}}^\mathsf{T}\cdot \vec{a}{}^\mathsf{T} = \begin{pmatrix}1&2&3\end{pmatrix} \begin{pmatrix}4 \\ 5 \\ 6\end{pmatrix} = \begin{pmatrix}1\cdot4 + 2 \cdot 5 + 3 \cdot 6\end{pmatrix} = 32
\end{align}
So I get a relation that $\vec{a}\cdot\vec{b} = \vec{b}^T \cdot {a}^{T} = 32$. But why do I find a different equation on Wikipedia which says: $(\vec{a}\cdot\vec{b} ){}^\mathsf{T}= \vec{b}{}^\mathsf{T} \cdot \vec{a}{\hspace{0.4mm}}^\mathsf{T}$?

EDIT: If i do it like @Samuel says i define original vectors differently:
\begin{align}
\vec{a}= \begin{pmatrix} 4\\ 5 \\ 6 \end{pmatrix} \qquad \vec{b}= \begin{pmatrix} 1\\ 2 \\ 3 \end{pmatrix}
\end{align}
And now i try to calculate $\vec{a} \cdot \vec{b}$ which is not defined. I can calculate ${\vec{a}}^T \vec{b}$ though:
\begin{align}
{\vec{a}}^T \cdot \vec{b}= \begin{pmatrix} 4& 5 &6 \end{pmatrix} \begin{pmatrix} 1\\ 2 \\ 3 \end{pmatrix} = 4\cdot 1 + 5\cdot 2 + 6 \cdot 3 = 32
\end{align}
Now i try to calculate scalar product $\vec{b} \cdot \vec{a}$ and neither this one is defined. But i can calculate ${\vec{b}}^T\cdot \vec{a}$ though:
\begin{align}
{\vec{b}}^T \cdot \vec{a}= \begin{pmatrix} 1& 2 &3 \end{pmatrix} \begin{pmatrix} 4\\ 5 \\ 6 \end{pmatrix} = 1\cdot 4 + 2\cdot 5 + 3 \cdot 6 = 32
\end{align}
So now i can say ${\vec{a}}^T \cdot \vec{b} = {\vec{b}}^T \cdot \vec{a} $. So this now is a lot wierder and i cant find it on Wikipedia.

A: A vector should always be a column vector. If you want to talk about a "row vector", you should write it as the transpose of some vector, or as a matrix with just one row.
I will add that, technically, the scalar product can not be written as a matrix product the way you are doing it. If $u,v$ are vectors, then the matrix product $u^T v$ is a $1\times 1$-matrix, whereas the scalar product $u\cdot v$ is a scalar. It is common to ignore this and consider them the same, but one should sometimes be careful when using this, for example when one wants to multiply the scalar product with a matrix.
Added: You cannot say that $a$ is a vector and then write $a=(4,5,6)$ as a row matrix. You can however say that $a$ is a $1\times 3$-matrix $(4,5,6)$, or that $a$ is a vector and $a^T=(4,5,6)$ (and in the latter case, $a$ is a column vector). Let us suppose that you defined the matrices $a=(4,5,6)$ and $b=\begin{pmatrix}1\\2\\3\end{pmatrix}$. Now, the matrix product $a\cdot b$ is equal to the $1\times 1$-matrix $[32]$, not the number 32, which is the scalar product of the vectors $\begin{pmatrix}4\\5\\6\end{pmatrix}$ and $\begin{pmatrix}1\\2\\3\end{pmatrix}$. Likewise, the matrix product $b^T\cdot a^T$ is equal to the $1\times 1$-matrix $[32]$. Then we can conclude that $a\cdot b=b^T\cdot a^T$ (note that you made a typo in your post and wrote $a^T\cdot b^T$ for the right-hand-side). This is consistent with Wikipedia, which states that $(a\cdot b)^T=b^T\cdot a^T$. However, your typo is also correct in this particular case, namely $(a\cdot b)^T=a^T\cdot b^T$, but this is only because both matrices are $1\times 1$-matrices, so they are equal to their own transposes.
Added after the edit: You get the identity $a^T\cdot b=b^T\cdot a$. This equation is not true for general matrices $a,b$, so you will not find it on Wikipedia. What is generally true, however, is the identity $(a^T\cdot b)^T=b^T\cdot a$. The reason your identity is true is because both matrices are $1\times 1$-matrices, and the transpose of a $1\times 1$-matrix does not change the matrix.

A: Vectors have a notation, they can be written only as a column matrix. In case of multiplying two such vectors, matrix multiplication is not defined as both would be 3x1 matrices.
\begin{gather}
\vec{u} = \left[ \begin{array}{c}
u_1 \\
u_2 \\
u_3 \\
\end{array} \right] & \vec{v} = \left[ \begin{array}{c}
v_1 \\
v_2 \\
v_3 \\
\end{array} \right]
\end{gather}
Then the following is not defined -
\begin{gather}
\vec{u}\cdot \vec{v} = \left[ \begin{array}{c}
u_1 \\
u_2 \\
u_3 \\
\end{array} \right] \cdot \left[ \begin{array}{c}
v_1 \\
v_2 \\
v_3 \\
\end{array} \right]
\end{gather}
A dyadic multiplication is defined, which gives rise to a column or a row matrix. It is as follows:
\begin{gather}
\vec{u} \otimes \vec{v} = \left[ \begin{array}{ccc}
u_1\cdot v_1 & u_1 \cdot v_2 & u_1 \cdot v_3\\
u_2\cdot v_1 & u_2 \cdot v_2 & u_2 \cdot v_3\\
u_3\cdot v_1 & u_3 \cdot v_2 & u_3 \cdot v_3\\
\end{array} \right]
\end{gather}
It is therefore
\begin{gather}
\vec{u} \otimes \vec{v} = (\vec{v} \otimes \vec{u})^T
\end{gather}
In terms of vector inner product same may be written as
\begin{gather}
\vec{u} \otimes \vec{v} = \vec{u} \cdot \vec{v}^T
\end{gather}
OR
Valid vector inner product is therefore,
\begin{gather}
\vec{u}\cdot \vec{v} = \left[ \begin{array}{c}
u_1 \\
u_2 \\
u_3 \\
\end{array} \right] \cdot \left[ \begin{array}{ccc}
v_1 & v_2 & v_3 \\
\end{array} \right]
\end{gather}


text:
Q: PYTHON -INSTAGRAM Selenium I have been stuck at the code from a long time:
so i want to send dm's using python on instagram but i am having a problem slecting the user from drop down menu
like the text even goes in here, but now after this how do i select the first person?
I have tried using the find xpath method or get the class method or even tried using the button containing the text.
please help me.
from selenium import webdriver
from time import sleep

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select

x=input("Whom to you want to send your text message? Please type his/her name:- ")
print("Okay cool ! I got it !")
y=input("What is the message? Don't worry you can send any personal messages, I don't save them in my memory xD !")

class Instabot:
    def __init__(self, username, password):
        self.driver = webdriver.Chrome()
        self.driver.get("https://instagram.com")
        sleep(2)
        self.driver.find_element_by_xpath("//input[@name=\"username\"]")\
            .send_keys(username)
        self.driver.find_element_by_xpath("//input[@name=\"password\"]")\
            .send_keys(password)
        self.driver.find_element_by_xpath('//button[@type="submit"]').click()
        sleep(3)
        self.driver.find_element_by_xpath('//button[text()="Not Now"]').click()
        sleep(2)
        self.driver.find_element_by_xpath('//button[text()="Not Now"]').click()
        sleep(2)
        self.driver.find_element_by_xpath("//input[@placeholder=\"Search\"]")\
            .send_keys(x)
        sleep(2)
        select = Select(self.driver.find_element_by_id(x))
        select.select_by_visible_text(x)

        sleep(1)
        self.driver.find_element_by_xpath('//button[text()="Message"]').click()
        sleep(1)

        k=self.driver.find_element_by_tag_name('textarea')
        k.send_keys(y)
        sleep(1)
        self.driver.find_element_by_xpath('//button[text()="Send"]').click()
        sleep(1)

Instabot("username","password",)

A: Full working code. This will select the first suggestion, Visit the profile page, if the message option exists, it will click on message, and send the message.
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select

x = input("Whom to you want to send your text message? Please type his/her name:- ")
print("Okay cool ! I got it !")
y = input("What is the message? Don't worry you can send any personal messages, I don't save them in my memory xD !")

class Instabot:
    def __init__(self, username, password):
        self.driver = webdriver.Chrome()
        self.driver.get("https://instagram.com")
        sleep(2)
        self.driver.find_element_by_xpath("//input[@name=\"username\"]") \
            .send_keys(username)
        self.driver.find_element_by_xpath("//input[@name=\"password\"]") \
            .send_keys(password)
        self.driver.find_element_by_xpath('//button[@type="submit"]').click()
        sleep(3)
        self.driver.find_element_by_xpath('//button[text()="Not Now"]').click()
        sleep(2)
        self.driver.find_element_by_xpath('//button[text()="Not Now"]').click()
        sleep(2)
        self.driver.find_element_by_xpath("//input[@placeholder=\"Search\"]") \
            .send_keys(x)
        sleep(3)
        self.driver.find_element_by_xpath("//*[@id=\"react-root\"]/section/nav/div[2]/div/div/div[2]/div[4]/div/a[1]/div/div[2]/div").click()
        sleep(3)

        sleep(1)
        self.driver.find_element_by_xpath('//button[text()="Message"]').click()
        sleep(4)

        k = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea')
        k.send_keys(y)
        sleep(1)
        self.driver.find_element_by_xpath('//button[text()="Send"]').click()
        sleep(1)


text:
Q: R decision tree error message I have an error message when make predictions with an decision tree that I don't know how to intrepret:
library(DMwR)
library(rpart.plot)
train <-na.omit(train)
test <-na.omit(test)

ar <- rpartXse(Survived ~ .,train)

prp(dt,type=4,extra=101)

pre <- predict(ar,test,type='class')

Error:
5.
stop(sprintf(ngettext(length(m), "factor %s has new level %s", "factor %s    has new levels %s"), nm, paste(nxl[m], collapse = ", ")), domain = NA)
4.
model.frame.default(Terms, newdata, na.action = na.action, xlev = attr(object, "xlevels"))
3.
model.frame(Terms, newdata, na.action = na.action, xlev = attr(object, "xlevels"))
2.
predict.rpart(ar, test, type = "class")
1.
predict(ar, test, type = "class")

At first I think it was by have NA values I correct that, don't worked.
Someone can tell me how to interpret messages of this kind and how can I correct it please.
Thanks in advance.


text:
Q: camera2 size surfaceview I am developing an Android app that must show camera inside LinearLayout. I am creating a Fragment with a SurfaceView and Camera2 object. After a lot of work I could show camera over surfaceview but I am having problems with size.
Camera's image is begin showed just in a part and the rest is just a black screen. I tried to define width and height that surfaceChanged give me with setFixedSize but I get this error
Surface with size (w=516, h=828) and format 0x4 is not valid, size not in valid set: [1440x1080, 1280x720, 960x720, 880x720, 960x540, 720x540, 800x480, 720x480, 640x480, 528x432, 352x288, 320x240, 176x144]
If I define some of the sizes in the message I can get camera image but not over all my surface just a part and the rest is black.
I can not figure out what I am doing wrong.
This is my layout
 <LinearLayout
        android:id="@+id/contenedor1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </LinearLayout>

This is how I get valid device sizes. I am taking first in the list but I tried with all availables sizes
val map = cameraCharacteristics!!.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)

                medida= map.getOutputSizes(SurfaceHolder::class.java)[0]
                w=medida.width
                h=medida.height

Then I set size with
override fun surfaceCreated(p0: SurfaceHolder?) {
        p0!!.setFixedSize(w,h)

        Superficie = p0!!.surface
    }

And this is the image I get