text:
Q: Listings - Hide range labels and suffix/prefix from code I'm using listings to generate some code boxes, and am taking excerpts using range labels with suffixes and prefixes. I'm able to hide the begging tag from the full code by escaping to LaTeX and using \phantom, but when I try to escape to LaTeX with the end tag inside, it does not work..
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{cleveref}

\lstset{
    language=Python,
    basicstyle=\ttfamily\small,
    aboveskip={1.0\baselineskip},
    belowskip={1.0\baselineskip},
    frame=tblr,
    rulecolor=\color{gray},
    keywordstyle=\color[rgb]{0.627,0.126,0.941},
    commentstyle=\color[rgb]{0.133,0.545,0.133},
    stringstyle=\color[rgb]{01,0,0},
    numbers=left,
    numberstyle=\footnotesize\color{gray},
    captionpos=t,
    escapeinside={\#`}{`},
}

\begin{document}

\section{Examples}

\subsection{Excerpt of Code}
\lstinputlisting[includerangemarker=false,
rangeprefix=:~,
rangesuffix=~:,
linerange=beg:def-end:def,
]{"ex.py"}

\subsection{Full Code}
\lstinputlisting[
]{"ex.py"}

\end{document}

With the Python code below
import numpy as np

x = np.linspace(0,10,num=100)
#`\phantom{:~beg:def~:}`
def y(x, a=1, b=1, c=1):
    return a*x**2 + b*x + c
#:~end:def~:

print(y(x))

print('Finished')

but when I change line 7 to
#`\phantom{:~end:def~:}`

the functionality of the tag end:def stops working and the code excerpt displays the rest of the code, but starting at beg:def.

A: First of all you should make sure that the range delimiters span the whole line, otherwise the range detection might not be correct. So if all your range comments look like
#`:~<marker>~:`

you should define
rangeprefix = \#`:~,
rangesuffix = ~:`

For hiding the marker comments in your full code listings, I see two options.
If you want to just hide the marker comment but keep the line in the listing, you could define a new delimiter that renders the comment in white (or the background) color:
moredelim = [is][\color{white}]{\#`:~}{~:`}

If you want to remove the corresponding lines completely, you could define a new, invisible comment type which is ended by the end-of-line character ^^M, thus removing the whole line from the output:
morecomment = [is]{\#`:~}{\^^M}

Note that the latter makes listings literally not see the line, which has consequences on the line numbering.
Full example:
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.py}
import numpy as np

x = np.linspace(0,10,num=100)
#`:~beg:def~:`
def y(x, a=1, b=1, c=1):
    return a*x**2 + b*x + c
#`:~end:def~:`

print(y(x))

print('Finished')
\end{filecontents*}

\lstset{
    language=Python,
    basicstyle=\ttfamily\small,
    aboveskip={1.0\baselineskip},
    belowskip={1.0\baselineskip},
    frame=tblr,
    rulecolor=\color{gray},
    keywordstyle=\color[rgb]{0.627,0.126,0.941},
    commentstyle=\color[rgb]{0.133,0.545,0.133},
    stringstyle=\color[rgb]{01,0,0},
    numbers=left,
    numberstyle=\footnotesize\color{gray},
    captionpos=t,
%    escapeinside={\#`}{`},
}

\begin{document}

\section{Examples}

\subsection{Excerpt of Code}
\lstinputlisting[
    includerangemarker=false,
    rangeprefix=\#`:~,
    rangesuffix=~:`,
    linerange=beg:def-end:def,
]{\jobname.py}

\subsection{Full Code, delimiters hidden}
\lstinputlisting[
    moredelim={[is][\color{white}]{\#`:~}{~:`}}
]{\jobname.py}

\subsection{Full Code, delimiter lines removed}
\lstinputlisting[
    morecomment={[is]{\#`:~}{\^^M}}
]{\jobname.py}

\end{document}

outputs


text:
Q: Is there a way to make this code insert all the current data in the database? What i want is to insert all of the data in all rows and columns from my datagrid view into my database. I am not getting any error but this is not working not inserting any value in my database.
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd = con.CreateCommand();
    for (int i = 0; i < dgEdit.Rows.Count; i++)
    {
       DateTime ds = DateTime.Now;
       cmd.CommandType = CommandType.Text;
       cmd.CommandText = "INSERT INTO Tb BL_Attendance(Course, Subject,
       Year, Section, Name, Room, SeatNo, Status, Date) VALUES('" +
       dgvAtt.Rows[i].Cells[0].Value + "', '" +
       dgvAtt.Rows[i].Cells[1].Value + "', '" +
       dgvAtt.Rows[i].Cells[2].Value + "', '" +
       dgvAtt.Rows[i].Cells[3].Value + "', '" +
       dgvAtt.Rows[i].Cells[4].Value + "', '" +
       dgvAtt.Rows[i].Cells[5].Value + "', '" +
       dgvAtt.Rows[i].Cells[6].Value + "', '" +
       dgvAtt.Rows[i].Cells[7].Value + "', @Date) ";
       cmd.Parameters.AddWithValue("@Date", ds);
       cmd.ExecuteNonQuery();
    }
     MessageBox.Show("Updated! please check the report", "Save",
     MessageBoxButtons.OK, MessageBoxIcon.Information);
     con.Close();

I was expecting this to insert all of my datagrid values into a table

A: The logic below tries to be as close as possible to your implementation, but taking into account best practices when dealing with database connections:
// You will need the following namespaces:
// using System;
// using System.Data;
// using System.Data.SqlClient;
// using System.Windows.Forms;

var connectionString = "Your SQL Server connection string";

using (var con = new SqlConnection(connectionString))
{
    con.Open();

    var cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText =
        "INSERT INTO Tbl_Attendance (Course, Subject, Year, Section, Name, Room, SeatNo, Status, Date) " +
        "VALUES (@Course, @Subject, @Year, @Section, @Name, @Room, @SeatNo, @Status, @Date)";

    var courseParam = cmd.Parameters.Add("@Course", SqlDbType.VarChar, 50);
    var subjectParam = cmd.Parameters.Add("@Subject", SqlDbType.VarChar, 50);
    var yearParam = cmd.Parameters.Add("@Year", SqlDbType.VarChar, 50);
    var sectionParam = cmd.Parameters.Add("@Section", SqlDbType.VarChar, 50);
    var nameParam = cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50);
    var roomParam = cmd.Parameters.Add("@Room", SqlDbType.VarChar, 50);
    var seatNoParam = cmd.Parameters.Add("@SeatNo", SqlDbType.VarChar, 50);
    var statusParam = cmd.Parameters.Add("@Status", SqlDbType.VarChar, 50);

    var dateParam = cmd.Parameters.Add("@Date", SqlDbType.DateTime);
    dateParam.Value = DateTime.Now;

    // If you are going to insert a lot of records, it's advised to call the Prepare method on your SqlCommand.
    // Un-comment the line below if you want to see how this behaves.
    // cmd.Prepare();

    foreach (DataGridViewRow row in dgEdit.Rows)
    {
        courseParam.Value = row.Cells[0].Value;
        subjectParam.Value = row.Cells[1].Value;
        yearParam.Value = row.Cells[2].Value;
        sectionParam.Value = row.Cells[3].Value;
        nameParam.Value = row.Cells[4].Value;
        roomParam.Value = row.Cells[5].Value;
        seatNoParam.Value = row.Cells[6].Value;
        statusParam.Value = row.Cells[7].Value;

        cmd.ExecuteNonQuery();
    }
}

MessageBox.Show("Updated! please check the report", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);

Reason behind the changes:

*

*When possible, instantiate and open your SqlConnection connection inside a
using statement. This will ensure that your connection is always
closed (disposed) when you are done with it in the scope.

*Always use parameters in your queries when interacting with any external input, to avoid Bobby's mom exploit! (https://xkcd.com/327/).
This will ensure that your code is not susceptible to SQL injection.
As you can see, I added some parameters, but because you didn't
provide your table schema I made then VARCHAR(50) with the
exception of the @Date one where it's clear that you are saving a
System.DateTime. Please feel free to change the SqlDbType.VarChar
to the correct type where needed.

*I moved the call to MessageBox.Show outside the using scope so it doesn't interfere with the connection disposal.

Another enhancement that you could do to this logic is implementing the use of the System.Transactions.TransactionScope class (you must add a reference to System.Transactions.dll), to ensure that if there's an error during any of the inserts, nothing gets committed to the database.

A: Your prototype is correct but you did one mistake, dgvAtt.Rows[i].Cells[0].Value return an Object to must convert it to ToString() or the column data in your table that could match with.

Let's say this is my form

I Created a table 'Person'

Code Source

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd = con.CreateCommand();
            for (int i = 0; i < dgvAtt.Rows.Count - 1; i++)
            {
                con.Open();
                cmd.CommandType = CommandType.Text;
                string Query = "INSERT INTO Person (idPerson, fullnamePerson) VALUES (" + dgvAtt.Rows[i].Cells[0].Value.ToString() + ",'" + dgvAtt.Rows[i].Cells[1].Value.ToString() + "')";
                cmd.CommandText = Query;
                cmd.ExecuteNonQuery();
                con.Close();
            }
            MessageBox.Show("Updated! please check the report", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Don't write any Parameters because this will give you an exception.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change offset / margin position based on page scroll location I have three div elements on my webpage. One on the top ( for the menu ), one on the left ( for user information ), and the last on the right ( for user posts ). I have the user information section in a fixed position, which works good, but also when I scroll down the page, it shows the gap at the top of the page where the menu once was. Is there a way to have the top offset / margin change when the menu isn't on the screen? I want to do this without javascript if possible. Every search i did showed only javascript, but I want pure css / html for this case.

A: If you really don't want to use javascript the answer is "No."
There is no way to check the scroll position and change the CSS only with CSS.


text:
Q: Pandas: IF value in dataframe1...THEN decrease value in dataframe2 is anyone familiar with if...conditions in pandas and can help me with a petite question for a beginner?
right now I have this:
tmy_data.loc[tmy_data['elevation of sun'] <= 10, 'DNI'] = 0
But instead of setting the'DNI' to zero when 'elevation of sun' is less then 10, I want it to decrease to 80%
Probably its not that complicated...but I still have no idea  my try just ended in decreasing the whole dataframe instead of the single value

A: If you want to save to the existing column 'DNI'
tmy_data.loc[tmy_data['elevation of sun'] <= 10, 'DNI'] = tmy_data['DNI']*0.8

If you want to save to a new column 'DNI_new'
tmy_data.loc[tmy_data['elevation of sun'] <= 10, 'DNI_new'] = tmy_data['DNI']*0.8


text:
Q: Write byte array to pdf file on click of view I am done with writing the file content to pdf file on click of view, But it's not opening automatically.Can any one help. Thanks in advance.And please correct me if anything wrong here.
@RequestMapping(value = { "/view" }, method = RequestMethod.GET)
        public static byte[] loadFile(@RequestParam("file_path") String file_path,@RequestParam("file_name") String fileName,HttpServletResponse response, HttpServletRequest request,HttpServletResponse resp) throws IOException, DocumentException {

        FileInputStream inputStream = null;
        try {
            String filePath = file_path.replace("/", "\\");
            File file = new File(filePath);
            inputStream = new FileInputStream(file);
            filePath.endsWith(".pdf");
            return readFully(inputStream, filePath, fileName, resp,   request,
                    resp);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

here i am calling the below method and written the code for opening a file automatically.
@ResponseBody
    public static byte[] readFully(FileInputStream inputStream,
            @RequestParam("file_path") String file_path,
            @RequestParam("file_name") String fileName,
            HttpServletResponse response, HttpServletRequest request,
            HttpServletResponse resp) throws IOException, DocumentException {
        byte[] buffer = new byte[8192];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        Document doc = new Document();
        PdfWriter.getInstance(doc, baos);
        doc.open();
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName + ".pdf");
        response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
        response.setContentLength(baos.size());
        ServletOutputStream outn = response.getOutputStream();
        outn.flush();
        baos.writeTo(outn);
        File f = new File("C:\\Users\\Downloads\\" + fileName + ".pdf");
        if (f.exists()) {

            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().open(f);
            } else {
                System.out.println("Awt Desktop is not supported!");
            }

        } else {
            System.out.println("File is not exists!");
        }
        System.out.println("Done");
        return baos.toByteArray();
    }

A: You can write your inputstream into spring fileInputStream.
You can do this just writing input stream in httpservletResponse.
Please change your all code with below method. You can achieve your goal.
@RequestMapping(value = { "/view" }, method = RequestMethod.GET)
@ResponseBody
public void loadFile(@RequestParam("file_path") String file_path,@RequestParam("file_name") String fileName,HttpServletResponse response, HttpServletRequest request,HttpServletResponse resp) throws IOException, DocumentException {

    String filePath = file_path.replace("/", "\\");
    File file = new File(filePath);
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setHeader("Content-Type", "application/pdf");
    response.setHeader("Content-Disposition","attachment;filename="+fileName);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        FileCopyUtils.copy(fileInputStream, httpServletResponse.getOutputStream());
        fileInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


text:
Q: How to fix scss file import error on angular Nativescript app I'm working on a NativeScript app and I'm using scss for styling.
The app was working well but it started showing me an error concerning a certain scss file.
Error message:

here is the folder containing my _colors.scss file:

file _colors.scss file content :

and I'm importing it in the other scss files like this (depending on the directory) :

all the import directories are fine, I don't see why this 'Could not resolve' error keeps showing.
I've tried restarting the app and deleting the (hooks, node_modules and platformes) files and running 'npm install' again.
Let me know if you need more clarifications.


text:
Q: Python string in exception converted to tuple Python 2.7.10 appears to be converting my string into a tuple when thrown in an exception. Here's my example:
class MyError(RuntimeError):
   def __init__(self, arg):
      self.args = arg

def raiseMyError():
    errorCode = 29
    errorText = 'Port not ready yet'
    exitCodeMessage = 'ERROR {0}: {1}'.format(errorCode, errorText)
    # print exitCodeMessage  --> print out here and it's a string
    raise MyError(str(exitCodeMessage))

try:
    raiseMyError()

except MyError as e:
    print e.args

I create a string containing the error code and description and use this to construct a purpose built exception class. When I print out the exitCodeMessage variable before the exception is created I get what I'd expect:
ERROR 29: Port not ready yet

However, the trace from within the exception handler gives me the following:
('E', 'R', 'R', 'O', 'R', ' ', '2', '9', ':', ' ', 'P', 'o', 'r', 't', ' ', 'n', 'o', 't',
' ', 'r', 'e', 'a', 'd', 'y', ' ', 'y', 'e', 't')

Can anyone tell me what's going on here and what I can do about it?

A: Actually you don't need to override the __init__ method at all, it's sufficient enough to:
class MyError(RuntimeError):
   pass

Regarding the behaviour - docs state that args is:

The tuple of arguments given to the exception constructor.

When you inherit from Exception class or any of it's children printing e.args will simply print tuple(e.args), since args property is defined in such way in the Exception class (see @advance512 answer).
When you don't inherit from Exception:
class MyError:

    def __init__(self, arg):
        self.args = arg

you don't inherit the "magic" behind the args, thus calling e.args will work as expected.
You could also write like this (note self.arg instead of self.args):
class MyError(RuntimeError):

   def __init__(self, arg):
      self.arg = arg

and calling e.arg will also work as expected.

A: This is because args is a property that is defined in the BaseException class.
Check out exceptions.py:70:
args = property(lambda self: tuple())
Try this:
class MyError(RuntimeError):
   def __init__(self, errorString):
      self._errorString = errorString

def raiseMyError():
    errorCode = 29
    errorText = 'Port not ready yet'
    exitCodeMessage = 'ERROR %s: %s' % (errorCode, errorText)
    # print exitCodeMessage  --> print out here and it's a string
    raise MyError(exitCodeMessage)

try:
    raiseMyError()

except MyError as e:
    print e._errorString
    print e.args

output:
ERROR 29: Port not ready yet
()


text:
Q: Removing Duplicate object from array in jquery code not working This is my array in jquery , which contains duplicate objects/elements :
[{
    "name": "hello",
    "label": "world"
}, {
    "name": "abc",
    "label": "xyz"
}, {
    "name": "hello",
    "label": "world"
}]

I am using the following piece of code to remove duplicate elements but it not working the duplicate elements are not removed.
var result = [];

$.each(subservices, function (i, e) {
    if ($.inArray(e, result) == -1)
        result.push(e);
});

alert(JSON.stringify(result));

A: Function $.inArray works fine for simple types (e.g. number or string), but for complex types it does not produce the correct result, because it tries to match by reference. Instead of using inArray in your loop you can search the array using function grep:
var subservices = [{
        "name": "hello",
        "label": "world"
    }, {
        "name": "abc",
        "label": "xyz"
    }, {
        "name": "hello",
        "label": "world"
    }
];

var result = [];
$.each(subservices, function (i, e) {
    var matchingItems = $.grep(result, function (item) {
       return item.name === e.name && item.label === e.label;
    });
    if (matchingItems.length === 0){
        result.push(e);
    }
});

//displays result [{"name":"hello","label":"world"},{"name":"abc","label":"xyz"}]
alert(JSON.stringify(result));

Here is a working jsFiddle

A: You need to filter array by unique name/value. Here is some pure JS solution:

var data = [{
    "name": "hello",
    "label": "world"
}, {
    "name": "abc",
    "label": "xyz"
}, {
    "name": "hello",
    "label": "world"
}];

var result = data.filter(function(el, i, x) {
    return x.some(function(obj, j) {
        return obj.name === el.name && (x = j);
    }) && i == x;
});

alert(JSON.stringify(result, null, 4));

A: This is because these two objects are distinct, even though all the attributes inside are the same. You can see this from:
console.log(result[0] === result[2]);

which results in false.
Instead, you need to iterate through your array based on a unique identifier, such as name & label as such:
for(var i = 0, i < results.length; i++) {
    if (result[i].name === ... && result[i].label === ...) {
        index = i;
        break;
    }
}

to check if your item is unique.


text:
Q: Can't connect to mysql using sqlalchemy. Library not loaded error I am trying to run a simple test code to connect ti a mysql db using sql alchemy.
The code is as follows:
from sqlalchemy import (create_engine, Table, Column, Integer, String, MetaData)
import settings
import sys
try:
    db = create_engine('mysql://daniel:dani@localhost/test')
    db.connect()
except:
    print('opps ', sys.exc_info()[1])

I get the following error:
dlopen(//anaconda/lib/python3.5/site-packages/_mysql.cpython-35m-darwin.so, 2): Library not loaded: libssl.1.0.0.dylib
Referenced from: //anaconda/lib/python3.5/site-packages/_mysql.cpython-35m-darwin.so
  Reason: image not found
[Finished in 1.4s]

But running on terminal:
locate libssl.1.0.0.dylib

I get:
/Applications/Dtella.app/Contents/Frameworks/libssl.1.0.0.dylib
/Applications/XAMPP/xamppfiles/lib/libssl.1.0.0.dylib
/Users/dpereira14/anaconda/envs/dato-env/lib/libssl.1.0.0.dylib
/Users/dpereira14/anaconda/lib/libssl.1.0.0.dylib
/Users/dpereira14/anaconda/pkgs/openssl-1.0.1k-1/lib/libssl.1.0.0.dylib
/anaconda/lib/libssl.1.0.0.dylib
/anaconda/pkgs/openssl-1.0.2g-0/lib/libssl.1.0.0.dylib
/opt/local/lib/libssl.1.0.0.dylib
/usr/local/Cellar/openssl/1.0.1j/lib/libssl.1.0.0.dylib

I have no clue how to fix this error.
Thanks!

A: I also had some problems with SQLAlchemy with mysql, i changed localhost in the create_engine to 127.0.0.1:port, and also had to use pymysql. Ended up working with this:
engine = create_engine('mysql+pymysql://user:password@127.0.0.1:port/db')
pymysql is installed via pip.

A: You are using python , so you have add mysqldb with mysql. Try the below code.
try:
    db = create_engine('mysql+mysqldb://daniel:dani@localhost/test')
    db.connect()
except:
    print('opps ', sys.exc_info()[1])


text:
Q: problems populating ListView in Notification I have a Notification.  When its expanded, I want it to display a ListView that I populate with data in real time.
Here's the Notification's expanded view (layout/notification_expanded.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="right|top">

    <ListView
        android:id="@+id/listViewWidget"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Here's the layout of an individual row to append to it (layout/list_row.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@android:color/black" >

    <TextView
        android:id="@+id/heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toRightOf="@id/imageView"
        android:singleLine="true"
        android:text="Heading"/>

    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/heading"
        android:text="Content"/>

</RelativeLayout>

Based on the examples I've seen, I need a RemoteViewFactory to produce RemoteViews that I
then attach to listViewWidget (described in the Notification's expanded view above)
public class ListProvider implements RemoteViewsFactory {
    private Context context;
private ArrayList<String> listItemList = new ArrayList<String>();

    public ListProvider(Context context){
        this.context = context;
        populateListItem();
    }

public RemoteViews getViewAt(int position) {
    final RemoteViews remoteView = new RemoteViews(
            context.getPackageName(), R.layout.list_row);
    ListItem listItem = listItemList.get(position);
    remoteView.setTextViewText(R.id.heading, listItem.heading);
    remoteView.setTextViewText(R.id.content, listItem.content);

    return remoteView;
}

}
and here is the Activity where my problems begin:
        RemoteViews expandedView =
                new RemoteViews(getPackageName(), R.layout.notification_expanded);

        ListProvider lp = new ListProvider(this);

        //notification.bigContentView = expandedView;
        for (int ii = 0; ii< lp.getCount(); ii++) {
            notification.bigContentView = lp.getViewAt(ii);
        }

When the above code runs, I get the last element of my ArrayList displaying in the first element of my ListView.
I understand why - notification.bigContentView is the RemoteView that represents the notification when its expanded
and I'm setting it to the RemoteView created from the last element in the ArrayList holding my data.
How do I change this so I append each element in the ArrayList to notification.bigContentView?  Is it possible to update the ListView with an ArrayAdapter in the typical fashion?


text:
Q: How would I make selections from one listbox show the selected items in a second listbox? I have a listbox (lstbx1) that shows conversion options (Miles to KM, KM to miles, etc). I am pulling these from a text file. I want to show the final conversion in the second listbox (lstbx2). How would I show the selected items's conversions?
I have tried using a foreach method, but it only makes the number of selected items appear, not the selected items themselves.
Here is the main form:
Main form
As you can see, I am wanting to convert 11 Miles to KM, 11 ft to m, and 11 in to cm. I have the calculations written, but I cannot figure out how to show them. Below is my code for my main form, my Conversion(calculation) class, and my database class.
I have thought about making the selections in lstbx1 an array, but I'm not sure how I would do that.
Thanks in advance!
 public partial class frmMain : Form
    {
        // Create blank list conversions
        private List<Conversion> conversions = ConversionsDB.GetConversions();

        public frmMain()
        {
            InitializeComponent();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            // Close application
            System.Windows.Forms.Application.Exit();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            // Load data from file and create a list

            // Load conversion options list
            lstConversionOpts.Items.Clear();
            foreach(Conversion conversion in conversions)
            {
                lstConversionOpts.Items.Add(conversion.GetBasicConversions());
            }
        }

        // Open Manage conversions form
        private void btnManage_Click(object sender, EventArgs e)
        {
            frmManageConvs chManageConvsForm = new frmManageConvs();
            chManageConvsForm.ShowDialog();
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            lstMainConversions.Items.Clear();
            // Check to see if input is valid
            if (IsValid())
            {
                decimal chFinalVal = Convert.ToDecimal(txtOrigValue.Text);

                // Show final conversions
                foreach (var converionType in lstConversionOpts.SelectedItems)
                {
                    lstMainConversions.Items.Add(lstConversionOpts.Items.ToString());
                }

            }

        }

        // Check for valid input
        private bool IsValid()
        {
            bool chValid = true;
            string chError = "";
            chError += Validator.IsNumeric(txtOrigValue.Text, txtOrigValue.ToString());

            if (chError != "")
            {
                chValid = false;
                MessageBox.Show(chError, "Entry Error");
            }
            return chValid;
        }

    }

public class Conversion
    {
        // Construct default conversion method
        public Conversion()
        {

        }

        public Conversion(string from, decimal fromVal, string to, decimal toVal, decimal inVal, decimal finalVal) =>
            (this.From, this.fromValue, this.To, this.toValue, this.inVal, this.finalVal) =
            (from, fromVal, to, toVal, inVal, finalVal);

        // Get/set Conversion data
        public string From { get;  set; }
        public decimal fromValue { get;  set; }
        public string To { get;  set; }
        public decimal toValue { get;  set; }
        public decimal inVal { get; set; }
        public decimal finalVal { get; set; }

        // Display values
        public string GetDisplayText() => From + "|" + To + "|" + toValue;
        public string GetBasicConversions() => From + " to " + To.ToLower();
        public string GetFinalConversions(decimal inVal) => inVal + " " + From + " = " + (inVal * toValue) + " " + To;
    }

public class ConversionsDB
    {
        // Declare where files are stored
        private const string chDir = @"G:\Other computers\My Computer\School\Spring_Semester_2023\CIST2342 - C# II\ProgrammingProject1\CHPP1\CaseyHemphillCalculateConversions";
        private const string chPath = chDir + "Conversions.txt";
        private const string chDefault = chDir + "ConversionsDefault.txt";

        // Create list from files
        public static List<Conversion> GetConversions()
        {

            // Read from file
            using StreamReader chTxtIn =
                new StreamReader
                (
                    new FileStream(chPath, FileMode.OpenOrCreate, FileAccess.Read)
                );

            // Create list from file
            List<Conversion> chConversions = new List<Conversion>();
            while (chTxtIn.Peek() != -1)
            {
                string chRow = chTxtIn.ReadLine();
                String[] chColumns = chRow.Split(' ');
                Conversion chConversion = new Conversion();
                chConversion.From = chColumns[0];
                chConversion.fromValue = Convert.ToDecimal(chColumns[2]);
                chConversion.To = chColumns[1];
                chConversion.toValue = Convert.ToDecimal(chColumns[5]);
                chConversions.Add(chConversion);
            }

            return chConversions;
        }

        // Save list
        public static void SaveConversions(List<Conversion> chConversions)
        {
            using StreamWriter chTxtOut =
                new StreamWriter
                (
                    new FileStream(chPath, FileMode.Create, FileAccess.Write)
                );

            foreach (Conversion chConversion in chConversions)
            {
                chTxtOut.Write(chConversion.fromValue + " ");
                chTxtOut.Write(chConversion.From + " = ");
                chTxtOut.Write(chConversion.toValue + " ");
                chTxtOut.Write(chConversion.To);
            }
        }

        // Create default list from files
        public static List<Conversion> GetDefault()
        {

            // Read from file
            using StreamReader chTxtIn =
                new StreamReader
                (
                    new FileStream(chDefault, FileMode.OpenOrCreate, FileAccess.Read)
                );

            // Create list from file
            List<Conversion> chConversions = new List<Conversion>();
            while (chTxtIn.Peek() != -1)
            {
                string chRow = chTxtIn.ReadLine();
                String[] chColumns = chRow.Split(' ');
                Conversion chConversion = new Conversion();
                chConversion.From = chColumns[0];
                chConversion.fromValue = Convert.ToDecimal(chColumns[2]);
                chConversion.To = chColumns[1];
                chConversion.toValue = Convert.ToDecimal(chColumns[5]);
                chConversions.Add(chConversion);
            }

            return chConversions;
        }
    }```

A: To show the selected item's conversion, you need to get the selected Conversion object from the conversions list that matches the selected item in the lstConversionOpts. You can achieve this by using the Find method of the List class, which takes a predicate function as a parameter that returns true if the item matches the criteria you're looking for.
Once you have the selected Conversion object, you can use its GetFinalConversions method to get the final conversion result, which you can add to the lstMainConversions.
Here's an updated btnConvert_Click method that demonstrates this approach:
    private void btnConvert_Click(object sender, EventArgs e)
    {
    lstMainConversions.Items.Clear();
    // Check to see if input is valid
    if (IsValid())
    {
        decimal chFinalVal = Convert.ToDecimal(txtOrigValue.Text);

        // Show final conversions
        foreach (var selectedItem in lstConversionOpts.SelectedItems)
        {
            // Find the Conversion object that matches the selected item
            var conversion = conversions.Find(c => c.GetBasicConversions() == selectedItem.ToString());

            // If a matching conversion is found, add the final conversion result to lstMainConversions
            if (conversion != null)
            {
                lstMainConversions.Items.Add(conversion.GetFinalConversions(chFinalVal));
            }
        }
    }
}

Also, note that you were previously using lstConversionOpts.Items.ToString() to try to get the selected item's text, which is not correct. To get the selected item's text, you need to use selectedItem.ToString() instead, as shown in the updated code above.


text: Q: Boardman Vogt W construction for modules over an operad The W construction of Boardman and Vogt gives a cofibrant replacement for operads. In http://arxiv.org/abs/math/9907073, Salvatore describes a cofibrant replacement for algebras over an operad. Is there a similar construction which produces cofibrant resolutions of right or left modules over an operad? Does anyone have know of a reference for this?


text:
Q: System specific file access in Python Trying to design a system-specific access control for PDF files. The overall flow of the system will look like this:

*

*A person downloads or receives a PDF and the access code to open it

*Once they use the access code on a computer, it is tied to their MAC/Motherboard/CPU serial so that they can't use the same code on a different system to open the file

I am open to using an online database for managing access codes and system serial mappings but need recommendations on the tools, libraries, and approaches to use to build the product.


text:
Q: How to import the object from React file to plain vanila javascript file I need help to find out the way to import the object from react file to plan the vanilla javascript file. The react js file is the config file which is exporting the multiple URLs from that file, just like below:
let API;
module.exports = {
 API: 'https://localhost/3000/general/'
}

I would like to use this API path in the different plan javascript file.
When I use it using the below code,
    import { API } from "../src/config";
function sendRequest(query) {
        var data = JSON.stringify(query);
        var url = API

        // Send Request.
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                 console.log(xhr.response);
            }
        };
        xhr.open("POST", url, true);
        xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
        xhr.send(data);

    }

It is giving me an error : can not use import statement outside a module
I tried with 'require' as well and it is also giving error :
Uncaught ReferenceError: require is not defined
Any lead would be appreciated!

A: export default {
 API: 'https://localhost/3000/general/'
}

import { API } from "../src/config";

do like this


text:
Q: why is the exit status saved in a variable changing (bash shell)? I have the following executable files:
set_status.sh
    #!/bin/bash
    exit $1
tst_set_status.sh
    #!/bin/bash
1.  echo arg1 = $1
2.  ./set_status.sh $1
3.  stat=$?
4.  echo $?
5.  if [ $stat -eq 0 ]; then
6.    final_stat="ok"
7.  fi
8.  echo $stat
9.  echo `echo $?`

So:
./tst_set_status.sh 1
arg1 = 1
0
1
0

Questions:

*

*Why does $stat have the value 0 and not 1 at line 4?
Is line 4 printing the result of the shell asignment on line 3?

*Which command exit status is the ? variable reporting in line 9?

A:
Why does $stat have the value 1 and not 0 on line 6?

Because tar (or whatever was immediately before line 1) exited with a status of 1. $stat got the value of 1 on line 1, and didn't change afterwards.
The question you didn't ask is "why does echo $? print 0 on line 2?" And that's because the assignment on line 1 was a success, and so $? was reset to 0 before line 2.

Which command exit status is the ? variable reporting in line 7

The exit status of the echo on line 6.


text:
Q: How can I find the file that a particular line of code existed within in my commit history? There is a line of code that I wish to recover from a previous commit as it turns out that this line of code was very important and useful.
For example, let's say that this is my line of code:
df[df$type == "creator", ]

The problem is that I can't remember the file that this code was saved in, nor can I recall where/when it was committed.
I use SourceTree and have tried the Search option, but it only gives me the option to search Commit Message, File Changes and Authors.
I use the File Changes search option but the results show me previous commits whereas I would like to see a list of files that contained the line of code at some point in time.
Aside from manually looking through each version of each file in each commit, I'm not sure how to approach it.
How can I do this?
Note that I am also open to suggestions/solutions using the terminal also.
Update:
The line of code can be in either one of three files and I know roughly the time it was committed (about two weeks ago).

A: Try git log, for example:
git log --name-only -S"<text-you-search-for-goes-here>"

It will print all commits in which any file contained the searched text at any point in time and for each commit it displays:

*

*commit hash

*author

*date of the commit

*commit message

*names of files in which the searched text appeared (thanks to --name-only)


text:
Q: What is a good number of partitions in spark as a function of number of executors and threads? I'm using Spark on EMR. I launch a cluster and sometimes the cluster is small (when writing/testing out code), say 5-10 instances. Other times executing the same code using a larger number of instances say 30-50.
I know I can access the configurations to assist in setting the number of partitions and choosing a good number of partitions helps the runtime.
I'd like to parameterize the number of partitions as a function of the number of executors and the number of threads:
val instanceCount = sc.getConf.get("spark.executor.instances").toDouble
val coreCount = sc.getConf.get("spark.executor.cores").toDouble

Has anyone looked into this and can give any advice on a good way to parametrize the number of partitions?
I realize there will not be one good answer but some functional form, with constants would help. For example:
val partitionCount = instanceCount*coreCount*0.7

appears to work good in my use cases and describe your use cases (number/range of executors) that would be helpful.
In the answer if you could indicate the range of instances your working over that would be helpful too. If there is a canonical investigation of this somewhere a pointer to that would be helpful.

A: There is no single optimal configuration for all use-cases, but I will give you all the heuristics I have gathered along my experience with Spark.
More partitions than cores
First, let's state the obvious. You need to have more partitions (= tasks in a given stage) than you have cores, otherwise some cores will be sitting around doing nothing. Are there exceptions to this rule of thumb? Yes:

*

*you could also be running multiple jobs in parallel. Say you have 1000 small datasets and you need to apply some transformations to each of them independently of the others. You probably do not want to partition each dataset in 128k files, however you could be running multiple jobs of 128 partitions in parallel to max out your number of cores. Note that I only know how to do that within a single step or on a custom-managed YARN cluster by setting spark.scheduler.mode=FAIR. I've never tried to submit parallel EMR steps and I don't know if it's possible, it's not a regular YARN concept (but again, you can do it within the same step if you wish).

*your tasks are themselves parallelized. It's absolutely not a regular use-case and I don't recommend in general, but I have had to parallelize some MXNet classification code on Spark. The Java code creates a Python process that uses MXNet to predict and then returns the result to Java. Since MXNet is internally parallel and pretty good at using the cores, I've found throughput to be a lot higher by having as many machines as possible (so taking the smallest possible instances) and only two executors (containers) per machine. Each executor was creating a single MXNet process for serving 4 Spark tasks (partitions), and that was enough to max out my CPU usage. Without restricting the number of MXNet processes, the CPU was constantly pegged at 100% and wasting huge amounts of time in context switching.

Good amount of data per partition
Small partitions lead to slower jobs because there's a certain amount of communication between the driver and the slaves, and it does amount to a lot of time if you have 100 000 small tasks. If your tasks complete under 1 second your partitions are definitely too small.
Conversely, big partitions are memory hazards, especially during shuffles. Shuffles are very demanding on memory and will have you do a lot of garbage collection. If your partitions are too big, you will increase the risk of running out of memory or at best spending 50%+ of your time in GC. 2GB in serialized form is the absolute limit for a partition's size because Spark uses a Java IO utility that is backed by a byte array, which can only hold 2^31 - 1 (size of an int) elements.
Generally, I recommend around 25MB-70MB in gzipped form if you're doing shuffles (mainly talking about JSON and textual data here).
Broadcasts
If you need to broadcast some objects to all your executors (for example, a Bloom filter for reducing the size of a dataset before shuffling it), the number of containers you want will be dictated by the amount of memory you are willing to use on each machine to hold your broadcasts. Indeed, the object will be broadcasted once per executor, so the amount of broadcasted data per machine is object_size * num_executors / num_ec2_instances assuming a homogeneous cluster. Network cost also increases with the number of containers since the object needs to be broadcasted multiple times to each EC2 instance.
However, I've had the case where my broadcasted object was a logistic model that was using some internal mutable state during classification. This meant that the predict method was synchronized and that all the threads in my container were fighting to access this lock. By increasing the number of containers (and thus the memory and network cost of my broadcast), I made the job 4 times faster.
Summary
The number of partitions is rather dictated by the size of the data than by the number of cores available. If your data doesn't require more than 200 partitions, then just do not take a cluster larger than 200 cores, you will probably not get any meaningful speed up from increasing the number of partitions and cores if the partitions are already reasonably well sized.
As long as your data is well-sized and your partitions balanced, the only remaining heuristics are:

*

*use at least as many cores as partitions

*run multiple jobs in parallel (if you can and) if you want to increase your throughput but your partitions are already well-sized

*avoid running multi-threaded code within your tasks, but in the rare cases for which you need it, consider having fewer partitions than cores contrarily to what we said before.

*the more containers you have, the more expensive broadcasting becomes (more network activity during the broadcast, and more memory usage until its destruction). If your broadcasted object is fully immutable, try having as little containers as possible. If your container has some internal state and requires locking, having too many threads per container might increase contention and slow you down.


text:
Q: How do I disable uninstall button with accessability service in android? I am making a kids app locker and im currently working on the NoRemoval class. It should disable the uninstall button. Bbut I am not receiving any actions whie debugging. Could not figure out why.
And secondly how can I find / disable the uninstall button. I already disabled the clear app data button with this
android:manageSpaceActivity="com.sec.SpaceManage"

but I cant figure out how to disable grey out uninstall button.
package com.sec;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.provider.Settings;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
public class NoRemoval extends AccessibilityService {
    private static final String TAG = NoRemoval.class.getSimpleName();

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        Log.i(TAG, "EventType: " + event.getEventType());
    }

    @Override
    public void onServiceConnected() {
        Log.i(TAG, "Service Connected");
    }

    @Override
    public void onInterrupt() {
        // TODO Auto-generated method stub

    }
}

<service android:name=".NoRemoval"
                android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
                android:label="Enable this">
                <intent-filter>
                    <action android:name="android.accessibilityservice.AccessibilityService" />
                </intent-filter>
                <meta-data
                    android:name="android.accessibilityservice"
                    android:resource="@xml/description" />
            </service>

Part of manifest.
Now comes "@xml/description":
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/accessibility_service_description"
    android:packageNames="com.sec"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFlags="flagRequestTouchExplorationMode"
    android:accessibilityFeedbackType="feedbackAllMask"
    android:notificationTimeout="1"
    android:canRetrieveWindowContent="true"
    android:settingsActivity="com.sec.ServiceSettingsActivity"
    />


text:
Q: Retrieve mongodb documents with int as _id I imported some wikipedia documents into mongodb with int type "_id" field (they are the pageids for wikipedia page):
> db.wiki_page_id.find()
{ "_id" : 10, "page_title" : "AccessibleComputing" }
{ "_id" : 12, "page_title" : "Anarchism" }

I am using Mongo engine together with Django, and I am having trouble retrieving the documents I imported. When I use the following code:
page_id_doc = WikiPageId.objects(id=10)[0]

it reports this error:

u'10' is not a valid ObjectId, it must be a 12-byte input of type 'str' or a 24-character hex string

When I use the bson.objectid.ObjectId class as this:
page_id_doc = WikiPageId.objects(id=ObjectId(10))[0]

It reports the following error:

id must be an instance of (str, unicode, ObjectId), not

Is there any way to work around this?
Thanks!

A: With MongoEngine, you can define a field in your document as the "primary key" ( "_id" field by using primary_key in the keyword arguments to the field:
class MyClass(Document):
    id = IntField(primary_key=True)

But of course you need to make sure that "type" is used everywhere in your collection otherwise the type checking will fail for any "_id" that is not an int().


text:
Q: RippleDrawable NOT drawing over Views I have a layout with a KenBurnsView and an ImageView over it (just a toggle button). When I click on the button a Ripple is generated but is drawn below the KenBurnsView.
Previously, when I had an Image view in replacement to the KenBurnsView the Ripple was drawn above the ImageView on the top.
Here is my layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    android:clickable="true"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="@dimen/nav_drawer_header_height">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <com.flaviofaria.kenburnsview.KenBurnsView
                android:id="@+id/header_cover"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/cover_1" />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:id="@+id/header_toggle"
                    android:layout_width="50dp"
                    android:layout_height="30dp"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentRight="true"
                    android:layout_marginBottom="10dp"
                    android:layout_marginRight="10dp"
                    android:padding="10dp"
                    android:src="@drawable/toggle_down" />

            </RelativeLayout>

        </FrameLayout>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/nav_toggle_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></RelativeLayout>

</LinearLayout>

This is my ripple drawable XML:
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@android:color/white"
    android:drawSelectorOnTop="true"> <!-- ripple color -->

</ripple>

This is how I am adding the ripple:
toggle.setBackground(getResources().getDrawable(R.drawable.ripple));

What is the problem because of which the Ripple gets drwan below the KenBurnsView? It used to work perfectly when there was an ImageView in place of the KenBurnsView?

A: Unbounded ripples are projected on to the first available background of an ancestor view. Trace up the view hierarchy from the ImageView that's hosting the ripple and you will find that the first available background is on the LinearLayout with identifier drawer.
If you set a transparent background on the RelativeLayout containing your ImageView, the first available background will be one that's rendered above the sibling view and you will get the desired effect.
Side note, that RelativeLayout should be replaced with a FrameLayout, which will provide the same effect with a less expensive layout pass.

A: as you can see from your own code ('setBackground') , you're setting the ripple as a BACKGROUND that's why it's being drawn on the background.
ImageView on android API 21 added this "hack" for the ripple android:drawSelectorOnTop="true". But the library you're using didn't add the same hack to it.
There's nothing wrong itself on your code. But this type of behavior cannot be guaranteed by the Android team for 3rd party libraries.
You have a few of options here that will vary on cleanliness, effort and performance:

*

*check ImageView source code, clone the library, add the same hack that imageview used on it for the ripple. After it's working fine, make sure to pull request back to the library.

*wrap your KenBurnsView with a FrameLayout and set the ripple using setForeground on the FrameLayout.

*clone the library, add option to foreground drawable to it (similar to this How to set foreground attribute to other non FrameLayout view). Also make sure to pull request this valueable code back to the library.


text:
Q: jQuery selector not working on Windows Phone 7 I have a strange problem with a web app for WP7 (7.1).
The code that works with Chrome, Safari, etc.:
$.each(val, function(sub_key, sub_val) {

                $("."+sub_key).html(sub_val);

});

Examples for the variables in use:
sub_key : title-home
sub_val : This is home

This does not work on WP7 (v. 7.1). I tried endless combinations but the only way to get the selector working is to define a static string inside the selector. Like so:
$.each(val, function(sub_key, sub_val) {

                $(".title-home").html(sub_val);

});

This is of course not an option.
Is there some kind of bug in IE when joining strings like I did?
BTW I think WP7 is using the IE 7 engine.
Cheers Johe

A: --edit:
If you have problems with on-page javascripts not running at all: make sure to check my findings on the subject that I've posted at http://social.msdn.microsoft.com/Forums/en-AU/jscript/thread/bac9f056-e0de-449e-a1b6-36e745fa59c6 - maybe your problems are related to some unlucky timings or property-setter ordering. it turns out that if you hardcode the URL in XAML, then you must ensure that in that XAML the IsScriptEnabled is set BEFORE the SOURCE property, or else you will have lots of failures depedent on what doctype your pages have. the same applies to setting the Source or Navigate'ing in the code, but that's quite obvious there. on the other hand, at first glance, bindings seem to work properly either way.
--/edit
It may be not very helpful for you, but I'll post it anyways, as it may help many other people with WP7 and jQuery:
Please, ensure that you are using the newest JQ that is marked by its team as ok-with-wp7. I recently was interoperating with a website, where the pulisher constantly mixed up different versions of the JQ. From my humble experiments, only the current jQuery 1.6.2 was working properly inside WebBrowser control, also the jQueryMobile was doing well. Versions 1.4.x and 1.5.x that was commonly used on that site I worked with - completely failed to parse somewhere at the jQ.js core script, saying shortly - jQuery and $ symbols were 'undefined' after the page loaded. BTW. If I recall correctly, that was on 7.0 (from MS: "something between IE7 and IE8") and  on the 7.1 (overheard somewhere: "something between IE8 and IE9") the compatibility is a bit better, but not perfect.. If you can, try jQmobile first.
About the failed js code -- you have to be extra-uber-careful when scanning the page. You say about WP7.1 app - so I assume you are working inside WebBrowser control. If so - then cut your JS script off the page, copy it down as a string somewhere in you app, and then, on the WebBrowser.NavigationCompleted - try to execute that script manually through WebBroweser.InvokeScript. If there's whatever actual error - you will get an exception, most probably "ComException 0x80020101. You know.. the WebBrowser is strange on that thing, it's its beloved error code returned for so many different causes.. anyways:
If that error occurs, the JS is instantly aborted, and your code will get an except that you will be able to catch. Inside that except object you will get ... no information at all. Pity. But with some tricks, you can play minesweeper with the JS code and cut it down to the minimal examples that either work properly or crash - and maybe you will deduce what's up.
Some errors, for example:
- trying to use a name that is unknown, may return "undefined" but also, may crash, especially at global scope
- trying to accidentially stringify window, window.external, and other natives, may somtimes cause crash
- trying to touch the BODY of the document, before it loads completely, may cause crash
- ...
and so on. Please note, that the "before the page loads" is just my guess. I assume you try to play with your page AFTER you have received the 'webbrowser.navigated' event, as it is the first sane point to do so, as the Browser notifies you the page has been loaded. Yet, still, even with that, you can still get that error, and it's may just be all about unfotunate timing. If you retry to invoke exactly the same code just a bit later, you may succeed without any exceptions.
Forgive me, but I'll repeat: most of the times, if anything bad occurs, you will get a "Name not found/COM0x80020101" error, that will cause the JS code or file to silently abort and be skipped. It usually does not mean what the exception name stands for. Thats just an generic-fault in the JS. Occasionally you will get a few other exceptions, but thats 95%-to-5%. Btw. other exceptions usually also have quite unmeaningful data inside them.
Now, I mentioned some tricks.
The WebBrowser.InvokeScript is erm.. let's say, unfriendly to use.
It is designed only to invoke global functions registered by the javascript. The InvokeScript has 2 overloads: (string name) and (string name, object[] params). The important thing to know is, that the first parameter is the NAME of the function. It must be a name. It cannot be an arbitrary JS code, the InvokeScript looks for functions by name, and if it finds none, a .. 0x80020101 is thrown :) Arguments/strings - you may pass whatever.
I'm writing all of this to aid you with eventual manual debugging/minesweeping the JS code. If you set a breakpoint inside the WebBrowser.NavigationCompleted event handler, or wherever called afterwards, you may play with the JS quite interactively from within the debugger's watch window, with the mighty trick of a single, guaranteed-to-exist, js-core function: the eval
Although InvokeScript can invoke only a function, picked by name, with "eval" function, you may execute completely arbitrary code. I've (not once) injected/eval'ed whole JQuery1.6.2 library into the page, just to check whether it works or to fiddle with the contents on the page - because the page linked to ie. JQ1.4 that was broken on WP7.
Be warned though, even if foth of the InvokeScript overloads claim to return an "object", do not be fooled by that. At least when playing with eval, they are unable to do so. The only thing they are able to return is a pure string. Whatever else you will try to return, it will be returned as an "", an empty string. I've checked on 7.0, 7.1 and 7.5. The object[]params is dubious too. I've managed to pass strings only.
examples to type into the Watch window (assuming 'wb' is the WebBrowser control)
wb.InvokeScript("eval", " 'mom' "); // returns string, 'mom'
wb.InvokeScript("eval", " window "); // returns empty string
wb.InvokeScript("eval", " ' '+window "); // returns [object Object] -- note the ' '+ -- to stringify it before returning

wb.InvokeScript("window"); // 0x80020101
wb.InvokeScript(" 5+5 "); // 0x80020101 :)
wb.InvokeScript(" 'mom' "); // 0x80020101 :))
wb.InvokeScript("myfunction"); // 0x80020101 or calls your function from JS
wb.InvokeScript("function blah(){return 5+5}; ' '+blah() "); // 0x80020101

wb.InvokeScript("eval", " '5'+'5' "); // returns '55' - only with eval you may exec custom code
wb.InvokeScript("eval", "function blah(){return 5+5}; ' '+blah() "); // you can even define functions - returns 10
wb.InvokeScript("eval", " ' ' + blah() "); // what's more, whatever you do, it's permanent, functions is still there, returns 10

// JQ works too:
wb.InvokeScript("eval", " ' ' + $ "); // if you see" undefined", the JQ failed to load
wb.InvokeScript("eval", " ' ' + jQuery "); // the same as above
wb.InvokeScript("eval", myVariable_withCached_JQueryCoreCode); // works! (at least on 7.1 and JQ162)
wb.InvokeScript("eval", " ' ' + jQuery "); // jq dump, if it was loaded properly
wb.InvokeScript("eval", " ' ' + $ "); // the same
wb.InvokeScript("eval", " ' ' + $(document.body)[0] ");

the last line in my case, sometimes threw, and sometimes did not. If it threw, I usually was able to re-call it once again successfully for example, 250ms later, set with a timer _in_the_app_code_, but was unable to do the same in a setTimeout! When I was trying to perform a similar delay-call from within the JS, it sometimes worked, but sometimes even crashed the whole application.. I bet that the exception was 80020101, but I've just became mad about that after spending 5+ hours on tracing that thing.. Funnily, but if the same line referred to document.head instead of document.body - no exceptions thrown, ever.
I think I've again written a bit too much, sorry about that :)

A: quetzalcoatl, two things:

*

*How do you know that a JQuery version is OK to Windows Phone? I've not seen anything official about this.

*How about the debugger thing? If I set a breakpoint at Navigated's handler, the page I wish to display doesn't load correctly and I cannot use the Watch successfully.


text:
Q: How to get data out of a recordset in excel? I have the following code:
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim AppPath As String
Set cn = CreateObject("ADODB.Connection")
AppPath = Application.ActiveWorkbook.Path

Set rs = CreateObject("ADODB.RecordSet")

strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=" & AppPath & "\Masterlist_Current_copy.accdb;"

strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];"
cn.Open strConnection
Set rs = cn.Execute(strSql)

'Need Code here to get Info out of recordset

I am trying to get information out of the recordset that has the query result being dumped into it. I'm trying to figure out how to query the recordset and get the number of rows with a specific value in the "Neptune Number" field. I will then insert the correct number of rows into the worksheet I'm modifying. After that I need to get the data for that value and insert it into the worksheet.
Note: I don't care if recordset, datatable or anything else is used I simply need to be able to do what I described above. Please show code.

A: The easiest way to get where you I think you are asking to go is to modify your SQL statement changing
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];"

to
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components] WHERE [Neptune Number] = 'Specific Value' ;"

This will force the sql query to only return the records you need. the .find method can be used for filtering the recordset, but i have avoided using it in this instance as it is cleaner to just ask the db for only the information that you want.
to process the recordset you can use the following
with rs
    'will skip further processing if no records returned
    if not (.bof and .eof) then
        'assuming you do not need the headers
        'loop through the recordset
        do while not .eof
            for i = 0 to .fields.count -1
                'assuming the active sheet is where you want the data
                cells(row, i + colOffset) = .fields(i).value
            next
            Rows(Row & ":" & Row).Insert
            .movenext
        loop
    end if
end with

Where row is the starting point of your data and colOffset is the starting column of your data. Note that this code does not do things in the exact order you specified in your question (I am inserting rows as needed instead of calcualting the number of records up front.)
I have avoided using .recordcount because I find depending on the database used it will not return a correct record count.


text:
Q: Saving pictures in specified folder in Android This is my first post here at Stackoverflow and I have my fingers crossed that you may be able to help me.
I've recently started learning Android and have decided a simple app which takes a photo and then shows the photo to the user within the app would be a good place to start.
However, after following the guide over at the Android Developer site (http://developer.android.com/training/camera/photobasics.html) I just can't seem to get the image to display.
I receive the error:

Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/Pictures/JPEG_20160101_163802_1697759335.jpg: open failed: ENOENT (No such file or directory)

I can see that the photo has been saved in the default camera folder, not the path I had specified (as copied/pasted from the developer tutorial).
I would be hugely grateful if anyone could help me figure out how to either save the photo in the specified file, or to get the saved location back from the camera app.
    package uk.co.c2digital.futurefoto;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * The following code is based on the following article: http://developer.android.com/training/camera/photobasics.html
 */

public class MainActivity extends AppCompatActivity {

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

        Log.v("MainActivity", "App Started");
    }

    /**
     * This block of code launches the default camera application
     */

    static final int REQUEST_TAKE_PHOTO = 1;

    public void dispatchTakePictureIntent(View view) {

        Log.v("MainActivity", "dispatchTakePictureIntent() function started");

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

            // Out success result to log
            Log.v("MainActivity", "Camera app found");

            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
                Log.v("MainActivity","Image will be saved to: " + photoFile);
            } catch (IOException ex) {
                // Error occurred while creating the File
                Toast.makeText(this, "Unable to save image", Toast.LENGTH_SHORT).show();
                Log.v("MainActivity", "Error while attempting to run createImageFile()");
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Log.v("MainActivity","File created");
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);

            }
        } else {
            Toast.makeText(this, "Unable to launch camera app", Toast.LENGTH_SHORT).show();
            Log.v("MainActivity","Unable to find camera app");
        }
    }

    /**
     * End of camera launch code
     */

    /**
     * This block of code creates a unique file name for captured photos to prevent naming collisions
     */

    String mCurrentPhotoPath;

    public File createImageFile() throws IOException {

        Log.v("MainActivity","createImageFile() functions started");

        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();

        return image;
    }

    /**
     * End of unique file name code
     */

    /**
     * This block of code decodes and scales the photo and displays in photoView
     */

    public void setPic() {

        Log.v("MainActivity","setPic() function started");

        ImageView mImageView = (ImageView) findViewById(R.id.imageViewer);

        // Get the dimensions of the View
        int targetW = mImageView.getWidth();
        int targetH = mImageView.getHeight();

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        mImageView.setImageBitmap(bitmap);
    }

    /**
     * End of photo scaling code
     */

    /**
     * THis block of code allows the created photo to be made available to the photo gallery
     */

    private void galleryAddPic() {

        Log.v("MainActivity", "galleryAddPic() function started");

        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

    /**
     * End of gallery code
     */

    /**
     * This block of code handles the responce from the cameras intent
     */

    public void onActivityResult(int RequestCode, int ResultCode, Intent data) {

        Log.v("MainActivity","onActivityResult() function started");

        if (RequestCode == REQUEST_TAKE_PHOTO) {

            Log.v("MainActivity","RequestCode matched REQUEST_TAKE_PHOTO");

            if (ResultCode == RESULT_OK) {

                Log.v("MainActivity","ResultCode was OK");

                 // galleryAddPic();
                  setPic();

            } else {

                Log.v("MainActivity","ResultCode was not OK");
                Log.v("MainActivity","ResultCode was: " + ResultCode);
            }

        } else {

            Log.v("MainActivity","RequestCode did not equal REQUEST_TAKE_PHOTO");
            Log.v("MainActivity","Request Code was: " + RequestCode);
        }

    }
}

A: This is the approach I use:
Uri newPhotoUri;
public void takePhoto() {
    // create Intent to take a picture and return control to the calling application
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    newPhotoUri = Uri.fromFile(new File(filename)); // create a file to save the image
    intent.putExtra(MediaStore.EXTRA_OUTPUT, newPhotoUri); // set the image file name

    // start the image capture Intent
    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}

and then:
/**
 * Called when returning from the camera request.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        Log.d(TAG, "Received camera activity result");
        if (resultCode == RESULT_OK) {
            String resultPath = "";
            if (data == null) {
                if (this.newPhotoUri != null) {
                    Log.d(TAG, "Intent data is null, trying with uri " + this.newPhotoUri.getPath());
                    resultPath = this.newPhotoUri.getPath();
                } else {
                    Log.d(TAG, "Intent data and photo Uri are null, exiting");
                    return;
                }
            } else {
                // Image captured and saved to fileUri specified in the Intent
                Log.d(TAG, "Image saved to: " + data.getData());
                resultPath = data.getData().toString();
            }
            // process resultPath
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
            Log.d(TAG, "User cancelled");
        } else {
            // Image capture failed
        }
    }
}

With some devices, the media store location is not guaranteed to be used, so this is more of a practical approach.


text:
Q: The sum of Opening and Closing Balances for each Financial Year Grouped by Category in MYSQL I have used three days attempting how to figure out this with no avail.I also did some search even from this forum but failed  too.
It might look like Duplicate Question but to be honest this is different from others has been asked.
My question is how to get the sum of  Balance Carry forward C/F and Closing balance  for each financial year being GROUPED BY loan_id For each Date Range ie.Financial year?

transaction_t
Na    loan_id     date       credit_amount     debit_amount
1      1        2017-01-01     5,000            4,000
2      1        2017-05-01     6,000            2,000
3      2        2017-10-01     1,000            1,500
4      1        2018-10-30     2,000            400
5      2        2018-11-01     12,00            1,000
6      2        2019-01-15      1,800            500
7      1        2019-05-21     100               200

The above table schema and its data have mysql fiddle  here I have also read this thread MySQL Open Balance Credit Debit Balance  which is only working for single user.
So far I have tried:
SELECT loan_id,

 SUM(credit)-(SELECT SUM(a.debit) FROM transaction_t a
   WHERE a.transaction_date
   BETWEEN '2019-01-01' AND '2020-12-31' AND a.loan_id = loan_id) AS OpeningBalance,

sum(credit),sum(debit),
(@OpeningBalance+SUM(credit))-SUM(debit) AS closing_balance
FROM transaction_t tr
WHERE transaction_date BETWEEN DATE('2019-01-01') AND DATE('2020-12-31')
GROUP BY loan_id

But the above is not giving correct results ,How do i get the results like these ones?
A: Query made for date between 2017-01-01 and 2018-12-31
loan_id     opening_balance       sum(credit_amount)     sum(debit_amount)   closing_balance
1           0                     13,000.00                6,400.00           6,600.00
2           0                     2,200.00                 2,500.00          -300

B: Query made for date between 2019-01-01 and 2020-12-31
loan_id     opening_balance       sum(credit_amount)     sum(debit_amount)   closing_balance
1           6,600                     100.00               200.00            6,500.00
2           -300                      1,800.00             500.00            1,000

A: You are looking for conditional aggregation.
The key thing is that you need to start scanning the table from the beginning of the history in order to generate the initial balance. Then you just need to adjust the conditional sums:
Consider:
SET @start_date = '2017-01-01';
SET @end_date = '2018-12-31';

SELECT
    loan_id,
    SUM(CASE WHEN transaction_date < @start_date THEN credit - debit ELSE 0 END) opening_balance,
    SUM(CASE WHEN transaction_date BETWEEN @start_date AND @end_date THEN credit ELSE 0 END) sum_credit,
    SUM(CASE WHEN transaction_date BETWEEN @start_date AND @end_date THEN debit ELSE 0 END) sum_debit,
    SUM(CASE WHEN transaction_date <= @end_date THEN credit - debit ELSE 0 END) closing_balance
FROM transaction_t
WHERE transaction_date <= @end_date
GROUP BY loan_id

In your DB Fiddle, this returns:
loan_id opening_balance sum_credit  sum_debit   closing_balance
1       0               13000       6400        6600
2       0               2200        2500        -300

And when changing the dates to 2020-2021:
loan_id opening_balance sum_credit  sum_debit   closing_balance
1       6600            100         200         6500
2       -300            1800        500         1000

NB: that was a well-asked question, that SO could use more of!


text:
Q: Application insights | Sometimes End-to-end transaction details do not show all telemetry I have .Net core App deployed on azure and enabled application insights.
Sometimes Azure application insights End-to-end transaction details do not display all telemetry.
Here it only logs the error and not request or maybe request logged but both do not display together over here(difficult to find out due to many people use it)

Should be like:

Sometimes request log but with no error log.
What could be the reason for happening this? do I need to look into application insights specific set-up/feature?
Edit:
As suggested by people here, try to disable the Sampling feature but still not works, Here is open question as well.

A: This usually happens due to sampling. By default, adaptive sampling is enabled in the ApplicationInsights.config which basically means that only a certain percentage of each telemetry item type (Event, Request, Dependency, Exception, etc.) is sent to Application insights. In your example probably one part of the end to end transaction got sent to the server, another part got sampled out. If you want, you can turn off sampling for specific types, or completely remove the

AdaptiveSamplingTelemetryProcessor

from the config which completely disables sampling. Bear in mind that this leads to higher ingestion traffic and higher costs.
You can also configure sampling in the code itself, if you prefer.
Please find here a good overview of how sampling works and can be configured.

A: This may be related to :

*

*When using SDK 2.x, you have to track all events and send the telemetries to Application insights

*When using auto-instrumentation with 3.x agent, in this case the agent collect automatically the traffic, logs ... and you have to pay attention to the sampling file applicationinsights.json where you can filter the events.

*If you are using java, below the accepted Logging libraries :
-java.util.logging
-Log4j, which includes MDC properties
-SLF4J/Logback, which includes MDC properties


text:
Q: How to get the datatype of column from the sharepoint list?
*

*I want to get or retrieve the datatype of a particular column where
the list is created in a sharepoint list.
Can you help me for doing the task?

A: See SPField.Type (or SPField.TypeDisplayName).
SPList list = web.Lists["my list"];
SPField field = list.Fields["particular"];
SPFieldType fieldType = field.Type;
string fieldTypeName = field.TypeDisplayName;

A: Building off of Rich Bennema's answer (referencing the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.RunTime version 16 libriaries and using the Microsoft.SharePoint.Client name space):
using (ClientContext cont = new ClientContext(SharePointUrl))
{
    cont.Credentials = new SharePointOnlineCredentials(Username, SecurePassword);

    FieldCollection fields = cont.Web.Lists.GetByTitle(SharePointListName).Fields;
    cont.Load(fields);
    cont.ExecuteQuery();

    var results =
            fields.Select(
                f => new
                {
                    f.InternalName,
                    f.TypeDisplayName,
                    TextMaxLength = (f is FieldText) ? ((FieldText)f).MaxLength : 0,
                    FieldChoices = (f is FieldChoice) ? ((FieldChoice)f).Choices : new string[0]
                }
            );
}


text:
Q: Can we apply the component test for the given field?
Consider the following vector field $\mathbf F$, where
$$\mathbf F=x^3\sin\left(\frac1x\right)\mathbf{i}+(2x+e^y)\mathbf{j}+\left(\frac{x^2-y^2}{x^2+y^2}\right)\mathbf{k}$$
defined on its domain. Can you apply the Component Test for Conservative Fields to check whether the vector field is conservative or not. If yes, then use it to check whether $\mathbf F$ is conservative or not. If not, explain.

I understand that to apply the component test for any field, the domain must be simply connected. But for such a field, how can we determine whether the domain is simply connected or not?

A: Well, first of all, you should say what the domain actually is. I assume it's all the purely imaginary quaternions $x \,\boldsymbol i + y \,\boldsymbol j+ z \,\boldsymbol k$ for which the formula is defined. That would be $Im\mathbb H$ minus the plane spanned by $\boldsymbol j$ and $\boldsymbol k$, which is homeomorphic to $\mathbb R^3$ minus the $(y,z)$-plane, which is homotopy equivalent to the $x$-axis minus the origin by projecting, which has two simply connected components. That should be enough for your component test.

A: The maximal domain of the given vector field is $ D= \mathbb R^3\setminus \{(x,y,z):x=0\}$. This is not simply connected, since a closed curve around the $x$-axis can not be contracted to a point. However, if you restrict the domain to a simply connected set, e.g., the half space $D_+ = \{(x,y,z):x>0\} $, then you can apply the component test.


text:
Q: dplyr: How to apply do() on result of group_by? I'd like to use dplyr to group a table by one column, then apply a function to the set of values in the second column of each group.
For instance, in the code example below, I'd like to return all of the 2-item combinations of foods eaten by each person. I cannot figure out how to properly supply the function with the proper column (foods) in the do() function.
library(dplyr)

person = c( 'Grace', 'Grace', 'Grace', 'Rob', 'Rob', 'Rob' )
foods   = c( 'apple', 'banana', 'cucumber', 'spaghetti', 'cucumber', 'banana' )
eaten  = data.frame(person, foods)

by_person = group_by(eaten, person)

# How to do this?
do( by_person, combn( x = foods, m = 2 ) )

Note that the example code in ?do fails on my machine
mods <- do(carriers, failwith(NULL, lm), formula = ArrDelay ~ date)

A: Let us define eaten like this:
eaten <- data.frame(person, foods, stringsAsFactors = FALSE)

1) Then try this:
eaten %.% group_by(person) %.% do(function(x) combn(x$foods, m = 2))

giving:
[[1]]
     [,1]     [,2]       [,3]
[1,] "apple"  "apple"    "banana"
[2,] "banana" "cucumber" "cucumber"

[[2]]
     [,1]        [,2]        [,3]
[1,] "spaghetti" "spaghetti" "cucumber"
[2,] "cucumber"  "banana"    "banana"

2) To be able to do something near to what @Hadley describes in the comments without waiting for a future version of dplyr try this where do2 is found here:
library(gsubfn)
eaten %.% group_by(person) %.% fn$do2(~ combn(.$foods, m = 2))

giving:
$Grace
     [,1]     [,2]       [,3]
[1,] "apple"  "apple"    "banana"
[2,] "banana" "cucumber" "cucumber"

$Rob
     [,1]        [,2]        [,3]
[1,] "spaghetti" "spaghetti" "cucumber"
[2,] "cucumber"  "banana"    "banana"

Note: The last line of the question giving the code in the help file also fails for me.  This variation of it works for me:  do(jan, lm, formula = ArrDelay ~ date) .


text:
Q: Error con Local data infile MYSQL Estoy tratando de importar datos desde un archivo csv a una base de datos en mysql por medio del siguiente codigo
LOAD DATA INFILE 'direccion del archivo' INTO TABLE nombre_tabla
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';

Pero al momento de ejecutarlo me aparece el siguiente mensaje
the used command is not allowed with this mysql version

Estoy usando MYSQL WORKBENCH


text:
Q: AABB - AABB Collision response (sliding)
Here is the situation:

*

*I have a room with objects inside

*Each object has it's own AABB

Here is what i do:

*

*I check for collision between objects by checking AABB-AABB intersections

Here is what i need:

*

*How do i calculate the 'sliding' / response between those AABBs?


text:
Q: Add a variable to trigger a function in the parent - Vue I'm trying to call a function in the parent of a child.
I have created a component I can use on multiple pages in my Vue project, once the function has run I want to call a function on the parent.
I can achieve this by doing this.$parent.getLocations() - and it works.
However as this is a component I need getLocations() to be a variable this could be getPets() or getLunch() for example.
I am passing through 'Location' to the component so I can use that.
I have tried: '${this.$parent}.get${this.type}s()}' (this.type being Location) and this.$parent + ".get" + this.type +" s()
However neither trigger the function.
How do I make `getLocations a variable to run the function?

A: It's an anti pattern. The child of the parent should not know about the parent's function.
In the child:
this.$emit('needs-locations', { type: this.type })

In the parent:
<child @needs-locations="getLocations" :locations="locations">

getLocations(type) {
  api.then((locations) => this.locations = locations)
}

This will give you bidirectional communication without dependency.

A: First you emit an event from the child to the parent, and you pass a type to it.
this.$emit('runFunction', type)

Then handle the event:
<child-component @runFunction="handleRunFunction"/>

On the parent runFunction would look like this:
handleRunFunction(type) {
        switch (type) {
            case 'Location':
                getLocations();
            case 'Pets':
                getPets();
            default:
                break;
        }
    }

A normal if-else statement works equally well.


text:
Q: Running multiple SFDX source conversion commands concurrently. Any problems? We have Jenkins setup where it is possible to have multiple builds running concurrently on the same machine. The only SFDX commands that we use are force:mdapi:convert and force:source:convert.
So far we have not noticed any issues but wanted to ensure that there are no potential internal lockings between the concurrent command executions.
I am aware of the various commands that need to share the .sfdx context. But for us, we only use SFDX as pure binary function to help with source conversion and nothing else.
I don't have enough internal understanding of the SFDX CLI to make this judgement but would appreciate comments from anyone in this forum.
Thanks.


text:
Q: (Spring Security Crypto Module) encrypted data Search I have Used Spring Security Crypto Module for data encryption . Now I want To Search these encrypted data from the database.But I am not getting any idea how do i search.Please Post something if you already faced that type of problem.

A: You'll have to decrypt it first. You cannot search encrypted data unless you've deliberately chosen homomorphic encryption and you haven't. Note that homomorphic encryption isn't used too much in practice. Normally encrypted data should be indistinguishable from random.


text:
Q: Is thermal conductivity in a thin, malleable metal possible or practical without conducting electricity? I'm looking to be able to apply and control heat to a malleable metal, ideally a wire. Perfect conditions would be a wire that takes a controlled amount of heat (heated to) between 250-450 degrees, and fairly evenly distributes this heat along it. The application is to selectively burn solid surfaces, such as wood, at scale. First, I would like to be able to vary the shape of the wire iteratively, hence the malleability -- as I develop the ideal "branding" pattern for different pieces. But later, I want to be able to process many pieces rapidly, hence the branding/stamping.
I understand that electrically charging a high-resistance metal, like Nichrome, is the common solution for household devices such as a toaster. This may be my best bet.
However, I want to know if a cost-effective metal / heating method exists without electrifying the metal, in order to increase safety and thus application. Perhaps a solution is a heated metal surface, and pressing a copper wire to it, to bring the wire to temperature before applying it to the work piece. This feels energy inefficient, though.
I also welcome any suggestions for how to think about this differently.

A: Electric heating can be safe if the voltage is low. I have an old notebook that no longer works, but its charger still has an output of 19 V. I was testing it some time ago to heat one of that steel wires used to uncloging pipes.
Even with this type of source, designed to eletronic device and not for high current, the wire could be hot enough to be not possible to hold it with the hand.


text:
Q: Beautiful Soup multiple URLs from bs4 import BeautifulSoup
from docx import Document
from docx.shared import Pt
import requests

user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.``3945.88 Safari/537.37"
url = "https://www.atlanticcouncil.org/events/?ac-timing=past"
data = requests.get(url, headers={"User-Agent": user_agent})
soup = BeautifulSoup(data.text, "lxml")

document = Document()

events = soup.find_all("div", class_ = "gta-embed--content gta-event-embed--content")
for event in events:
    event_name = event.find("h3", class_ = "gta-event-embed--title gta-embed--title")
    link = event.find("a")
    try:
        print(event_name.text)
        document.add_paragraph(event_name.text, style='List Bullet')
        print(link['href'])
        document.add_paragraph(link['href'])
    except:
        continue

document.save('demo.docx')

URL1 = https://www.atlanticcouncil.org/events/?ac-timing=past&ac-page=1
URL2 = https://www.atlanticcouncil.org/events/?ac-timing=past&ac-page=2
I tried this but couldn't make it, is this wrong:
page = 1
while page != 6:
      url = f"https://www.atlanticcouncil.org/events/?ac-timing=past&ac-page={page}"
      print(url)
      page = page + 1

A: Try this code:
from bs4 import BeautifulSoup
from docx import Document
from docx.shared import Pt
import requests

user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.``3945.88 Safari/537.37"

def scrape_and_write_to_docx(page):
    url = f"https://www.atlanticcouncil.org/events/?ac-timing=past&ac-page={page}"
    data = requests.get(url, headers={"User-Agent": user_agent})
    soup = BeautifulSoup(data.text, "lxml")
    events = soup.find_all("div", class_ = "gta-embed--content gta-event-embed--content")
    for event in events:
        event_name = event.find("h3", class_ = "gta-event-embed--title gta-embed--title")
        link = event.find("a")
        try:
            print(event_name.text)
            document.add_paragraph(event_name.text, style='List Bullet')
            print(link['href'])
            document.add_paragraph(link['href'])
        except:
            continue

document = Document()

for page in range(1,7):
    scrape_and_write_to_docx(str(page))

document.save('demo.docx')

Mostly what I did was rearrange things. I took the actual scraping and processing code and put it into a function, then created a quick for loop to run through pages 1-6, and called the function with each value of page. I opened the new Document() at the beginning, and closed/saved it at the very end.
You'll need to do a little tweaking of the strings you write, as the resulting document doesn't look that great, but it has all the info you're looking for.


text:
Q: Determine when value will be greater than x I want every time to add '$(b-x)$' to the value of $a$ and i want to know how many times i will repeat this operation to be the value of $a$ greater or equal to $x$.
$a = b+a - x$
I know that $b > x$ and $ a < x $
Any ideas?

A: So you have an arithmetic sequence
$t_n = a + n(b - x)$, (Starting at $n = 0$).
where $a < x < b$, and you want to know the first time that $t_n > x$
\begin{align}
   t_n & > x\\
   a + n(b - x) & > x\\
   n(b - x) & > x - a\\
   n & > \dfrac{x - a}{b - x}\\
   n & = \left \lceil \dfrac{x - a}{b - x} \right \rceil
\end{align}
If $\dfrac{x - a}{b - x}$ is not an integer, then
$n = \left \lfloor 1 + \dfrac{x - a}{b - x} \right \rfloor
   = \left \lfloor \dfrac{b - a}{b - x} \right \rfloor$
But if $\dfrac{x - a}{b - x}$ is an integer, then the answer is still
$\left \lceil \dfrac{x - a}{b - x} \right \rceil$.

A: Let the answer is n. Then you have to add $(b-x)$ to $a$, n times. So
$$x \geq a + n(b-x)$$
And then $$n=\frac{x-a}{b-x}$$
which is the answer.
If the answer comes in fractions then just take the next integer.


text:
Q: How does MySQL handle exotic between statements I have a between case, where the expression is not a calculation nor a field.
Somehow this is valid SQL and the results with different permutations for this kind of system, gives different results.
I have tried to figure out what MySQL does, but I couldnt make out any pattern nor any sense.
Here is the example Query:
SELECT
*
FROM
<table>
WHERE
status = 'test'
BETWEEN
2 AND
'test';

Feel free to replace the values and data types.
I would appreciate a hint to what could happen here exactly.

A: status = 'test' results in true or false which equals 1 or 0 in MySQL.
BETWEEN 2 AND 'test' translates to BETWEEN 2 AND 0 in MySQL.
x BETWEEN a AND b translates to x >= a AND x <= b.
So the condition is never met:
1 >= 2 AND 1 <= 0 => false
2 >= 2 AND 2 <= 0 => false

The query should never return any row.
CORRECTION: It shows that MySQL doesn't Interpret
WHERE status = 'test' BETWEEN 2 AND 'test'

as
WHERE (status = 'test') BETWEEN 2 AND 'test'

but as
WHERE status = ('test' BETWEEN 2 AND 'test')

which I consider a flaw. (EDIT: I looked it up; it is a flaw. The comparision operator = should have precedence over BETWEEN: https://dev.mysql.com/doc/refman/5.7/en/operator-precedence.html.)
Anyway:

*

*('test' BETWEEN 2 AND 'test') is always false, which is 0 in MySQL.

*If status is a string column, then status converted to integer results in 0 for most strings. Only if the string starts with an integer that integer is converted to number. E.g. '123ABC' results in 123.

*If status is a numeric column it is not converted.

*If status is a boolean column it gets converted to 0 for false and 1 for true.

*So some rows get returned, others not.

A: From MySQL documentation:

If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0. This is equivalent to the expression (min <= expr AND expr <= max) if all the arguments are of the same type. Otherwise type conversion takes place according to the rules described in Section 12.2, "Type Conversion in Expression Evaluation", but applied to all the three arguments.

So BETWEEN is operating in the same way for integers and for character strings. MySQL is doing type conversion to be able to calculate this operation. This is part of the ANSI standard.
For example:
// returns true
select ('C' BETWEEN 'A' AND 'D');

Or more interesting:
//also returns true
select ('test' BETWEEN 'test' AND 'testa');

For more information check here and here.


text:
Q: Mutexes with variables in struct I'm working on a project that uses multiples threads which can access a shared struct containing multiple variables.
To avoid concurrency problems, I use mutexes whenever a write is made to one of the variables inside the shared struct. Right now I use a different mutex for each variable, so that I avoid locking a thread for trying to write to a variable that is not being written to, but I'd like to know if there is a better way to avoid this problem.
Also, considering that my struct has uint16_t variables, is there any additional measures I should take to guarantee data consistency across threads because of memory alignment and multiple variables stored on the same data register?
Thanks.

A: You didn't say what language.  I'm going to pretend it's C++.

I use a different mutex for each variable...

That sounds suspicious.
Your threads communicate with each other by updating shared state.  A mutex, when correctly used, does two things:

*

*It ensures that after thread A updates the shared state, other threads will be able to see what was changed, and

*It ensures that the other threads will not see the change until the change is complete.

If a thread can meaningfully change the state of the program by writing a single uint16_t value, then you don't need a mutex for that.  Just change the type of the variable to atomic<uint16_t>.  Making it atomic will ensure that other threads can see the change.  And, you don't have to worry about the completeness.  That's trival: Every other thread must either see the old value or the new value. There's no other possibilities.
You need a mutex when the situation is more complicated.  Suppose you have three variables:
int a, b, c;

And, suppose that there's a rule, that a+b+c must always equal zero.  A rule like that is called an invariant.  Now, there's no way a thread can legally change just one of those three variables.  But, if it tries to change two of them in a row, there's always the possibility that some other thread could look at them at just the wrong moment, and it could see them in an inconsistent state (i.e., in a state that breaks the invariant.)
Making the variables atomic won't fix the problem.  And, making a separate mutex for each variable won't fix the problem.  You need one mutex whose purpose is to protect the invariant.  You need every thread that updates a, b, and/or c to lock that one mutex whenever it's making a change; and you need every thread that expects the invariant to be true to lock the same mutex whenever it looks at them.