text:
Q: Examples of prime ideals for Lie algebras I am looking for examples of prime ideals for Lie algebras. In particular, I am interested in examples involving the Lie algebra given by the commutator of endomorphisms of a complex vector space and the Lie algebra of functions on the phase space $\mathbb{R}^{2n}=(x^1,\ldots,x^n,p_1,\ldots,p_n)$ given by
$$
[f,g]=\sum_i\frac{\partial f}{\partial x^i}\frac{\partial g}{\partial p_i}-
\frac{\partial g}{\partial x^i}\frac{\partial f}{\partial p_i},
$$
where $f$ and $g$ are real or complex-valued functions on the phase space.
My interest has originated in physics, where the time derivative of a physical "observable" $X$ can generally be written (except for multiplicative constants) as
$$
\frac{d X}{d t} = [H,X],
$$
where $H$ is the Hamiltonian operator in quantum mechanics or the Hamiltonian function on classical phase space. If the Hamiltonian and $X$ are not in the prime ideal at some initial time, then $X$ will never be.
I have made some searching on the internet, but I have found only two papers that are rather abstract with no examples at all.


text:
Q: Usage of "Add" button in Java AbstractTableModel I am trying to add an "Add" button to my AbstractTableModel. It would then bring up a form for the user to enter in the ip address of a pc and click "Add". I am just stuck at the part on how to add a new row (cell) to the table dynamically. I have found a couple of examples on here, all which have not helped me in my situation.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException;

public class CampaignConfiguration extends JFrame {

    //private static final long serialVersionUID1 = 1L;
    private JPanel contentPane1;
    private JLabel lblTestsuiteName;
    public static  JTextField testSuiteTexField;
    public static JTextArea computerTextArea;
    public static String[] computerListArray;
    public static String testSuiteName;
    private JTextField txtHours;
    private JTextField txtMin;
    private JLabel label;
    private static JTable table;
    private static JButton btnUnmap, btnSave, btnClose, btnAdd;
    public static ArrayList<String> computerTextArray = new ArrayList<String>();
    final MyTableModel tableData;

    private JPanel contentPane;
    private boolean debug = true,  // Prints out debug messages
                     booleanValue;   // Used to convert String[] execute to a boolean value
    XMLparser xml = new XMLparser(Constants.TMP_DIR + Constants.COMPUTER_LIST_TEMP_FILE, Constants.XML_ROOT_TAG, Constants.XML_PARENT_TAG);
    public ArrayList<String> parameters_1 = new ArrayList<String>(),
                             parameters_2 = new ArrayList<String>(),
                             parameters_3 = new ArrayList<String>(),
                             parameters_4 = new ArrayList<String>(),
                             parameters_5 = new ArrayList<String>();

    private SaveToXml save = new SaveToXml();
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args){
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    final CampaignConfiguration frame = new CampaignConfiguration();
                    frame.setVisible(true);
                    frame.validate();

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

    public void ActionOnClose(){
        addWindowListener(
                  new java.awt.event.WindowAdapter()
                  {
                    public void windowClosing( java.awt.event.WindowEvent e )
                    {
                      try {
                        Main.Refresh();
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    }
                  }
                );
    }

    /**
     * Create the frame.
     */
    public CampaignConfiguration() throws FileNotFoundException, ParserConfigurationException, SAXException, IOException{
        ActionOnClose();
        setTitle("Campaign Configuration");
        ArrayList<MyObject> list = new ArrayList<MyObject>();
        int listSize = NetworkMapping.usedDrives.size();
          for(int i = 0; i < listSize;i++){
            if(debug){
                System.out.println("---------------------------------------------");
                System.out.println("pc_ip_address [" + i + "] = '" + NetworkMapping.usedDrives.get(i) + "'");
                System.out.println("---------------------------------------------");
                System.out.println("\n");
            }
            list.add(new MyObject(NetworkMapping.pc_ip_addresses.get(i)));
         }

        // Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 87, 493, 263);
        TableColumn column = null;

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 529, 517);
        contentPane1 = new JPanel();
        contentPane1.setBorder(new EmptyBorder(50, 10, 10, 10));
        contentPane1.setLayout(null);
        contentPane1.add(scrollPane);
        setContentPane(contentPane1);

        // Add the scroll pane to this panel.
        getContentPane().add(scrollPane);
        tableData = new MyTableModel(list);
        table = new JTable(tableData);

        scrollPane.setViewportView(table);
        //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setRowHeight(25);
        table.setFillsViewportHeight(true);

        JLabel lblCampaignName = new JLabel("Campaign Name (Case Sensitive)");
        lblCampaignName.setBounds(10, 11, 218, 14);
        contentPane1.add(lblCampaignName);

        textField = new JTextField();
        textField.setBounds(10, 36, 86, 20);
        contentPane1.add(textField);
        textField.setColumns(10);

        btnSave = new JButton("Save");
        btnSave.setBounds(209, 361, 89, 23);
        contentPane1.add(btnSave);

        btnUnmap = new JButton("Disconnect Drives");
        btnUnmap.setBounds(177, 395, 154, 23);
        contentPane1.add(btnUnmap);

        btnClose = new JButton("Close");
        btnClose.setBounds(308, 361, 89, 23);
        contentPane1.add(btnClose);

        btnAdd = new JButton("Add");
        btnAdd.setBounds(108, 361, 89, 23);
        contentPane1.add(btnAdd);

        // Add actionlistener
        ButtonAction ba = new ButtonAction();
        btnClose.addActionListener(ba);
        btnSave.addActionListener(ba);
        btnUnmap.addActionListener(ba);
        btnAdd.addActionListener(ba);
    }
    class MyObject {
        String ip_address;
        int iterations;
        boolean isExecute;
        String parameter_1,
               parameter_2,
               parameter_3,
               parameter_4;

        MyObject(String ip_address) {
             this.ip_address = ip_address;
        }
   }

class MyTableModel extends AbstractTableModel {
    Vector<String> textData = new Vector<String>();

    private static final long serialVersionUID = 1L;
    /**
     *
     */
    //private static final long serialVersionUID = 1L;
    private String[] columnNames = { "Test Machine IP Address"};

    ArrayList<MyObject> list = null;

    MyTableModel(ArrayList<MyObject> list) {
         this.list = list;
    }

    public void addText(String text) {
        textData.addElement(text);
        fireTableDataChanged();
      }
    public int getColumnCount() {
         return columnNames.length;
    }

    public int getRowCount() {
         return list.size();
    }

    public String getColumnName(int col) {
         return columnNames[col];
    }

    public Object getValueAt(int row, int col) {

         MyObject object = list.get(row);

         switch (col) {
         case 0:
              return object.ip_address;
        /* case 1:
              return object.iterations;
         case 2:
              return object.isExecute;
         case 3:
             return object.parameter_1;
         case 4:
             return object.parameter_2;
         case 5:
             return object.parameter_3;
         case 6:
             return object.parameter_4;*/
         default:
              return "unknown";
         }
    }
    @Override
    public boolean isCellEditable(int row, int col) {
        return true;
    }

    @SuppressWarnings("unchecked")
      public Class getColumnClass(int c) {
         return getValueAt(0, c).getClass();
    }
    @Override
    public void setValueAt(Object value, int row, int col) {
        MyObject obj = list.get(row);
        if(col == 0){
            obj.ip_address = (String)value;
        } /*else if(col == 1){
            obj.iterations = (int)value;
        } else if (col == 2) {
            obj.isExecute = (Boolean)value;
        } else if (col == 3) {
            obj.parameter_1 = (String)value;
        }else if (col == 4) {
            obj.parameter_2 = (String)value;
        }else if (col == 5) {
            obj.parameter_3 = (String)value;
        }else if (col == 6) {
            obj.parameter_4 = (String)value;
        }*/
        fireTableCellUpdated(row, col);
        try {
            SaveDataEntered(value, row, col);
        } catch (ParserConfigurationException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    // col = 0 / IP Address
    // col = 1 /
    // col = 2 /
    // col = 3 /
    private void SaveDataEntered(Object value, int row, int col) throws ParserConfigurationException, IOException {
      MyObject obj = list.get(row);
      if(col == 0){
          System.out.println("ip address column");
          NetworkMapping.pc_ip_addresses.set(row, (String)value);
      } /*else if(col == 1){
          System.out.println("iterations column");
         // iterations[row] = Integer.toString((int)value);
      } else if(col == 2){
          System.out.println("execute column");
         // execute[row] = Boolean.toString((Boolean)value);
      } else if(col == 3){
          obj.parameter_1 = (String)value;
          System.out.println("(String)value = " + (String)value);
         // parameters_1.set(row, (String)value);
      } else if(col == 4){
          obj.parameter_2 = (String)value;
          System.out.println("(String)value = " + (String)value);
         // parameters_2.set(row, (String)value);
      }else if(col == 5){
          obj.parameter_3 = (String)value;
          System.out.println("(String)value = " + (String)value);
         // parameters_3.set(row, (String)value);
      }else if(col == 6){
          obj.parameter_4 = (String)value;
          System.out.println("(String)value = " + (String)value);
         // parameters_4.set(row, (String)value);
      }*/

          //save.WriteClaConfigFile(pc_ip_address, pc_ip_address, iterations, execute, parameters_1, parameters_2, parameters_3, parameters_4);

      if(debug){
              System.out.println("    row " + row + ":");

    System.out.println("--------------------------");
                  System.out.println("pc_ip_address selection\t= '" + NetworkMapping.pc_ip_addresses.get(row)+ "'");
                  System.out.println("value\t\t\t= '" + value + "'");
                  System.out.println("row\t\t\t= '" + row + "'");
                  System.out.println("col\t\t\t= '" + col + "'");
                  System.out.println("--------------------------");
          }

        }
   }

}

Forgot my button action:
class ButtonAction
        implements ActionListener{
        ButtonAction() {}

        public void actionPerformed(ActionEvent e){

          Object obj = e.getSource();
          if (obj == btnAdd){               // Add machine
              System.out.println("Should be adding");
              //tableData.addText("Test");
              tableData.addRow("Test");
          }
          } // Close if/else block
        } // Close actionPerformed

A: You are pointing getValueAt in the table model to list yet but your addText method is setting values in textData.
Uncomment out tableData.addText("Test") in the action listener and in addText change textData.addElement(text) to list.add(new MyObject(text)).

redpajama_set_name: RedPajamaStackExchange


text:
Q: why some locally constant sheaves aren't constant? Many times you have to show that a certain sheaf, maybe obtained as gluing of other sheaves, is not constant ; there are methods or tricks immediate or generally to do this?
What is special about a constant sheaf that other sheaves (e.g. those locally constant ) don't have ?
in particular cases :

*

*if $X$ is not connected and disjoint union of two open not empty subset $U, V$ and if i take the sheaves constant on $U$ and $V$ and glue them (for example i can take the zero sheaf on $U$ and the constant sheaf with stalk $K$ on $V$); why I don't get a constant sheaf?

*if $X = \mathbb{R}\cup S^{1}$, why the sheaf locally constant that I get as gluing of the two constant sheaves $\mathbb{R}_{\mathbb{R}}$ and $\mathbb{R}_{\mathbb{S^{1}}}$ is not constant ?.


text:
Q: The function with srand will not compile This is the code that I have, and its intention is to take a an array, load it with values 1-100, re-arrange them with a random number, and re-sort them. The randomizeArray function will not compile and I do not understand why. Is it not declared properly? If so, how do I fix it.
I got the error message:

(62): error C2143: syntax error : missing ';' before 'type'

on the line declaring currPos.
#include <stdio.h>
#include <stdlib.h>
/*Set prototypes for functions used*/
void bubblesortArray(int[],int);
void printArray(int[], int);
void randomizeArray (int[], int);

int main()
{
   const int arraysize = 100;/*Defines the size of the array*/
   int mainArr [100];/*Declares the array, with the size above*/
   int index = 0;

   for(index; index<arraysize; index++)
   {
      mainArr[index] = index + 1;
   }

   printArray(mainArr, arraysize);

   randomizeArray (mainArr, arraysize);

   printArray(mainArr, arraysize);

   bubblesortArray(mainArr, arraysize);

   printArray(mainArr, arraysize);

   getchar();
}

void printArray(int mainArr[], int arraysize)
{
    int printindex = 0;/*INdex of the printing Array*/
    for(printindex; printindex<arraysize; printindex++)/*Prints the values of the Array on the screen*/
    {
    printf ("%5d,", mainArr[printindex]);
    if(((printindex+1)%10) == 0)
    printf("\n");
    }
}/*End of print function*/

void randomizeArray (int mainArr [], int arraysize)
{
   int seed = 10;/*Seed for the randon number operation*/
   srand(seed);
   int currPos = 0;
   for(currPos; currPos<arraysize; currPos++)
   {
      int swapval = rand()% 99;/*Sets a random pointer value for swapping in the array*/
      int temp = mainArr[currPos];
      mainArr[currPos] = mainArr[swapval];
      mainArr[swapval] = temp;
   }
}

void bubblesortArray(int mainArr[], int arraysize)
{
    int sortloop1 = 0;/*The first index fo the sort algorithm*/
    int sortloop2 = 0;/*The second(inner) index fo the sort algorithm*/
      for(sortloop1;sortloop1<arraysize;sortloop1++)                             /*Sort algorithm to get the values in their correct places.*/
      {
        for(sortloop2=sortloop1;sortloop2<(arraysize);sortloop2++)
        {
                if(mainArr[sortloop1]>mainArr[sortloop2])
                {
                    int temp=mainArr[sortloop1];
                    mainArr[sortloop1]=mainArr[sortloop2];
                    mainArr[sortloop2]=temp;
                }                                   /*End of sort operation*/
        }                                       /*End of inner sorting loop*/
      }                                             /* End of sort algorithm*/
}/*End of bubble sort function*/

A: From the error message in your comment:
(62): error C2143: syntax error : missing ';' before 'type' `

You are using a compiler that doesn't support C99, or you are not setting it in C99 mode. In C89, variables must be declared in the beginning of a block, so in this piece of code:
void randomizeArray (int mainArr [], int arraysize)
{
   int seed = 10;/*Seed for the randon number operation*/
   srand(seed);
   int currPos = 0;

The variable currPos must be declared before calling srand:
void randomizeArray (int mainArr [], int arraysize)
{
   int seed = 10;/*Seed for the randon number operation*/
   int currPos = 0;
   srand(seed);


text:
Q: Unable to retrieve context in Fragment I tried to find the solution with several resources:

*

*Retrieve Context from a fragment

*Using context in a fragment
But I still got the following error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference

Any help will be appreciated. Thanks!

My current codes:
AnalysisActivity.java:
package com.app.component.fragment;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import com.material.components.R;
import com.material.components.fragment.FragmentTabsEvents;
import com.material.components.fragment.FragmentTabsPerformance;
import com.material.components.fragment.FragmentTabsRecommendation;
import com.material.components.utils.Tools;

import java.util.ArrayList;
import java.util.List;

public class AnalysisActivity extends AppCompatActivity {

    private ViewPager view_pager;
    private TabLayout tab_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_analysis);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Tools.setSystemBarColor(this,R.color.black);

        view_pager = findViewById(R.id.view_pager);
        setupViewPager(view_pager);

        tab_layout = findViewById(R.id.tab_layout);
        tab_layout.setupWithViewPager(view_pager);
    }

    private void setupViewPager(ViewPager viewPager) {
        SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(FragmentTabsPerformance.newInstance(), "PERFORMANCE");
        adapter.addFragment(FragmentTabsRecommendation.newInstance(), "RECOMMENDATION");
        adapter.addFragment(FragmentTabsEvents.newInstance(), "EVENTS RELATED TO YOU");
        viewPager.setAdapter(adapter);
    }

    private class SectionsPagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public SectionsPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return  true;
    }
}

FragmentTabsPerformance.java:
package com.app.component.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.material.components.R;
import com.material.components.utils.Tools;

import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;

public class FragmentTabsPerformance extends Fragment {

    private Context context;
    public FragmentTabsPerformance() {
        this.context = getActivity().getApplicationContext();
        List<PointValue> values = new ArrayList<>();
        values.add(new PointValue(0, 2));
        values.add(new PointValue(1, 4));
        values.add(new PointValue(2, 3));
        values.add(new PointValue(3, 4));

        //In most cased you can call data model methods in builder-pattern-like manner.
        Line line = new Line(values).setColor(Color.BLUE).setCubic(true);
        List<Line> lines = new ArrayList<>();
        lines.add(line);

        LineChartData data = new LineChartData();
        data.setLines(lines);

        LineChartView chart = new LineChartView(this.getContext());
        chart.setLineChartData(data);
    }

    public static FragmentTabsPerformance newInstance() {
        FragmentTabsPerformance fragment = new FragmentTabsPerformance();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_tabs_performance, container, false);

        Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_1), R.drawable.image_8);
        Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_2), R.drawable.image_9);
        Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_3), R.drawable.image_15);
        Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_4), R.drawable.image_14);
        Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_5), R.drawable.image_12);
        Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_6), R.drawable.image_2);
        Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_7), R.drawable.image_5);

        return root;
    }
}

A: This exception occurred since you called the getActivity() in the construction method when the fragment is not attached to an activity. You may refer to the API guides about the lifecycle methods about fragment with activity. In your case, you may use getContext() instead of getActivity() method to get the context of fragment.

A: getActivity() only available after Fragment is attached to activity. So, getActivity() in Fragment constructor will return null. Check fragment life cycle for more detail


text:
Q: Проверка на наличие значений в PySimpleGUI InputText/полях ввода значения (if values['-YourName-']!=None) у меня такой код
 [sg.Text('Телефон'), sg.InputText(size=(20, 3), key='-PhonNumReg-', )],
            [sg.Text('Пароль'), sg.InputText(size=(20, 3), key='-Password1Reg-')],
            [sg.Text('Повторите пароль'), sg.InputText(size=(20, 3), key='-Password2Reg-')],
            [sg.Text('Имя'), sg.InputText(size=(20, 3), key='-Name1Reg-')],
            [sg.Text('Фамилия'), sg.InputText(size=(20, 3), key='-Name2Reg-')],
            [sg.Submit("Далее")]]

я хочу проверить values['-PhonNumReg-'] на наличия введеного текста, проверяю так(не работает)
if values['-PhonNumReg-']!=None и так  if values['-PhonNumReg-']!=''


text:
Q: How to add a date and print all results within a certain day? I think my question won't be any complicated for you, I'm just a noob. (however, trying hard to work on it)
I have a table in my .db and it looks like this:

Number
Text
DateTime

31156
abc
11.01.2021 21:07:56

31155
cba
11.01.2021 21:07:56

31034
def
06.01.2021 20:16:40

30472
ghi
18.12.2020 20:55:45

30471
ihg
18.12.2020 20:55:45

30466
jkl
18.12.2020 19:29:24

30465
lkj
18.12.2020 19:29:24

30322
mno
14.12.2020 17:30:11

30303
pqr
12.12.2020 20:55:15

30302
rqp
12.12.2020 20:55:15

To print all results I use this code:
$Query = "SELECT LeagueLog.*
FROM LeagueLog
ORDER BY LeagueLog.Number DESC";

$Transaction = $db->query($Query);
if (empty($Transaction) == false){while ($row = $Transaction ->fetchArray()) {

echo "
" .$row['Text'] . " (" .$row['DateTime'].")" . "

\n"; /* The \n is for a new line in the HTML Code */

With this code I get all results in one column like this:
abc (11. 1. 2021)
cba (11. 1. 2021)
def (6. 1. 2021)
ghi (18. 12. 2020)
ihg (18. 12. 2020)
jkl (18. 12. 2020)
lkj (18. 12. 2020)
mno (14. 12. 2020)
pqr (12. 12. 2020)
rqp (12. 12. 2020)

However, I would like to have a Date and all results within the day. Something like this:
11. 1. 2021
abc
cba

6. 1. 2021
def

18. 12. 2020
ghi
ihg
jkl
lkj

14. 12. 2020
mno

12. 12. 2020
pqr
rqp

I really have no clue how to do this.
Thank you for your help!


text:
Q: putting x=sin(t)+3 in terms of t For
$x = \sin(t)+3$
would it be correct to say that
$t = \arcsin(x-3) $
be correct even though this would mean that it's possible for $x$ to not be between $-1$ and $1$?

A: Unless one restricts $\sin t$ to the interval $\left[-\dfrac{\pi}{2},\dfrac{\pi}{2}\right]$ here are many solutions, one for each integer value of $k$
$$ t=(-1)^k\sin^{-1}(x-3)+k\pi $$
for $t$ in the interval $\left[-\dfrac{\pi}{2}+k\pi,\dfrac{\pi}{2}+k\pi\right]$.
Look here a desmos.com demonstration


text:
Q: Upload an image file via rich text editor webpart of sharepoint 2010 My goal is to
Upload an image file via rich text editor webpart of sharepoint 2010
According to how seems can only to give URL of the image and not to upload a image
Directly through the webpart

A: Click in the rich text field and go to the insert sub-menu on the ribbon.  From there, if you have permissions, you can probably upload a file to the pages or images library.


text:
Q: Scrapy rules and regular expression I'm trying to use Scrapy to scrap information from geonames.org. More specifically, I want to retrieve the 10 largest cities for each country. My starting URL is http://www.geonames.org/countries/. On this page, I want to follow each URL that meets the regex:
/countries/\w{2}/..html
Then on followed pages (that is the country pages), I want to  follow the URL with the following structure http://www.geonames.org/XX/largest-cities-in-YYYY.html
where XX is the two letter country code and YYYY is the actual name of the country which obviously can be of variable length. The code below doesn't work. I suspect it's due to a problem with the regex of the second rule. But maybe not!
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
import re
import os

class MySpider(CrawlSpider):
    name = 'geocodeSpider'
    allowed_domains = ['www.geonames.org']
    start_urls = ['http://www.geonames.org/countries/']

    fileName="largest_cities.txt"
    try:
        os.remove(os.path.join('geocode/output',fileName))
    except OSError:
        pass
    rules = (
        Rule(LinkExtractor(allow=(r'/countries/\w{2}/.\.html', )),),
        Rule(LinkExtractor(allow=(r'/\w{2}/largest-cities-in-.\.html', )), callback='parse_item'),
  )

    def parse_item(self, response):
...


text:
Q: I need help with understanding expected values Consider a discrete random variable $X$ that takes on the values $x_1,...,x_n$ and for every $x_i$ there's a probability $p(x_i)=p_i$. I am attempting to understand why the expectation $E[X]$ is defined the way it is.
$$E[X]=x_1p_1+...+x_np_n$$
I cannot figure out why it is defined this way and I have already checked my book and wikipedia. I don't understand how this "weighted average" thing is applicable here. $E[X]$ is suppose to be the average value $X$ takes if some experiment is performed many times, correct? Since $p_1+...+p_n=1$ $E[X]$ can expressed as
$$E[X]=\frac{x_1p_1+...+x_np_n}{p_1+...+p_n}$$
but that still does not tell me anything. I would appreciate if someone could help me out here.

A: I will try to give you some more insight:
suppose you have a random variable $X$ which takes two values (say 4 and 8) with a chance of 50% each.
   $P(X=4) = P(X=8) =.5 = p_1 = p_2$.
You can imagine that $X$ is linked to a fair coin and every Head corresponds to 4 and tail corresponds to 8.
The expected value is a number which represents the average outcome of the random variable $X$. So assume you have several observations of $X$ (i.e. you throw a coin say 1000 times and note the outcome). Since both outcomes are evenly likely, the arithmetic mean (or average) of this 1000 experiments would be close to 6:
$$
Ave_{1000} = \frac{\#occurrences~ of~ 4}{1000}*4 +\frac{\#occurrences~ of~ 8}{1000}*8 \approx \frac{500}{1000} \cdot 4 + \frac{500}{1000}\cdot 8 =6
$$
The expected value can be obtained by taking the number of repetitions to infinity: by doing so the relative frequency of fours would converge to .5 (since probabilities can be defined by the limit of relative frequencies) and so would the relative number of eights. Hence,
$$
Ave_{\infty} := E[X] = \frac 12 4 + \frac 12 8 = p_1 4 + p_2 8 = 6.
$$
So the expected value is the arithmetic mean of an experiment repeated infinitely often. In general, if you experiment $X$ has $n$ different outcomes denoted with $(x_1, \dots, x_n)$  occurring with probabilities $(p_1, \dots, p_n)$ then $p_i$ will be close to the relative frequency of outcome $x_i$ if the number of repetitions is large. If you have say 1000 repetitions then the arithmetic mean (or average) is given by
$$
Ave_{1000} = \sum_{i=1}^n \frac{\#occurrences~ of~ x_i}{1000} \cdot x_i \approx \sum_{i=1}^n p_i \cdot x_i.
$$
Again by taking the number of repetitions to infinity the relative frequencies converge to the probabilities and $Ave_N$ will converge to a number which is known as the expected value.
I hope this was somehow helpful.

A: Let's take a simple example.
Imagine $x_1,x_2,x_3,x_4$ as vertex of a square ABCD. And now you pick randomly one vertex again and again. If you draw vertices many times, then the average of all those draws will be the center (or barycenter) of the square since you have the same probability picking any of the vertices.
The barycenter G of ABCD satisfies :
$$0=\vec{GA}+\vec{GB}+\vec{GC}+\vec{GD}=\frac 1 4\vec{GA}+\frac 1 4\vec{GB}+\frac 1 4\vec{GC}+\frac 1 4\vec{GD}$$
Which can be rewritten as :
$$\vec{OG}= \frac 1 4\vec{OA}+\frac 1 4\vec{OB}+\frac 1 4\vec{OC}+\frac 1 4\vec{OD}$$
Picking a vertex is the same as picking a vector.
Then if we take this back into the world of probabilities, it tells you that the expectation ($\vec{OG}$) is equal to the sum of the probability of picking a vertex ($\vec{OA}$ for example) multiplied by the vector.
Now if instead of picking a vertex with equals probabilities, we weight the vertices differently (or not). Let $X$ be the random variable associated to the draw of a vertex.
Then $P(X=x_i)=p_i$ for $i=1,2,3,4$ and $p_1+p_2+p_3+p_4=1$.
The weighted barycentre verifies :
$$0=p_1\vec{GA}+p_2\vec{GB}+p_3\vec{GC}+p_4\vec{GD}$$
Which again can be rewritten as :
$$(p_1+p_2+p_3+p_4)\vec{OG}=p_1\vec{OA}+p_2\vec{OB}+p_3\vec{OC}+p_4\vec{OD}$$
Then we finally get : $$\vec{OG}=\dfrac 1 {(p_1+p_2+p_3+p_4)} p_1\vec{OA}+p_2\vec{OB}+p_3\vec{OC}+p_4\vec{OD}$$
And by the same reasoning then before, you can interpret those quantities as expectation and probabilities.


text:
Q: Server side query rerun for paging, sort or filtering What is the best approach to rerun a server query/subscription for a specific connected client when some data on that client changes?
This would be very useful for server side filtering, ordering or paging.
For example, the client has a table with thousands of lines that are paginated, when the user changes the filtering text or page number the server would recompute the query subscription with that filter, and update the client on the fly.
The search input doesn't have to be synced across all connected users of the server, and thus its not needed to be present in the database.
Is there any way to perform this with traditional model methods on both client and server or do I have to implement a RPC like approach as mentioned in the FAQ?
Thanks!

A: var filter = model.root.filter('items', 'temp.pageNumber', function(item, x,y,pageNumber){
   if (item.index > pageNumber*10 && item.index < pageNumber*10+10){
      return true;
   }
   return false;
}
model.root.subscribe(filter,function(){
   model.ref('filteredItems', filter);
});

and bind to filteredItems in view.
something like this.


text:
Q: Prove that there is a positive real number $\lambda$, so that $A =\lambda B$, for two positive definite square matrices A and B are positive definite square $n$ $\times$ $n$ matrices. The thereby defined dot products define the same orthogonality relation. Which means:
$∀v, w ∈ R^n : v · Aw = 0 ⇔ v · Bw = 0.$
Show that there is a positive real number $\lambda$, so that $A =$ $\lambda$$B$
How can I show that?

A: So as a positive definite matrix, we can find its $n$ eigenvectors $[v_1,...v_n]$ and $n$ positive eigenvalues $\lambda_1,...\lambda_n$. As a property of real symmetric matrix, we know these vectors are orthogonal to each other,
$$
\forall i,j,i\neq j, v_i^Tv_j=0
$$
Then
$$
\forall i,j,i\neq j, v_i^TAv_j=\lambda_j v_i^Tv_j=0
$$
which implied
$$
\forall i,j,i\neq j, v_i^TBv_j=v_i^TAv_j=0
$$
Now let's take $v_1$ as an example, $Bv_1$ is orthogonal to $v_2,...v_n$. in a $n$ dimensional space, this implies $Bv_1$ lies in the $span(v_1)$, which means $v_1$ is an eigenvector for $B$.
Similarly, the eigenvectors for $A$, $v_1...v_n$ are all eigenvectors for $B$.
So now we showed, $A,B$ could be jointly diagonalized by a same set of vector.
Let's say the eigenvalues of $B$ for $v_1...v_n$ are $\mu_1,...\mu_n$.
Now using the eigenbasis $v_1,...v_n$, a vector $x=\sum_i a_iv_i$, $y=\sum b_i v_i$. Then $x^TAy=\sum_i \lambda_i a_ib_i$, $x^TBy=\sum_i \mu_i a_ib_i$.
To make things simple, let $x=\sum_i v_i$, i.e. $a_1=a_2=a_3...a_n=1$
$$
x^TAy=\sum_i \lambda_i b_i\\
x^TBy=\sum_i \mu_i b_i\\
$$
Using the similar argument from above we can find $n-1$ linear independent vectors $\mathbf b=[b_1,b_2...b_n]$ from the orthogonal space of vector $\mathbf \Lambda=[\lambda_1,...\lambda_n]$, For all these vectors
$$
x^TAy=x^TBy=\mathbf b^T\mathbf \Lambda=0=\mathbf b^T \mathbf M
$$
in which $\mathbf M=[\mu_1,\mu_2...\mu_n]$
Then we can see, $\mathbf M$ live in the same linear space as $\mathbf \Lambda$, existing $\exists k,s.t. \mathbf M=k\mathbf \Lambda$, since $k\neq 0$ ($\mu_i >0$ positive definite) we can also define $\lambda=1/k$ so $\lambda\mathbf M=\mathbf \Lambda$
Taking this together, $A,B$ has same eigenvectors, eigenvalus of $A$ are $k$ times of $B$, then you get
$$
A=\sum_i \lambda_i v_iv_i^T = \lambda \sum_i \mu_i v_iv_i^T = \lambda B
$$


text:
Q: Does theory have the smallest model I have a language $L=\{P\}$ with equation, where $P$ is binary predicate symbol. Language's formulas are:
$\varphi \equiv  \forall x \forall y (\neg P(x,x) \land (P(x,y) \to P(y,x)))$,
$\psi \equiv \forall x \exists y \exists z(y\ne z \land P(x, y) \land P(x,z) \land \forall v (P(x,v) \to (v=y \lor v =z )))$
and for every $n \in N^+$
$\xi_n \equiv \exists x_1 \exists x_2 ... \exists x_n
(\bigwedge \limits _{i=1}^{n-1}P(x_i, x_{i+1}) \land \bigwedge \limits _{i=1  }^{n}\bigwedge \limits _{j=i+1}^{n} x_i \ne x_j)$
Theory $T=\{\varphi,\psi\} \cup \{\xi_n | n \in N^+\}$ is being considered.
In my question models with countable field only are considered(I mean for every implementation $M$ injection from $M$ to $N$ should exist)
I need to decide if $T$ has the smallest model $M$. With smallest model I mean such model, that for any $M'$ of theory $T$ there exist injective homomorphism from $M$ to $M'$. Could somebody please help me with this?

A: No. Let $C_\infty$ be an infinite chain, and let $C_n$ be a finite loop of length $n$. Then $C_\infty$ is a model of your theory, and so is $\coprod_{n\geq 3} C_n$, the disjoint union of a loop of length $n$ for all $n\in \mathbb{N}$ with $n\geq 3$. But obviously neither of these models embed into the other.
However, any completion of this theory has a smallest model. In my answer to your previous question, I described all completions of this theory and all of their countable models. In any completion, the model with the fewest possible infinite chains ($0$ if the completion allows arbitrarily large finite loops, $1$ if not) will embed into every other model.


text:
Q: BibTeX proceedings with acmart I'm using the acmart class and proceedings items in my bibliography look rather odd, e.g.,
[1] IEEE 1997. Proc. 12th Symposium on Logic in Computer Science. IEEE.

I've tried a few variations, without success.
What I'd like is something like:
[X] IEEE. Proc. 12th Symposium on Logic in Computer Science, 1997.

(for X, I don't really care, but I guess it should be sorted as if IEEE
was the author).
Here is a MEWB:
\documentclass{acmart}
\bibliographystyle{ACM-Reference-Format}
\citestyle{acmnumeric}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
@proceedings{DBLP:conf/lics/1997,
  author = {},
  key = {LICS 1997},
  organization = {IEEE},
  year      = {1997},
  title     = {Proc.\ 12th Symposium on Logic in Computer Science},
}
\end{filecontents}

\begin{document}

\cite{DBLP:conf/lics/1997}

\bibliography{\jobname}

\end{document}

Any hints please?

A: First of all: If you want to publish an article at ACM, you should not do any change on the style but use it as it is or you should at least ask the editor/publisher before doing such changes! Often editors/publishers will not accept such changes and undo them.
With natbib (used by default by acmart) you need to change ACM-Reference-Format.bst. To do so:

*

*make a copy of ACM-Reference-Format.bst in your document folder and name it, e.g., Non-ACM-Reference-Format.bst.

*open Non-ACM-Reference-Format.bst in a text editor and search for FUNCTION { proceedings }.

*replace the whole function by
FUNCTION { proceedings }
{
  output.bibitem
  editor empty.or.unknown
    { organization output
      organization format.key output }  % gnp - changed from author format.key
    { format.editors output.nonnull }
  if$
  % author format.key output             % gnp - removed (should be either
  %                                        editor or organization
  % output.year.check                    % added (newapa); Schweinebacke: removed
  new.block
  format.btitle format.city "title" output.check        % jtb: added city
  new.sentence
  format.bvolume output
  format.number.series output
  new.sentence
  editor empty.or.unknown % schweinebacke: added
  { } % schweinebacke: added
  { % schweinebacke: added
    organization output
  }% schweinebacke: added
  if$ % schweinebacke: added

  % jtb: normal order: publisher, address
  publisher empty.or.unknown
     { }
     { "\bibinfo{publisher}{" publisher * "}" * output }
  if$
  address empty.or.unknown
     { }
     { "\bibinfo{address}{" address * "}" * output }
  if$
  fin.block
  output.issue.doi.coden.isxn.lccn.url.eprint.note
  new.block                        % schweinebacke: added
  output.year.check                % schweinebacke: added
  fin.entry
}

*change
\bibliographystyle{ACM-Reference-Format}

in your document into
\bibliographystyle{Non-ACM-Reference-Format}

*do again run bibtex and also pdflatex.
The result would be

Note: In our days often usage of biblatex is recommended, because you can do changes of the bibliography with biblatex without bst hacking. To use biblatex with acmart you have to pass option natbib=false. In this case you could start with standard numeric style and change the formatting of the entries step by step.

A: I'd like to add to @Schweinebacke's answer.
It is relatively easy to change bibliographic formatting.  However, when you use "official" styles like ACM, you'd better not do it.  The reason is, publishers like ACM created their own 'house style', and insist on it being followed.  This is the reason their styles are given to the authors.  Changing this subverts the purpose of "official" styles.  You may prefer your way of formatting, but if you do not want problems with the publisher, please use theirs.
A self-respecting publisher just cannot allow two papers in the same journal or book to use different formatting.
I am afraid that the right way to change the formatting is to petition ACM to change their specifications.  Then it would be easy for me to accommodate.  This is not a TeXnical question, but a design question.


text:
Q: client.get_bucket() fails, but only from cloud dataflow (compute engine) Application has been working normally, now on a re-deploy, google storage is giving strange errors.
MissingSchema: Invalid URL 'None/storage/v1/b/my-bucket-name?projection=noAcl': No schema supplied. Perhaps you meant http://None/storage/v1/b/my-bucket-name?projection=noAcl?
  File "/usr/local/lib/python2.7/dist-packages/lib/file_store.py", line 11, in __init__
    self.bucket = self.client.get_bucket(parts[0])
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/storage/client.py", line 301, in get_bucket
    bucket.reload(client=self)
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/storage/_helpers.py", line 130, in reload
    _target_object=self,
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 392, in api_request
    target_object=_target_object,
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 269, in _make_request
    return self._do_request(method, url, headers, data, target_object)
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 298, in _do_request
    return self.http.request(url=url, method=method, headers=headers, data=data)
  File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/requests.py", line 208, in request
    method, url, data=data, headers=request_headers, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 462, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 313, in prepare
    self.prepare_url(url, params)
  File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 387, in prepare_url
    raise MissingSchema(error)
MissingSchema: Invalid URL 'None/storage/v1/b/my-bucket-name?projection=noAcl': No schema supplied. Perhaps you meant http://None/storage/v1/b/my-bucket-name?projection=noAcl? [while running 'generatedPtransform-51']

The code causing the error, I can run this locally using the same service account and it works, no error. I am using $env:GOOGLE_APPLICATION_CREDENTIALS to export my service account credentials at deploy time. All other services are working normally.
# My test is:
# fs = FileStore("gs://my-bucket-name/models/", "development", "general")

class FileStore():
    # modelPath - must be a gs:// style google storage resource path containing everything but the file extension
    def __init__(self, modelPath, env, modelName):
        from google.cloud import storage

        parts = modelPath[5:].split('/', 1)
        self.client = storage.Client()
        self.bucket = self.client.get_bucket(parts[0]) # <- error here

Why would google core client fail to build a URL? Based on 'None/storage/v1/b/my-bucket-name?projection=noAcl', the missing part of the URL should be something like "https://www.googleapis.com".

A: This error is apparently caused by a mismatch between google_cloud_storage and google_cloud_core. I had specified google_cloud_core >= 1.0.3 in my setup.py but when I looked on the docker image on the compute VM I found it had an earlier version.
After rebuilding my venv from setup.py I had to also run:
C:\Python27\python.exe -m pipenv install google-cloud-core>=1.0.3 --skip-lock

Then I was able to deploy and the application started working again.


text:
Q: How to store unhashable objects I'm using a library that provides me with some objects (SocketIO sessions, but that's a detail outside the scope of the question).
I want to store (the references to) those objects (not copies) upon connection and later remove them. Coming from a C++ background, I'd expect a set to be able to just store the pointers to those objects. But those are not hashable, so I can't put them in a set. And I don't know a Python way to get something akin to a pointer. I can put them in a list, but then the removal requires traversal (O(n)) and the insertion would allow duplicate.
Is there any trick to obtain something that behaves like a C++ pointer (comparable, ordered), from a Python object?
Right now, I'm doing:
# global var
my_objects = []

# upon receive:
my_objects.append(session)

# upon removal:
my_objects = my_objects - session

A: One idea is to use the id of the object. It identifies the object, although it will only work if you're really using the same object and not a new one with the same values.
# global var
my_objects = {}

# upon receive:
my_objects[id(session)] = session

# upon removal:
del my_objects[id(session)]


text:
Q: Generate random numbers using inversion method Assume you have an uniformly distributed r.v. $U(0,1)$. Use the inversion method to generate random numbers from an exponential distribution with parameter $\lambda$.
I have no idea where to start, can someone please explain the inversion method and help me solve the problem?

A: You 'invert' the cumulative probability of the uniform distribution to the exponential distribution by mapping $p$ in $U(0,1)$ to the $x$ that has the same cumulative distribution.
I found a nice document that explains it in more detail: http://www.columbia.edu/~ks20/4404-Sigman/4404-Notes-ITM.pdf
Example 1.1.1 is what you are looking for.


text:
Q: Random number generator in a for loop gives same numbers each time This program is supposed to function as a pretty primitive slot machine with three different "wheels" to spin. Each wheels contains a set amount of characters. A function generates a random number to assign as an array position in each wheel, which then yields a symbol corresponding to that position.
The problem I'm having is that the randomly generated number doesn't change through each iteration of my for loop. So I'm basically always getting "X - X" or " X @ -" for every single loop-through. I've searched through previously asked questions and found several related ones, but none seemed to solve my particular problem.
Apologies for the longish code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

const int WHEEL_POSITIONS = 30;
const char wheelSymbols[WHEEL_POSITIONS + 1] = "-X-X-X-X-X=X=X=X*X*X*X*X@X@X7X";

struct slotMachine
{
    char symbols[WHEEL_POSITIONS + 1];
    int spinPos;
    char spinSymbol;
} wheels[3];

void startWheels(slotMachine []);
void spinWheels(slotMachine []);
void displayResults(slotMachine []);
bool getWinner(slotMachine []);

int main(void)
{
    int spinNum;

    cout << "How many times do you want to spin the wheel? ";
    cin >> spinNum;

    // Calls startWheels function
    startWheels(wheels);

    for (int i = 0; i < spinNum; i++)
    {
        // Calls spinWheels function
        spinWheels(wheels);

        // Calls displayResults function
        displayResults(wheels);

        // Calls function getWinner; if getWinner is true, outputs winning message
        if (getWinner(wheels) == true)
        {
            cout << "Winner! Matched 3 of " << wheels[0].spinSymbol << "." << endl;
        }
    }

    return 0;

}

// Function to initialize each wheel to the characters stored in wheelSymbols[]
void startWheels(slotMachine fwheels[3])
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < (WHEEL_POSITIONS + 1); j++)
        {
            fwheels[i].symbols[j] = wheelSymbols[j];
        }
    }
}

// Function to generate a random position in each wheel
void spinWheels(slotMachine fwheels[3])
{
    time_t seed;

    time(&seed);
    srand(seed);

    for (int i = 0; i < 3; i++)
    {
        fwheels[i].spinPos = (rand() % WHEEL_POSITIONS);
    }
}

void displayResults(slotMachine fwheels[3])
{
    for (int i = 0; i < 3; i++)
    {
        fwheels[i].spinSymbol = fwheels[i].symbols[(fwheels[i].spinPos)];
        cout << fwheels[i].spinSymbol;
    }

    cout << endl;
}

bool getWinner(slotMachine fwheels[3])
{
    if ((fwheels[0].spinSymbol == fwheels[1].spinSymbol) && (fwheels[0].spinSymbol == fwheels[2].spinSymbol) && (fwheels[1].spinSymbol == fwheels[2].spinSymbol))
    {
        return true;
    }

    else
    {
        return false;
    }
}

I'm sure it's something simple that I'm missing, but I can't quite find it!

A: You are re-seeding your random number generator every time you call the function spinwheels.
Move these three lines into the top of your main function.
   time_t seed;

   time(&seed);
   srand(seed);

When we generate random numbers using rand(), we are actually using a pseudo-Random Number Generator (PRNG), which generates a fixed sequence of random-looking values based on a particular input called a seed. When we set the seed, we are effectively resetting the the sequence to start at the same seed again.
You might think that using time would result in a different seed each time, which should still give you a different result each time, but in a fast computer program, so little time has passed that the seed is effectively unchanged during each call.
That is why, as the other answer mentions, you should only call srand() once in your program.

A: You should only be calling srand() once in the program, not everytime you want to generate a random number.
If you reseed rand() via time() in a short succession you'll just end up restarting the sequence and end up getting the first value repeatedly.


text:
Q: Finding length of arc on unit circle only given x position Some background:
I've been trying to map a texture onto a "sphere" using a look up table of texture co-ordinate changes. This is for a really slow micro controller to draw on a little LCD panel. So Three.JS is out, WebGL etc... the look up table should work!
The equations for texturing a sphere all pinch the poles. I can't "pre-spread" the texture of these extremes because the texture offset changes to make the "sphere" appear to rotate.
If you examine the code for making the lookup table here, you'll see the approach, and the running demo shows the issue.
https://codepen.io/SarahC/pen/KKoKqKW
I figured I'd try and come up with a new approach myself!
After thinking a while, I realised a sphere texture in effect moves the location of the texture pixel further from the spheres origin the further away from the origin it is! In a straight line from the origin.
So I figured - calculate the angle the current pixel is from the origin, calculate it's unit distance, then all I need to do is make a function that is given the distance, and calculates the new distance based on some "sphere calculation". That new distance is almost 1 to 1 near the center of the sphere, and rapidly increases right at the edges. Mapping a sphere texture!
That offset function I figured (may be wrong here?) (diagrammed below) given the distance from the origin L1 (unit circle) it returns the length of the arc L2 which in effect is the flat pixel offset to use from the source texture.
(I asked on Reddit, and got given Math.acos for X, but now I know that's wrong, because that's the X position of the circle! Not the straight line X position from the offset, AND it gives an angle, not the Y position... wrong on two counts. Oooph!
Oddly, surprisingly, because I thought it gave the Y position, I dropped it into an atan2 function, and it ALMOST worked... for all the wrong reasons of course but it made a bump at the center of the "sphere".
The current "state of the mistake" is right here:
https://codepen.io/SarahC/pen/abYbgwa?editors=0010 )
Now I know that aCos isn't the function I need, I'm at a loss for the solution.
But! Perhaps this approach I thought up is stupid? I'd happily use any look-up mapping function you think would work.  =)
Thanks for your time and reading and sharing, I like learning new stuff.

//JS

A: An interesting but befuddling problem...
Per Spektre's comment and my follow up comment, the mapping of x to the length of the circle's arc still resulted in the center bubble effect of the image as described in the question.  I tried numerous mathematically "correct" attempts, including picking a distant view point from the sphere and then calculating the compression of the 2d image as the view point angle swept from top center of the sphere to the edge, but again, to no avail, as the bubble effect persisted...
In the end, I introduced a double fudge factor.  To eliminate the bubble effect, I took the 32nd root of the unit radius to stretch the sphere's central points.  Then, when calculating the arc length (per the diagram in the question and the comments on "L2") I undid the stretching fudge factor by raising to the 128th power the unit radius to compress and accentuate the curvature towards the edge of the sphere.
Although this solution appears to provide the proper results, it offends the mathematician in me, as it is a pure fudge to eliminate the confusing bubble effect.  The use of the 32nd root and 128th power were simply arrived at via trial and error, rather than any true mathematical reasoning.  Ugh...
So, FWIW, the code snippet below exemplifies both the calculation and use of the lookup table in functions unitCircleLut2() and drawSphere2(), respectively...

// https://www.reddit.com/r/GraphicsProgramming/comments/vlnqjc/oldskool_textured_sphere_using_lut_and_texture_xy/

// Perhaps useable as a terminator eye?........
// https://www.youtube.com/watch?v=nSlEQumWLHE
// https://www.youtube.com/watch?v=hx_0Ge4hDpI

// This is an attempt to recreate the 3D eyeball that the Terminator upgrade produces on the Adafruit M4sk system.
// As the micro control unit only has 200Kb RAM stack and C and no 3D graphics support, chances are there's no textured 3D sphere, but a look up table to map an eyeball texture to a sphere shape on the display.

// I've got close - but this thing pinches the two poles - which I can't see happening with the M4sk version.

// Setup the display, and get its pixels so we can write to them later.
let c = document.createElement("canvas");
c.width = 300;
c.height = 300;
document.body.appendChild(c);
let ctx = c.getContext("2d");
let imageDataWrapper = ctx.getImageData(0, 0, c.width, c.height);
let imageData = imageDataWrapper.data; // 8 bit ARGB
let imageData32 = new Uint32Array(imageData.buffer); // 32 bit pixel

// Declare the look up table - dimensions same as display.
let offsetLUT = null;

// Texture to map to sphere.
let textureCanvas = null;
let textureCtx = null;
let textureDataWrapper = null;
let textureData = null;
let textureData32 = null;

let px = 0;
let py = 0;
let vx = 2;
let vy = 0.5;

// Load the texture and get its pixels.
let textureImage = new Image();
textureImage.crossOrigin = "anonymous";
textureImage.onload = _ => {
  textureCanvas = document.createElement("canvas");
  textureCtx = textureCanvas.getContext("2d");

  offsetLUT = unitCircleLut2( 300 );

  textureCanvas.width = textureImage.width;
  textureCanvas.height = textureImage.height;
  textureCtx.drawImage(textureImage, 0, 0);
  textureDataWrapper = textureCtx.getImageData(0, 0, textureCanvas.width, textureCanvas.height);
  textureData = textureDataWrapper.data;
  textureData32 = new Uint32Array(textureData.buffer);
  // Draw texture to display - just to show we got it.
  // Won't appear if everything works, as it will be replaced with the sphere draw.
  for(let i = 0; i < imageData32.length; i++) {
    imageData32[i] = textureData32[i];
  }
  ctx.putImageData(imageDataWrapper, 0, 0);

  requestAnimationFrame(animation);
}

textureImage.src = "https://untamed.zone/miscImages/metalEye.jpg";

function unitCircleLut2( resolution ) {

  function y( x ) {
    // x ** 128 compresses when x approaches 1.  This helps accentuate the
    // curvature of the sphere near the edges...
    return ( Math.PI / 2 - Math.acos( x ** 128 ) ) / ( Math.PI / 2 );
  }

  let r = resolution / 2 |0;

  // Rough calculate the length of the arc...
  let arc = new Array( r );
  for ( let i = 0; i < r; i++ ) {
    // The calculation for nx stretches x when approaching 0.  This removes the
    // center bubble effect...
    let nx = ( i / r ) ** ( 1 / 32 );
    arc[ i ] = { x: nx, y: y( nx ), arcLen: 0 };
    if ( 0 < i ) {
      arc[ i ].arcLen = arc[ i - 1 ].arcLen + Math.sqrt( ( arc[ i ].x - arc[ i - 1 ].x ) ** 2 + ( arc[ i ].y - arc[ i - 1 ].y ) ** 2 );
    }
  }

  let arcLength = arc[ r - 1 ].arcLen;

  // Now, for each element in the array, calculate the factor to apply to the
  // metal eye to either stretch (center) or compress (edges) the image...

  let lut = new Array( resolution );
  let centerX = r;
  let centerY = r;

  for( let y = 0; y < resolution; y++ ) {
    let ny = y - centerY;
    lut[ y ] = new Array( resolution );

    for( let x = 0; x < resolution; x++ ) {
      let nx = x - centerX;
      let nd = Math.sqrt( nx * nx + ny * ny ) |0;

      if ( r <= nd ) {
        lut[ y ][ x ] = null;
      } else {
        lut[ y ][ x ] = arc[ nd ].arcLen / arcLength;
      }
    }
  }

  return lut;

}

function drawSphere2(dx, dy){
  const mx = textureCanvas.width - c.width;
  const my = textureCanvas.height - c.height;
  const idx = Math.round(dx);
  const idy = Math.round(dy);

  const textureCenterX = textureCanvas.width / 2 |0;
  const textureCenterY = textureCanvas.height / 2 |0;

  let iD32index = 0;
  for(let y = 0; y < c.height; y++){
    for(let x = 0; x < c.width; x++){
      let stretch = offsetLUT[y][x];
      if(stretch == null){
        imageData32[iD32index++] = 0;
      }else{
        // The 600/150 is the ratio of the metal eye to the offsetLut.  But, since the
        // eye doesn't fill the entire image, the ratio is fudged to get more of the
        // eye into the sphere...
        let tx = ( x - 150 ) * 600/150 * Math.abs( stretch ) + textureCenterX + dx |0;
        let ty = ( y - 150 ) * 600/150 * Math.abs( stretch ) + textureCenterY + dy |0;
        let textureIndex = tx + ty * textureCanvas.width;
        imageData32[iD32index++] = textureData32[textureIndex];
      }
    }
  }
  ctx.putImageData(imageDataWrapper, 0, 0);
}

// Move the texture on the sphere and keep redrawing.
function animation(){
  px += vx;
  py += vy;
  let xx = Math.cos(px / 180 * Math.PI) * 180 + 0;
  let yy = Math.cos(py / 180 * Math.PI) * 180 + 0;
  drawSphere2(xx, yy);
  requestAnimationFrame(animation);
}
body {
  background: #202020;
  color: #f0f0f0;
  font-family: arial;
}

canvas {
  border: 1px solid #303030;
}


text:
Q: Google SpreadSheets Timestamp for IMPORTDATA What I tried to accomplish is a Google AppScript, which automatically gives me a Timestamp, whenever a cell withing a certain range changes. The certain range is for example Sheet1, col 1-89:

function onEdit(event) {
  var ss = SpreadsheetApp.getActiveSheet();
  var r = ss.getActiveCell();
  if (r.getColumn() < 90 && ss.getName()=='Sheet1') {
var celladdress = 'CT' + r.getRowIndex()
    ss.getRange(celladdress).setValue(new Date()).setNumberFormat("MM/dd/yyyy hh:mm");
  }
};

When Sheet1 contains an IMPORTDATA feed; does this even work? Because my timestamp did not change since I implemented the script.
Thank you!

A: If your IMPORTDATA is refreshed from an active worksheet, then yes it will allow you to update a timestamp value.
You can use the event object passed to onEdit here rather than check the active cell. If the edited cell is one that you want to track, then set a timestamp. Something like this:
function onEdit(event) {
var r = event.range
var ss = r.getSheet()
if (r.getColumn() < 90 && ss.getName()=='Sheet1') {
var celladdress = 'CT' + r.getRowIndex()
    ss.getRange(celladdress).setValue(new Date()).setNumberFormat("MM/dd/yyyy hh:mm");
  }
};

Reference:
https://developers.google.com/apps-script/guides/triggers/events


text:
Q: capture subprocess output but print nothing to console? I'm trying to run a curl command using subprocess. Works fine. I've got the output I need in a variable. The onlything I want is when the process runs, I don't want this printing in the console:
          % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                         Dload  Upload   Total   Spent    Left  Speed
        100   255  100   153  100   102     56     37  0:00:02  0:00:02 --:--:--    56

Here's what that part of the script looks like:
        import subprocess

        def F_createSingleTable(table_name):
         un = "test"
         pw = "testpass"
         url = "https://blah.fake.url.com:7877/services/createstable"
         size = "10"
         size_til_archive = "30"
         retention = "5"
         curl_call =\
          [\
          'curl', \
          '-k', \
          '-u', \
          (un)+":"+(pw), \
          (url), \
          '-d', \
          'name='+(table_name), \
          '-d', \
          'size='+(size), \
          '-d', \
          'size_til_archive='+(size_til_archive), \
          '-d', \
          'retention='+(retention)\
          ]
         process = subprocess.run((curl_call), check=True, stdout=subprocess.PIPE, universal_newlines=True)
         output = process.stdout
         if "already exists" in (output):
          print("table: "+(table_name)+" already exists")

if it matters the actual response I get which is stored in output is this:
        <?xml version="1.0" encoding="UTF-8"?>
        <response>
          <messages>
            <msg type="ERROR">table_name table already exists</msg>
          </messages>
        </response>

I don't need to save it, just check if 'alredy exists" is in it. Which I have and works.
Thanks
NOTE: I was originally wanting to use subprocess.call but I couldn't seem to capture the output to check if already exists was in the response

A: What you're seeing on the console is on stderr, not stdout. In it's normal mode, curl prints the fetched content to stdout and the transfer stats to stderr. You can either suppress the statistics with the -s/--silent flag or discard stderr by passing stderr=subprocess.DEVNULL to your subprocess call.
If you care about the stderr output, you can also capture it separately by passing stderr=subprocess.PIPE or merge it into the stdout stream (obviously not recommended for the specific use case in the question) by passing stderr=subprocess.STDOUT.


text:
Q: Weird partition mess on KDE. Read-only file system I'm trying to partition a usb stick to NTFS.
Before, I've wrongly flashed a windows iso using dd
dd if=./AME_2004_\(2020-09-16\).iso of=/dev/sdc status=progress

and since then I've been having problems formatting the drive.
Kde Partition Manager, cfdisk and fdisk all yield the same result when trying to partition the drive to NTFS
/dev/sdc read only file system

There isn't any physical switch on the usb, and the error doesn't seem to be caused by permissions issues. I've even tried to modify its permissions by using
sudo chown root:root -R /dev/sdc
sudo chmod 666 /dev/sdc

but the problem still persists.
Other usbs work fine.
I've tried flashing a (smaller) working usb onto the non-working one
sudo dd if=/dev/sdd of=/dev/sdc status=progress

now the problem persists and I can't even use every GB of the non-working usb
sdc      8:32   1   7.5G  0 disk
└─sdc1   8:33   1   3.7G  0 part

I objectively have no idea of what I'm doing and what to do, so if you know anything just please say it right away.

A: Looks like your system is automatically mounting any disk it sees. Check if your sdc is mounted somewhere: grep 'sdc' /proc/mounts. If that is the case, then umount -f /dev/sdc a few times, until it's nowhere to be seen in /proc/mounts. When that's done, zero out the disk with dd if=/dev/zero of=/dev/sdc. After that, tell the kernel to reread the disk's info: blockdev --rereadpt /dev/sdc. Now fdisk should have no complaints about that disk, unless of course there's something physically wrong with that disk as a coincidence.

A: Turns out, the kde auto-mounting system, udisks2 can cause quite a bit of trouble. Especially when trying to modify and update disk partitions.
Temporarily disabling udisk2 using  sudo systemctl stop udisks2.service did it for me.
Refer to this thread for more


text:
Q: MySQL batch and join: is it possible using SQL file injection? Here's a sample of a table I have:
mysql> select * from table_a where description='Auto';
+----+----------+-------------+-----------------+
| id | idparent | description | description_url |
+----+----------+-------------+-----------------+
| 11 |     NULL | Auto        | NULL            |
| 74 |       73 | Auto        | NULL            |
+----+----------+-------------+-----------------+
2 rows in set (0.00 sec)

mysql>

Now I insert into another table another record and remember its last inserted id:
INSERT INTO table_b (description) values ('Myvalue');
set @lt=LAST_INSERT_ID();

Now I have into @lt the value.
I could do this (and it works):
INSERT INTO table_a_link_b (id_a, id_b) VALUES (11, @lt);
INSERT INTO table_a_link_b (id_a, id_b) VALUES (74, @lt);

Now what follows doesn't work:
INSERT INTO table_a_link_b (id_a, id_b) VALUES
    ( (SELECT id FROM table_a where description='Auto') , @lt);

So I tried to put it into a variable:
mysql> set @t=(select id from table_a where description='Auto');
ERROR 1242 (21000): Subquery returns more than 1 row

It doesn't work. Is there a way I could do it without making a Php batch file and stay pure SQL?

A: INSERT INTO table_a_link_b (id_a, id_b)
SELECT id,@lt FROM table_a where description='Auto';

A: Wouldn't something like this work?
INSERT INTO table_a_link_b (id_a, id_b)
  SELECT id, max(table_b.id) FROM table_a
    join table_b on table_a.description = table_b.description
   where table_a.description='Auto' group by table_a.id;


text:
Q: Adding search box for admin on custom admin page I have fetched some rows on my custom admin page (using hook for adding admin menus).
Now I want to add a search box on that page to display only those rows with the 'title' column containing searched string in that column.
I'm trying with
SELECT * FROM Table WHERE Column LIKE %

to get the data. Please give me some idea.
How to do this stuff?

A: I fetched some rows on my custom admin page (using hook for adding admin menus).
I wanted to add a search box on that page to display only those rows with the 'name' column containing searched string in that column.
ID     |    Name
_________________
1      |    abc
2      |    abc
3      |    abz
4      |    xyz
_________________

I was trying with
$keyword = $_POST['data'];
$poi_sql="SELECT * FROM Details WHERE Name LIKE %".$keyword;

I got this::
$keyword = $_POST['data'];
$poi_sql="SELECT Name FROM Details WHERE Name LIKE '%". $keyword ."%'";

Silly mistakes. P)


text:
Q: fileReader and scanner I do not understand how to read data from .txt file below.
static final String DATA_PATH = "DataFile.txt";

public static void main(String[] args) {

    Scanner fileReader = null;
    try {

        fileReader = new Scanner(new File(DATA_PATH));
        //Print out a trace of the program as it is running
        System.out.println("Debug: Scanner is open "+fileReader);
    } catch (FileNotFoundException e) {
        // If the file is not there, an exception will be thrown and the program flow
        // will directed here.  An error message is displayed and the program stops.
        System.out.println("The file "+DATA_PATH+" was not found!");
        System.out.println("The program terminates now.");
        System.exit(0);
    }

A: Here is the example of readFile by using the Scanner. So, you should import three important packages which are :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

After that, you create the file object along with the file's name parameter. Then, the scanner object is created. Finally, you can use while loop to read line by line or whatever you want.
 public class ScannerReadFile {
    public static void main(String[] args) {
        //
        // Create an instance of File for data.txt file.
        //
        File file = new File("data.txt");

        try {
            //
            // Create a new Scanner object which will read the data
            // from the file passed in. To check if there are more
            // line to read from it we check by calling the
            // scanner.hasNextLine() method. We then read line one
            // by one till all line is read.
            //
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

So, you can try to start from the code that I mentioned here and Practice more! from many tutorials on websites.


text:
Q: Meteor aldeed collections2 update data to array of objects using for loop Hello Now i have a problem. I want to insert data to array of objects using for loop
fields:{
        type:[Object],
        label:"Fields",
        optional:true
    },
    "fields.$.category":{
        type:String,
        label: "Category"
    },
    "fields.$.sub":{
        type:String,
        label:"Sub Category",
    },

And using savaData.js in server i tried
// ServiceProviders.update({
                    //  '_id':"GmkGSXjyNFshomdCu"},
                    //  {
                    //      '$set': {'fields':{
                    //              '$.category':categorydata,
                    //              '$.sub':subdata
                    //      }}
                    //  },function(error,result){console.log(error);console.log(x+y);});

and
ServiceProviders.update(
{'_id': 'JN4mRPfJZqBadZtPY' },
    {'$set': {'fields.0.category': categorydata,'fields.0.sub':subdata}},
     true );

then
 var x = "fields."+i+".category";
                    var y = "fields."+i+".sub";
                    x=x.toString();
                    y=y.toString();
    ServiceProviders.update(
    {'_id': 'JN4mRPfJZqBadZtPY' },
    {'$set': {x: categorydata,y:subdata}},
     true );

I got Different errors every time could you please help me in this issue

A: Currently, $ Does not work on Meteor js.
So you have to create a fields object on either server side or client side:
var fieldsData = []
for (var i = 0; i < categorydata.length || i < subdata.length ; i++ ){
    fieldsData.push({
       category : ( categorydata[i] ? categorydata[i] : '' ),
       sub : ( subdata[i] ? subdata[i] : '' )
    })
}

ServiceProviders.update(
    {'_id': 'JN4mRPfJZqBadZtPY' },
    {'$set': {fields : fieldsData}},
     true );

Please make sure for either every filds data have cat and subcat value or make cat and subcat cat optional true.


text:
Q: Offline map in google-map-react I use google-map-react and I want to load images from localhost and I have some problems. This is my code:
         <GoogleMapReact
            onGoogleApiLoaded={({map, maps}) =>
                map.mapTypes.set("roadmap", new maps.ImageMapType({
                    getTileUrl: function (coord, zoom) {
                        return "http://192.168.1.103/google/" + zoom + "/" +  coord.x + "/" + coord.y + ".png"
                    },
                    tileSize:new maps.Size(256,256),
                    name:"GoogleRoadMaps",
                    maxZoom:18
                }))
            }
            yesIWantToUseGoogleMapApiInternals
            defaultCenter={this.props.center}
            defaultZoom={this.props.zoom}>
            {
                this.state.childrenm
            }
        </GoogleMapReact>

But it doesn't work. What's the problem?

A: There are a few possible causes:

*

*192.168.1.103 is your local area networt (LAN) IP address, which means it will only work if the WIFI of the client is connected to the same WIFI as the server and the machine is configured to allow connections on port 80.

*Content Security Policy(CSP) will need to be setup to upgrade the http connection to https if the site is secure

*If a hardcoded URL does not work, then the zoom may be configured incorrectly


text:
Q: Pandas timedelta64[ns] calculations I have the following DataFrame:
>>> sampleDate = pd.date_range('2018-01-01', periods=10, freq='D 16H')
>>> duration = pd.TimedeltaIndex(data =['123 days 5 hours', '1 day 6 min',  '2 days', '23 hours 7 min','5 days 17 hours 3 min','18 min', '1 day 17 hours',  '22 day 2 min', '22 hours','15 min'])
>>> df = pd.DataFrame(data={'time': sampleDate, 'duration': duration})
>>> df = df.set_index('time').sort_index()
>>> df
                             duration
time
2018-01-01 00:00:00 123 days 05:00:00
2018-01-02 16:00:00   1 days 00:06:00
2018-01-04 08:00:00   2 days 00:00:00
2018-01-06 00:00:00   0 days 23:07:00
2018-01-07 16:00:00   5 days 17:03:00
2018-01-09 08:00:00   0 days 00:18:00
2018-01-11 00:00:00   1 days 17:00:00
2018-01-12 16:00:00  22 days 00:02:00
2018-01-14 08:00:00   0 days 22:00:00
2018-01-16 00:00:00   0 days 00:15:00

I would like to do statistics on the different weeks or days of the year (e.g. mean duration during the first 7 days of the year). What I have tried is running
>>> df.rolling('7d').mean()

pandas.core.base.DataError: No numeric types to aggregate

What would it take to get it to pick up the right column?

A: You can convert duration to native format by astype, count mean and convert back:
df['duration'] = df['duration'].astype(np.int64)
df = pd.to_timedelta(df.rolling('7d')['duration'].mean())
print (df)
time
2018-01-01 00:00:00   123 days 05:00:00
2018-01-02 16:00:00    62 days 02:33:00
2018-01-04 08:00:00    42 days 01:42:00
2018-01-06 00:00:00    31 days 19:03:15
2018-01-07 16:00:00    26 days 13:51:12
2018-01-09 08:00:00     1 days 22:30:48
2018-01-11 00:00:00     2 days 01:53:36
2018-01-12 16:00:00     6 days 01:54:00
2018-01-14 08:00:00     6 days 01:40:36
2018-01-16 00:00:00     4 days 22:19:00
Name: duration, dtype: timedelta64[ns]

Or convert timedeltas to seconds:
df['duration'] = df['duration'].dt.total_seconds()
df1 = df.rolling('7d')['duration'].mean()
print (df1)
time
2018-01-01 00:00:00    10645200.0
2018-01-02 16:00:00     5365980.0
2018-01-04 08:00:00     3634920.0
2018-01-06 00:00:00     2746995.0
2018-01-07 16:00:00     2296272.0
2018-01-09 08:00:00      167448.0
2018-01-11 00:00:00      179616.0
2018-01-12 16:00:00      525240.0
2018-01-14 08:00:00      524436.0
2018-01-16 00:00:00      425940.0
Name: duration, dtype: float64


text:
Q: Java Generic Type with wildcard extends class I try to use BiConsumer in Java to do an addition, which accepts all Number type.
My code is as follow:
public class App {
    public static void main(String[] args) {
        BiConsumer<? extends Number, ? extends Number> addition = (a, b) -> {
            Double sum = a.doubleValue() + b.doubleValue();
        };
        addition.accept(1, 2.3);
    }
}

But it will have compiler error as below when I call the accept method in BiConsumer:

The accept method has a simple method signature as below:
void accept(T t, U u);
I am not familiar with Generic, can anyone explain why we cannot do so?
If it is invalid, why doesn't the compiler indicates when I declare ? extends Number in the BiConsumer.
And what is the proper why to achieve my goal?


text:
Q: Special character in filename I have many special characters in a filename e.g., ./CaMKII-8+PP1-32+L-125e-9+N-5+diff-0.1e-12.dat_processed.csv. I want to write this filename in a footnote. To make matter worse, this filename is stored in a macro e.g., \edef\fiename\{./CaMKII-8+PP1-32+L-125e-9+N-5+diff-0.1e-12.dat_processed.csv}.
When I try to print it using \texttt{\fileName}, I run into a 'missing $ inserted' issue. If I use \verb!\fileName!, it just prints \fileName (it's not expanded.)
How to get the filename printed in my pdf?

A: If the file name is stored in a macro, you can exploit \detokenize:
\newcommand{\fileName}{}% just to see it can be used
\edef\fileName{\detokenize{./CaMKII-8+PP1-32+L-125e-9+N-5+diff-0.1e-12.dat_processed.csv}}

This will have no consequence when \fileName is used for reading a file.
Note that you need \usepackage[T1]{fontenc} for the underscore to print when not in a \ttfamily or \texttt context. It will print fine with \texttt{\fileName}.


text:
Q: How to block the user from Accessing other Apps in Android? My question is exactly the same as this one Block Applications. However, there weren't any useful solutions that I could use for my reference. I am an Android beginner and am trying to build an App for a school project which has a functionality similar to FocusLock. For example, I want my app to prevent the user from accessing Messaging or Facebook. While I could get the list of Foreground apps, I am not able to block the user from accessing it.
Eagerly awaiting your suggestions.
Thanks!


text:
Q: Simple nested object produces `SyntaxError: Unexpected token` in Chrome console? How come this parses fine:
{a:5,{b:{c:7}}}

But all the forms below yield SyntaxError: Unexpected token '{'?
o={a:5,{b:{c:7}}}

console.log({a:5,{b:{c:7}}})

({a:5,{b:{c:7}}})

var o = {a:5,{b:{c:7}}}

var o = {"a":5,{"b":{"c":7}}};

A: Well if you take a look at this {a:5,{b:{c:7}}} we can see that it isn't a valid javascript object because an object should have key-value pairs.
a: 5 is fine but {b:{c:7}} doesn't have a key.

A: All of your object literals have an error:
{
  a: 5,
//v--- a key is missing, so { is unexpected
     {
     b: {
       c: 7
    }
  }
}

Because of that, all codes should throw.
However, your first one does not.
That is because when the JS interpreter encounters a {, immediately guesses if it is meant to be an object literal or a block statement. If both cases are possible, it assumes a block statement.
That happens in this case as well, and if you look at it closer, it's valid that way:
| block statement                              |
| |label|number|comma operator|object literal| |
 { a:    5      ,              {b:{c:7}}      }

A: type this into the console:
'hello', 'world', 42

The result is 42. You can read more about expressions like that at MDN
The question shows that you were thinking this were an object expression, which it isn't.
The JavaScript parser cannot read thoughts. Opening and closing curly braces ({,}) mark start and end not only for object literals; they do that also for the body of a function, the body of an if expression, and more. How is the JavaScript parser supposed to find out what you mean, when encountering an opening curly brace? What starts here? An object? The body of a function? The body of an if? A sequence-expression (those are the ones I mentioned in starting)?
There are JavaScript parsers written in JavaScript (like esprima or babel), which can help newbies and long-year professionals alike when "thinking like a parser" is required. Whether noob or pro, I recommend you get esprima and try out things like this:
esprima.parse('1,2,3').body[0].expression  // { type: "SequenceExpression", expressions: [ ... ]}

esprima.parse('{a:5,{b:{c:7}}}').body[0].body[0].body.expression // also SequenceExpression

or this
esprima.parse('{}').body[0] // BlockStatement

esprima.parse('({})').body[0]  // ObjectExpression

With esprima, you can get to the bottom of questions like, why ({hi:'petard',lo:'biere'})['hi'] works, but {hi:'petard',lo:'biere'}['hi'] doesn't, or the question you had.

A: it can be parsed but as different objects (the console prints the second only)
to be fixed: it needs to be in the format of key:value
e.g.
{a:5} {a:5,b:4} {a:5,b:{a:4}} but the one you have {a:5,{b:{c:7}}}
as key:value pair, you are missing for the second sub-object the key
so you need to assign something maybe like this:
const o={a:5,d:{b:{c:7}}} or stay to my second example above: const o={a:5,b:{c:7}}
think of it how it would look like trying to get each value in a javascript function
 const  o={a:5,d:{b:{c:7}}}
o.a=5, o.d={b:{c:7}}, o.d.b={c:7}, o.d.b.c=7


text:
Q: Disable drawer when app is in landscape mode I am working on one functionality where I want to disable drawer when app is in landscape mode for both iOS & Android. I saw the DrawerView from React-Navigation.
render() {
 // some code
    return (
      <DrawerLayout
        ref={(c: *) => {
          this._drawer = c;
        }}
        drawerLockMode={
          (this.props.screenProps && this.props.screenProps.drawerLockMode) ||
          (config && config.drawerLockMode)
        }
      //some code
       >
        <DrawerScreen
          screenProps={this.props.screenProps}
          navigation={this._screenNavigationProp}
        />
      </DrawerLayout>
    );
}

Here screenProps is used to handle the lock mode. I can disable the drawer using navigationOptions but I want to disable when user changes the orientation.
One more thing I have used StackNavigator inside DrawerNavigator.

A: first check this answer for modes How check status of Phone is Landscape or Portrait when Ativity not auto rotation?
then do drawer.setEnabled(false) accordingly.


text:
Q: (php скрипт) анализ позиций сайта в поисковой системе Доброго времени суток. Кто ранее сталкивался с подобным? Интересует есть ли система на php для анализа позиций сайта в поисковике по ключевым словам. Интересуют любые варианты, куски кода, статейки и т.д. Хочу для начала понять принцип работы.
Цель создать свой такой инструмент.
A: Яндекс.XML — сервис, позволяющий отправлять запросы к поисковой базе Яндекса и получать ответы в формате XML.


text:
Q: Known computations of certain 2-cohomology groups? I wanted to know if there are any computations of cohomology groups $H^n(\Gamma,A^{(\Gamma)})$ in the literature for certain $n\in\mathbb{N}$, Abelian groups $A$, and infinite groups $\Gamma$.
Here $A^{(\Gamma)}$ is the direct sum of copies of $A$ (one for each $g\in\Gamma$) and $\Gamma$ acts on $A^{(\Gamma)}$ via $(g.\xi)_h = \xi_{h g}$ for $\xi\in A^{(\Gamma)}$ and $g,h\in\Gamma$. Moreover, the cohomology theory under consideration is the (classical Eilenberg-MacLane) group cohomology of $\Gamma$ with coefficients in $A^{(\Gamma)}$.

A: When $A$ is a commutative ring, the module $A^{(\Gamma)}$ you describe coincides with the group ring $A[\Gamma]$ with it's canonical (right) $\Gamma$-action.
In particular, let $A=\mathbb{Z}$. Then $\Gamma$ is a duality group if there exists an integer $n$ such that $H^i(\Gamma ; \mathbb{Z}[\Gamma])=0$ for $i\neq n$ and $H^n(\Gamma;\mathbb{Z}[\Gamma])$ is torsion-free. In this case, $D=H^n(\Gamma;\mathbb{Z}[\Gamma])$ is called the dualizing module, and if $D \cong \mathbb{Z}$ then $\Gamma$ is called a Poincaré duality group. See Brown's "Cohomology of groups", section VIII.10, or Bieri and Eckmann's Inventiones paper "Groups with homological duality generalizing Poincaré duality"


text:
Q: Can't INSER timestamp into Postgresql psycopg2 I'm traying to inster timestamps as values in columns of my Postresql query but I seamn to get all sort of formating error in al variant ways is have tried this.
i have 3 cols that are timestamp : time_stamp,  start_date, end_date
start_date = datetime.strptime('2020-03-17 16:00:00', "%Y-%m-%d %H:%M:%S").timestamp()
end_date = datetime.strptime('2020-03-17 16:00:00', "%Y-%m-%d %H:%M:%S").timestamp()

sql_insert_query = 'INSERT INTO public.table(time_stamp, name, name_short, geo, link, img_url, source, type, category, start_date, end_date, quantity, remaining)' \
              ' VALUES ( current_timestamp, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,%s, %s);'

insert_tuple = (item['name'],'name_short',item['language'],item['_url'],item['image_url'],'_API',item['coupon_type'],item['category'],start_date ,end_date,coupon_limits,item['unused'])

cur = conn.cursor()
cur.execute(sql_insert_query, insert_tuple)

Error is (not exact as is translated):
psycopg2.ProgrammingError: the column «start_date» is of type timestamp without time zone but the expression is type numeric

on the SQL table i have declared columns as
    time_stamp timestamp without time zone NOT NULL DEFAULT now(),
    start_date timestamp without time zone,
    end_date timestamp without time zone NOT NULL,


text:
Q: Do Toughness or Vitality help with surviving fall damage? According to the GW2 wiki, Falling Damage:

Fall damage is proportional to the characters health: if a level 80 and a level 1 fall the same height, the amount taken will be different, but the percentage of health taken away will be the same.

Does this mean that both Toughness and Vitality don't reduce fall damage? Or would Toughness help because it's a fixed damage reduction rather than an increase in HP?

A: Toughness only reduces direct damage, rather than indirect damage. As such, toughness has no effect on fall damage according to the Guild Wars 2 wiki.
Stacking Vitality will not help, but does have an effect on fall damage - since fall damage is percentage based, having more vitality will cause you to take more damage, as you will always lose the same percentage of health from the fall.


text:
Q: Values from xml data field in mysql i would like to know if there is a query to select values from all of my xml data fields. There are around 1k rows which has xml data. All of them has almost the same data structure. With extract value i was able to extract one data field but at the point where more than one row is part of my subquery it breaks.
Here is an example xml data inside my db:
    <EDLXML version="1.0.0" type="variable">
  <properties id="template_variables">
    <deliveredDuration>4444</deliveredDuration>
    <deliveredNum>1</deliveredNum>
    <comment/>
    <projectname>cdfkusen</projectname>
    <name>kral_schalke_trenink</name>
    <order_id>372846</order_id>
    <cutlistId>2763_ID</cutlistId>
    <bcutlistId>51ddgf7a6-1268-1gdfged-95e6-5254000e8e1a</bcutlistId>
    <num>1</num>
    <duration>177760</duration>
    <quotaRelevantDuration>0</quotaRelevantDuration>
    <organisationUid>OrgName</organisationUid>
    <organisationQuota>333221233</organisationQuota>
    <organisationUsedQuota>123</organisationUsedQuota>
    <organisationContingentIrrelevantQuotaUsed>54</organisationContingentIrrelevantQuotaUsed>
    <userDbId>7xxxx84-eb9b-11fdsb-9ddd1-52cccccde1a</userDbId>
    <userId>xxxx</userId>
    <userRights>RH_DBC</userRights>
    <firstName>DThom</firstName>
    <lastName>Test</lastName>
    <userMail>xxx@ccc.cz</userMail>
    <language>English</language>
    <orderTimestamp>1659448080</orderTimestamp>
    <stitching>false</stitching>
    <transcode>NO</transcode>
    <destination>Standard</destination>
    <collaboration>private</collaboration>
    <premiumUser>false</premiumUser>
    <priority>normal</priority>
    <userMail2>xxx@ccc.cz</userMail2>
    <cutlistItems>
      <cutListId>125124_KFC</cutListId>
      <cutListItemId cutlistItemDeliveryStatus="&#10004" cutlistItemDStatusMessage="delivered">112799</cutListItemId>
      <bmarkerId>8f16ff80-1269-11ed-95e6-5254000e8e1a</bmarkerId>
      <videoId>2912799</videoId>
      <counter>1</counter>
      <frameInSpecified>true</frameInSpecified>
      <frameIn>15638</frameIn>
      <frameOutSpecified>true</frameOutSpecified>
      <frameOut>20082</frameOut>
      <tcIn>00:10:25:13</tcIn>
      <tcOut>00:13:23:07</tcOut>
      <duration>177760</duration>
      <BroadcastDate>2021-07-24</BroadcastDate>
      <eventDate>2021-07-24</eventDate>
      <resolutionFacet>HD</resolutionFacet>
      <provider>DBC</provider>
      <technicalrightholders>RH_DBC</technicalrightholders>
      <rights>DBC</rights>
      <materialType>DP</materialType>
      <targetFilename>kral_schalke_trenink</targetFilename>
    </cutlistItems>
  </properties>
</EDLXML>

I got the right value from query if i do:
SELECT ExtractValue((SELECT job_xml from cutlist where job_xml is not null LIMIT 1), '//deliveredNum');

But when i change the limit amount i get back: Subquery return more than one row.

A: extractvalue expects two string arguments. When your subquery returns more than one row, you are not simply passing a string as the first argument (you are passing a set of results).
Instead of calling extractvalue once for your entire query, call it once for every row, like:
SELECT ExtractValue(job_xml, '//deliveredNum')
FROM cutlist
WHERE job_xml IS NOT NULL


text:
Q: How do I change the background color of the column with the expanders in Eclipse? Recently after scorching my retinas from the garish white background in Eclipse, I found some of the excellent posts about how to change the colors so it uses sane (i.e. dark background) colors in the editor.  However, one problem present in all solutions is that background of the column with the expanders for code folding is always white.  Is there a way to change the background of that column?
I'm not the only person that has this problem, as shown in the screenshots for the following questions:

*

*Dark Color Scheme for Eclipse

*Color Themes for Eclipse (application of color schemes results in this issue on a Mac, no idea about PC)

I know that the problem is not language specific as it happens in Java, Python, HTML, and everything else.  Any hints on where in the pages of preferences this setting is?

A: This is related to Eclipse Bug 62712 which is fixed in build 20090329-2000 almost a year ago. In my Galileo of build 20090920-1017 it just works when I change the background color through General > Editors > Text Editors. Here's a screen (don't pay attention to the ugly color combo, my bg defaults to white and I just picked random yellow to demonstrate that the ruler background get changed as well):

In other words, just upgrade your Eclipse to include this bugfix. Did you check Help > Check for Updates?


text:
Q: not able to pass a array as prop to react component and render it Problem : I want to pass a array to QuizResult component and need to display it in  tag.
Code:
markedAnswers = [0,1,2,3,1,1,4,4]
<QuizResult result={markedAnswers}/>

const QuizResult = (result) => {
  return (

      {result.map((data, index) =>
 {data}
)} - result.map is not a function error

{result}
  - no error, empty div is shown

  );
};

export default QuizResult;

What i am missing here?

A: In this case:
const QuizResult = (result) => {

The result variable is an object containing all of the passed props.  So you'd refer to result.result for the array.  Instead, destructure the props in the function:
const QuizResult = ({result}) => {

Then result would contain just the array.


text:
Q: When is a normal curve sure to "fit" to a histogram of probabilities? In order to be able to create a histogram for the probabilities of an event (e.g. scoring 0,1,2,3...n heads in a row) that matches a normal curve the distribution must be symmetric.
Something like:

My question is: is there in general a relation between how big the n is with whether we can have a histogram such as the one in the image or is it irrelevant?
What would it depend on then?
Update after the comments:
Yes my example with the coin is indeed a binomial distribution but it was only an example of a case that can be represented by a histogram.
My question was about the cases that the histogram matches a normal curve.

A: If you have a binomial random variable with $n$ trials and Success
probability $p$ on each trial, then the number $X$ of heads observed
will become very nearly normal for large $n.$ The convergence to
normal is faster of $p = 1/2.$
Often one looks at $Z_n = \frac{X - np}{\sqrt{np(1-p)}},$ so that
$E(Z_n) = 0$ and $Var(Z_n) = 1.$ Then $Z_n$ 'converges in distribution'
to standard normal. Roughly speaking, that means
$\lim_{n \rightarrow \infty}P(Z_n \le c) = \Phi(c),$ where $\Phi$
denotes the CDF of the standard normal distribution.
For example, suppose $n = 100$ and $p = 1/2$ and let $X$ be the
number of successes. Then the exact value of $P(X \le 40) = 0.0284,$ to
four places. This can be found by summing the terms of the binomial
distribution from $P(X = 0)$ up through $P(X = 40).$ In R statistical
software, the computation is as follows:
pbinom(40, 100, .5)
## 0.02844397

Because this binomial distribution is nearly normal we can compute this
as
$$P(X \le 40) = P(X \le 40.5) = P\left(\frac{X - np}{\sqrt{np(1-p)}} \le
\frac{40.5 - 50}{5} = -1.9 \right) \approx \Phi(-1.9),$$
which can be evaluated as 0.0287, using printed normal tables or software.
pnorm(-1.9)
## 0.02871656

[Using 40.5 instead of 40 allows a better match between the discrete
binomial distribution and the continuous normal distribution. This is
sometimes called a 'continuity correction'.]
The plot below shows values of $\mathsf{Binom}(100,.25)$ with substantial
probability, along with the density function of $\mathsf{Norm}(\mu=50,\,\sigma=5).$ The relevant probability is to the left of the
vertical red line.

Also, if $n = 1000$ and $p = 1/4$ then $E(X) = 250$ and $SD(X) = 13.6931.$
If we seek $P(X \le 275)$ the exact value to four places is 0.9677,
and the value from a normal approximation is 0.9687. This illustrates
that the convergence of binomial to normal is usefu even if $p \ne 1/2,$
provided $n$ is sufficiently large. [Usually,
the normal approximation gives about two-place accuracy.]
pbinom(275, 1000, .25)
## 0.9677063
pnorm(275.5, 250, 13.6931)
## 0.9687162

A: The binomial $\text{pdf}$ is
$$B_k=\binom nkp^kq^{n-k}$$
while the corresponding normal approximation would be
$$\frac1{\sqrt{2\pi npq}}e^{-(k-np)^2/2npq}.$$
More precisely, we obtain the probability of the $k^{th}$ bin by integrating between half integers,
$$N_k=\int_{k-1/2}^{k+1/2}\frac1{\sqrt{2\pi npq}}e^{-(k-np)^2/2npq}dt=\Phi\left(\frac{k+\frac12-np}{\sqrt{npq}}\right)-\Phi\left(\frac{k-\frac12-np}{\sqrt{npq}}\right).$$
In the case of a fair coin,
$$B_k=\binom nk\frac1{2^n},$$
$$N_k=\Phi\left(\frac{2k-n+1}{\sqrt{n}}\right)-\Phi\left(\frac{2k-n-1}{\sqrt{n}}\right)\approx\sqrt{\frac2{\pi n}}e^{-(2k-n)^2/2n}=\tilde N_k.$$
Comparing these curves seems barely tractable by analytical methods.
The plot below shows the discrepancies between the Binomial and Normal laws, either exact or approximated, for $n=100$.

Fortunately, the largest error seems to occur in the middle, where
$$B_{n/2}=\binom n{n/2}\frac1{2^n},$$
$$N_{n/2}=2\Phi\left(\frac1n\right).$$
Note that approximating the Binomial term by Stirling makes the two values equal, so that a better approximation is required.
From Wikipedia,
$$\binom n{n/2}\approx2^n\sqrt{{\frac 2{\pi n}}}\left(1-\frac{2c_n}n\right)$$ with $\frac19<c_n<\frac18$. Hence the maximum error decreases like $$\frac1n.$$


text:
Q: Rails Model - custom primary key with ID as a custom column I struggle with modeling my table to Rails model with custom primary key and id as a regular (not null) column.
The problem is my table has:

*

*auto_id primary key column with AUTO_INCREMENT

*id as custom column with NOT NULL constraint on it (it should be set by the application side before saving)

class InitialMigration < ActiveRecord::Migration[6.1]
  def change
    create_table :cars, id: false, force: true do |t|
      t.primary_key :auto_id
      t.string :id, null: false
    end
  end
end

I want to:

*

*Make the primary_key being auto generated by database.

*Set the id value directly in the application before saving the model.

But when I try to save a Car instance to database I have a problem with setting id from the app.
class Car < ActiveRecord::Base
  self.primary_key = "auto_id"

  before_create do
    binding.pry
  end
end

Even in the binding.pry line, when I call self.id = '1234' it's being reassigned to auto_id field, instead of id.
Thus id columns always remain NULL which leads to a DB error Field 'id' doesn't have a default value.
[2] pry(#<Car>)> self.id = '9'
=> "9"
[3] pry(#<Car>)> self
=> #<Car:0x00007fcdb34ebe60
 auto_id: 9,
 id: nil>

PS. It's Rails 6.

A: I'd avoid using id this way by renaming it to something else. In rails id is whatever the @primary_key is set to. There is a whole module dedicated to it, that defines id attribute methods:
https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey.html
These methods can be overridden, but shouldn't:
class Car < ApplicationRecord
  self.primary_key = "auto_id"

  def id= value
    _write_attribute("id", value)
  end

  def id
    _read_attribute("id")
  end
end

"id" is hardcoded in write_attribute to use primary_key, so we can't use write_attribute to set id attribute itself.
Also, id methods are used in other places. Overriding them is a bad idea.
>> Car.create(id: "99")
=> #<Car:0x00007f723e801788 auto_id: nil, id: "99">
#                                    ^
# NOTE: Even though car has been saved, `auto_id` is still `nil`
#       but only in `car` object. Because we have overridden
#       `id`, primary key is read from `id` column and then `id`
#       attribute is set in `id=`. `auto_id` is bypassed.

>> Car.last
=> #<Car:0x00007f774d9e8dd0 auto_id: 1, id: "99">

# NOTE: Other methods are broken whenever `id` is used

>> Car.last.to_key
=> ["99"]
>> Car.last.to_gid
=> #<GlobalID:0x00007f774f4def68 @uri=#<URI::GID gid://stackoverflow/Car/99>>

A better way is to not touch id methods:
class Car < ApplicationRecord
  self.primary_key = "auto_id"

  def id_attribute= value
    _write_attribute("id", value)
  end

  def id_attribute
    _read_attribute("id")
  end
end

>> car = Car.create(id_attribute: "99")
=> #<Car:0x00007fb1e44d9458 auto_id: 2, id: "99">

>> car.id_attribute
=> "99"
>> car.id
=> 2
>> car.auto_id
=> 2