text:
Q: Copy attribute information when different element have the same name in XML with python So, here's my XML tree:
<?xml version="1.0"?>
<api>
    <query>
        <normalized>
            <n from="Brain_cancer" to="Brain cancer" />
        </normalized>
        <redirects>
            <r from="Brain cancer" to="Brain tumor"
            />
        </redirects>
        <pages>
            <page pageid="37284" ns="0" title="Brain tumor">
                <revisions>
                    <rev revid="412658600" parentid="412501243" user="Andycjp" userid="55014" timestamp="2011-02-08T03:35:27Z" size="59870" sha1="fe1ff25c27ebc86572aa4be8201cb813e1bf3d32" comment="/* Psychological and behavioral consequences */"  contentformat="text/x-wiki" contentmodel="wikitext" xml:space="preserve">
                    </rev>
                </revisions>
            </page>
        </pages>
    </query>
    <warnings>
        <revisions xml:space="preserve">
        </revisions>
        <result xml:space="preserve">
        </result>
    </warnings>
    <query-continue>
        <revisions rvcontinue="456175380"
        />
    </query-continue>
</api>

So, has you can see, the "revisions" element appears in two differents places, in differents levels. My objective is to reach the attribute "rvcontinue" (who's path is api/query-continue/revisions) to copy it's value in a new variable. It's probably because i'm just not getting it right, but elementTree and xpath didn't work so far.
This is what i've did so far, but it's getting no where
import xml.etree.ElementTree as ET
tree = ET.parse('Brain_tumor_5.xml')

for elem in tree.getiterator():
    if elem.tag=='{http://www.namespace.co.uk}query-continue':
        output = {}
        for elem1 in list(elem):
            if elem1.tag=='{http://www.namespace.co.uk}revisions':
                output['rvcontinue']=elem1.text
        print output

p = tree.find("./api/query-continue/revisions[@rvcontinue=]")
q = p.attrib
print q

A: I also have mostly used lxml, so I don't know what's up with etree, but it appears
that find from the tree doesn't work, but find from the root does work:
>>> tree.getroot().find( 'query-continue/revisions[@rvcontinue]' ).attrib['rvcontinue']
'456175380'

Also: I don't know if it's just a typo above, but:
p = tree.find("./api/query-continue/revisions[@rvcontinue=]")

will give a SyntaxError: invalid predicate
Added Note: It appears that tree.find( 'api' ) returns None,
but tree.find( '.' ) returns <Element 'api' at 0x1004e5f10>
so tree.find( './query-continue/revisions[@rvcontinue]' )
will also work.

A: This does not directly answer your question. However, I would use lxml.etree (which supposedly provides the same ElementTree interface) and the following code:
>>> import lxml.etree
>>> doc = lxml.etree.parse('doc.xml')
>>> node = doc.xpath('/api/query-continue/revisions[@rvcontinue]')
>>> node[0].attrib['rvcontinue']
'456175380'

Tried with xml.etree.ElementTree but doesn't appear to work.


text:
Q: Deriving the momentum Feynman rule for a vertex with a derivative of the field Consider the following modification of the klein gordon lagrangian:
$$S = \int\left(\frac{1}{2}(\partial \phi)^2 - \frac{m^2}{2}\phi^2 + \frac{\delta Z}{2}(\partial \phi)^2 - \frac{\delta m^2}{2}\phi^2 \right) \ d^4x.$$
I tried to calculate the momentum space feynman rule for the vertex $\frac{\delta Z}{2}(\partial \phi)^2 - \frac{\delta m}{2}\phi^2$. In order to do this, I tried transforming them into momentum space but I seem to be getting some unexpected result.  Let
$$\phi = \int\tilde{\phi} e^{ikx}dk.$$
Differentiating this gives:
$$\partial_\mu \phi = \int ik_{\mu} \tilde{\phi} e^{ikx}.$$
So we have $$(\partial \phi)^2 = - \int k'_{\mu}k^{\mu} \tilde{\phi} \tilde{\phi'}e^{i(k+k')x}dkdk'$$
and
$$\phi^2 = \int  \tilde{\phi}\tilde{\phi'} e^{i(k+k')x}dkdk'.$$
Since these are internal vertices, we will have an integral over all space. So we have,
$$\int \frac{\delta Z}{2}(\partial \phi)^2 - \frac{\delta m}{2}\phi^2 dx = - \frac{\delta Z}{2} \int k'_{\mu}k^{\mu} \tilde{\phi} \tilde{\phi'} \delta(k+k')dkdk' - \frac{\delta m^2}{2} \int  \tilde{\phi}\tilde{\phi'} \delta(k+k')dkdk'. $$
Therefore giving us:
$$\frac{\delta Z}{2} \int k_{\mu}k^{\mu} \tilde{\phi}(k) \tilde{\phi}(-k) dk - \frac{\delta m^2}{2} \int  \tilde{\phi}(k)\tilde{\phi}(-k) dk = \int [\frac{\delta Z}{2} k^2 - \frac{\delta m^2}{2}]\tilde{\phi}(k) \tilde{\phi}(-k) dk.$$
I might have messed up the signs somewhere but this would have been the right result if there was a $\tilde{\phi}^2$ instead of $\tilde{\phi}(k) \tilde{\phi}(-k)$ because it should be a two-legged  vertex I believe. What did I do wrong in the derivation?

redpajama_set_name: RedPajamaStackExchange


text:
Q: UML contracted user case contains system borders? Does contracted user case contain system borders? I mean: does it contain something like: machine doing biscuits, or just selling.

A: You have to depict the relevant use cases for each actor. So what are your actor(s) and does it make sense to associate them to "machine doing biscuit" or "selling" use cases?

A: *

*According to UML standard, every use case element MUST have at least one association with an actor element.

*So, if you want to show something as border classes, i.e., elements that are connected to user and elements that are not connected to user, it is impossible. EVERY use case shown in UC diagram must be connected to user.

*The UC diagram is not for showing inner, invisible for user behaviours. Its purpose is to define the subject (according to UML standard, the product you are working at)  by defining all its external behaviours.

*A system on UC diagram is shown as a rectangle. Its borders contain the use cases that belong to the system. The same for subsystems, components and packages on the UC diagram.

*So, a machine whose functionalities only support other machines, but never works with Actor (human or external system), is NOT a subsystem in UC diagram terms. Its functionality is not a use case. If you'll try to show it somehow here, you'll get a very bad and unreadable UC diagram. Show it on component and deployment diagrams.


text:
Q: Detecting a grid with Python OpenCV I have an image of a goban (example below). I want to detect the grid of the playing area to create an (x, y) coordinate system of the board. To start I am trying to just detect the lines on the board:
def find_lines(filename):
    gray = cv2.imread(str(filename), cv2.IMREAD_GRAYSCALE)

    kernel_size = 5
    blur = cv2.GaussianBlur(gray, (kernel_size, kernel_size), 0)

    low_threshold = 50
    high_threshold = 150
    edges = cv2.Canny(blur, low_threshold, high_threshold)
    rho = 1  # distance resolution in pixels of the Hough grid
    theta = np.pi / 180  # angular resolution in radians of the Hough grid
    threshold = 15  # minimum number of votes (intersections in Hough grid cell)
    min_line_length = 50  # minimum number of pixels making up a line
    max_line_gap = 20  # maximum gap in pixels between connectable line segments
    lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)

    line_image = np.zeros((*gray.shape, 3))
    for line in lines:
        for x1,y1,x2,y2 in line:
            cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),5)
    return line_image

def main(filename):
    lines = find_lines(filename)
    cv2.imwrite('lines.jpg'), lines)

if __name__ == '__main__':
    main(sys.argv[1])

This gives me a good image of the outline of the board, but I want to get just the grid. Part of the difficulty is that the grid lines have a width and HoughLinesP() is giving me the outline of these lines. Also, it is giving me multiple segments along each grid line when I want the (x, y) coordinates at the top and bottom or left and right of each grid line. The lines variable in find_lines() has dimensions (1411, 1, 4), but I only want the 38 grid lines. What can I do from here to get just the endpoints of the grid lines?


text:
Q: A function $g : \mathbb{R} \to \mathbb{R}$ is right-continuous if and only, if it preserves infima
I want to prove that a monotone ($=$ non-decreasing) function $g : \mathbb{R} \to
 \mathbb{R}$ is right-continuous if and only, if it preserves infima.

Unfortunately, I don't know how to prove any of the two directions. How do I go about this?
Remark: I assume it is known that if $g$ is monotone, then $g(\inf_{i\in I} x_i) \leq \inf_{i\in I} g(x_i)$. So for the forward direction only the other inequality has to be proved.

A: For a nondecreasing $g\colon \mathbb{R}\to \mathbb{R}$, we have
$$\lim_{x \to a^+} g(x) = \inf \{ g(x) : x > a\}.\tag{1}$$
Thus such a $g$ is right-continuous if and only if
$$g(a) = \lim_{x\to a^+} g(x)$$
for every $a\in\mathbb{R}$ (by definition of right continuity), if and only if
$$g(a) = g(\inf \{ x : x > a\}) = \inf \{ g(x) : x > a\}\tag{2}$$
by $(1)$.
So if $g$ preserves infima, i.e.
$$g(\inf M) = \inf \{ g(x) : x \in M\}$$
for all nonempty $M\subset \mathbb{R}$ that are bounded below, $(2)$ gives right continuity by choosing $M = (a,+\infty)$.
On the other hand, let $g$ right-continuous, and $\varnothing \neq M$ bounded below. If $\inf M \in M$, then clearly
$$g(\inf M) = \inf \{ g(x) : x \in M\}$$
by monotonicity. And if $\inf M \notin M$, then
$$g(\inf M) = \lim_{x\to (\inf M)^+} g(x) = \inf \{ g(x) : x > \inf M\} = \inf \{ g(x) : x \in M\},$$
since for every $x > \inf M$ there is an $m \in M \cap (\inf M,x)$. So $g$ preserves infima.
Note: we only consider nonempty sets that are bounded below. If we admit sets that are empty or not bounded below, the assertion may be wrong, or we must change the codomain to $[\inf g(\mathbb{R}), \sup g(\mathbb{R})]$ and set $g(-\infty) = \inf g(\mathbb{R}),\, g(+\infty) = \sup g(\mathbb{R})$, and interpret $\inf \varnothing = \sup g(\mathbb{R})$ in the codomain.


text:
Q: How to create a BaseClass that adds logging messages I am using serenity BDD for my automation testing and Page Object Model for my framework. I have created a BasePage class which will be inherited by all the other Pages. I want to minimize the logging messages from the Pages by adding all the log.info messages to a central Base page. Example, when calling the click() method, I will log before click and after click methods as shown below in the basePage class:
public class BasePage extends PageObject{
private static final Logger log = LogManager.getLogger(BasePage.class.getClass());
private final WebElementFacade element;

public static void clickBtn(WebElementFacade btnName) {
        log.info("About to click " + btnName + " button");
        btnName.click();
        log.info("Successfully clicked on " + btnName + " button.");
    }

Later I figured that instead of individually trying to figure out in advance what actions the user will perform on the webElements, and write new methods for each action (like the one shown above), just implement WebDriverFacade interface, so that I get all the unimplemented method list in BasePage from WebDriverFacade and then write the log messages inside each of them, like so:
public class BasePage extends PageObject implements WebElementFacade{
private static final Logger log = LogManager.getLogger(BasePage.class.getClass());
private final WebElementFacade element;

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

}

@Override
public void sendKeys(CharSequence... keysToSend) {
    // TODO Auto-generated method stub

}

@Override
public String getTagName() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public boolean isSelected() {
    // TODO Auto-generated method stub
    return false;
}
        .
        .
        .
        .
        .

}
This will serve two purposes:

*

*I will not have to create new methods for every action in BasePage class, example the 'clickBtn()' function in the first code

*As I mentioned before, I will not have to figure out what method any other person who adds methods to my code might use and having to change the BasePage class to create the new actions. So basically less maintenance in the long run.

The problem I am facing is an error that I receive in the second use case:
The return types are incompatible for the inherited methods WebElementFacade.withTimeoutOf(int, TimeUnit), PageObject.withTimeoutOf(int, TimeUnit)
Now my question is:

*

*How can solve this problem?

*Is this the right way to do things or should I be going with the first method and have maintenance overhead.

Just figured that another scenario where this might be useful. To make sure that subclass methods do not use methods from pageObject and are forced to use the methods from BaseClass only. This can be done by wrapping the WebElementFacade and adding the log messages as an added functionality. Any thought on this would be appreciated.
Thank you!

A: Honestly it is a neat trick and if you get it working you should be proud.
I think I figured something similar out in a dynamic language.
But you are better off just adding the logging entries and learning the following.
How to name functions so you don't feel like they need renaming.
How to log clearly for debugging use.
This is because loggings power is in its flexibility.
When you learn how to dump something complex like a matrix so you can eye it and go uh-oh  you are increasing your overall skills.
I apologize for not giving you code but I felt some "chase the other rabbit" advice was better.


text:
Q: Field Mapping Examples Using ArcGIS 10.4, arcpy
I am having trouble understanding field mappings and the esri examples aren't helping at all.  When I use model builder the field mappings make sense, but I need to customize them more.  I can successfully take the ObjectID field,add it to my new feature class with the input data from the old, but that is the only field that comes in. Is there a way to add all the others instead of going one by one? It seems like it should be so simple, I tried the (addtable) but that is where I am lost.
My end game is to keep ObjectID in my new feature class, I want everything else the same (Type, Length, etc).  Right now on my 'FeatureClasstoFeatureClass' all I can keep with the field mappings is ObjectID.  I could join it up and rexport but field mapping seems like it should be the easiest.
http://pro.arcgis.com/en/pro-app/arcpy/classes/fieldmappings.htm
I am looking at the examples here.  They only mention adding two fields, but what about every field.

A: This is an example how you can use field mapping in a function to return a feature layer with only specified fields visible:
import arcpy

def get_fl_with_optional_fields(in_fc, fieldlist):
    fc_desc = arcpy.Describe(in_fc)
    fl = arcpy.MakeFeatureLayer_management(in_fc,fc_desc.baseName)
    src_field_info = arcpy.Describe(fl).fieldInfo
    for field in [f.name for f in arcpy.ListFields(in_fc)]:
        field_idx = src_field_info.findfieldbyname(field)
        if field in fieldlist:
            src_field_info.setVisible(field_idx,'VISIBLE')
        else:
            src_field_info.setVisible(field_idx,'HIDDEN')
    newfl = arcpy.MakeFeatureLayer_management(in_fc,in_fc+'_fl',field_info=src_field_info)
    return newfl

arcpy.FeatureClassToFeatureClass_conversion(in_features=get_fl_with_optional_fields(r'C:\data.gdb\polygon123',['SomeFieldName','SomeFieldName2']), out_path=r'C:\data.gdb',
                                           out_name='newpolygons')


text:
Q: Screenshot w/highlighting feature wanted There are two super nice features on my iPhone:

*

*ability to take a screenshot with a hardware button combo;

*ability to highlight it with a semitransparent brush;

It enables me to take screenshots and draw "attention areas" over them.
There is a nearly same feature in Windows with Snipping Tool (much less convenient though).
Is there a way in Ubuntu to:

*

*run some tool via keyboard shortcut;

*take a screenshot of some area on the screen;

*highlight important area with a semitransparent brush.

A: Can I run some tool via keyboard shortcut?
Yes! Gnome has it's default shortcuts to do so, but so does KDE!
You can also customize Gnome or KDE to run a command when you hit the defined shortcut (see next response for said commands).

Can I take a screenshot of some area on the screen?
If you're using Gnome (the default desktop environment of  Ubuntu), you can either press Shift + Prt Scrn or pass the -a option to gnome-screenshot to start it in "area selection mode".
There are other options that you can use, like -w to capture a window, or -c to put the screenshot in the clipboard.
More infos can be found in gnome-screenshot's manpage.
If you're not using Gnome, I can either recommend:

*

*CLI only: maim with xclip for the clipboard part.

*GUI: flameshot
There is a ton of other tools listed in this question, but be warned that some of them (like Shutter) are completely outdated and unmaintained.
Personally, I use maim+xclip. Here the commands I use:
# Screenshot an area and store in clipboard
/bin/sh -c "maim -q -s | xclip -selection clipboard -t image/png"

# Screenshot an area and store in file
/bin/sh -c "maim -q -s ~/Pictures/Screenshots/region_$(date +%s).png"

Can I highlight important area with a semitransparent brush?
In that case, flameshot is definitely what you're looking for :)
just do sudo apt-get install flameshot and change your shortcuts to use it as the default!


text:
Q: Изменение ячейки с помощью combobox в datagridview Есть код по заполнению таблицы. Но никак не разберусь как заставить изменять значение в столбце "Код поставщика" при изменении значения в combobox в столбце "Поставщики". Буду признателен за подсказки и помощь.
conn = new OleDbConnection(conn_string);
conn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
string query = "select Договор.*, Поставщики.Название from Договор, Поставщики where Договор.[Код поставщика] = Поставщики.[Код поставщика] order by [№ договора]";
command.CommandText = query;

OleDbDataAdapter da = new OleDbDataAdapter(command);
dt = new DataTable();
da.Fill(dt);
Поставщики.DisplayMember = "Название";
Поставщики.ValueMember = "Код поставщика";
Поставщики.DataSource = dt;
dataGridView1.DataSource=dt;
this.dataGridView1.Columns["Название"].ReadOnly = true;
conn.Close();

A: Получилось вот так

DataSet dataSet = new DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
OleDbDataAdapter dataAdapter1 = new OleDbDataAdapter();

string query = "select * from Договор";
string query1 = "select * from Поставщики";

conn = new OleDbConnection(conn_string);

dataAdapter.SelectCommand = new OleDbCommand(query, conn);
dataAdapter1.SelectCommand = new OleDbCommand(query1, conn);

dataAdapter.TableMappings.Add("Table", "Договор");
dataAdapter1.TableMappings.Add("Table", "Поставщики");

dataAdapter.Fill(dataSet);
dataAdapter1.Fill(dataSet);

BindingSource dogSource = new BindingSource();
dogSource.DataSource = dataSet;
dogSource.DataMember = "Договор";
dataGridView1.DataSource = dogSource;

BindingSource postSource = new BindingSource();
postSource.DataSource = dataSet;
postSource.DataMember = "Поставщики";

DataGridViewComboBoxColumn comboColumn = new DataGridViewComboBoxColumn();
comboColumn.HeaderText = "Поставщики";
comboColumn.DataSource = postSource;

comboColumn.DataPropertyName = "Код поставщика";

comboColumn.DisplayMember = "Название";

comboColumn.ValueMember = "Код поставщика";


text: Q: Alternative to list to store large dataframe? I have a multiple files in a folder. Looping through the folder I use pd.read_csv() to read the files and store it in the list. After storing all the files I use pd.concat(list) to get the single dataframe. But, my concern is list uses the memory to store the data. When the dataframe is huge list consumes lots of memory. Is there any other alternative to list I can use to store the data


text:
Q: tictactoe game No operator "==" matches these operands It is probably very inefficient and messy but here is my problem- Where it says stuff like "zz == defo && zo == defo" The equals is underlined in red saying Error: no operator "==" matches these operands and when I run I get an error that is too long to post here- http://pastebin.com/KTEM0MZK
What am I doing wrong? Thanks in advance
Here is my code-
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
using namespace std;

string random1(){
    srand(((time(0) - 23) * time(0)) - (9*time(0)));
  if (rand() % 2 == 0){
    return "1";
        } else {
            return "0";
        }
}
string random2(){
    srand((((time(0) - 89) * time(0)) - (9*time(0)) / 3) - 99);
  if (rand() % 2 == 0){
    return "1";
        } else {
            return "0";
        }
}
int main(){
    string zz = "-";
    string zo = "-";
    string zt = "-";
    string oz = "-";
    string oo = "-";
    string ot = "-";
    string tz = "-";
    string to = "-";
    string tt = "-";
    for(int a = 1;a<=9;a++){
        srand ( time(NULL) - 8 );
        int ran1 = rand() % 3;
        srand ( time(NULL) * 2);
        int ran2 = rand() % 3;
        int tote = (ran1 * 10) + ran2;
        cout << endl << "format- 0 = zero, 1 = one, 2 = two" << endl;
        int input;
        cin >> input;
        if(input == 00){
            zz = "X";
        } else if(input == 01){
            zo = "X";
        } else if(input == 02){
            zt = "X";
        } else if(input == 10){
            oz = "X";
        } else if(input == 11){
            oo = "X";
        } else if(input == 12){
            ot = "X";
        } else if(input == 20){
            tz = "X";
        } else if(input == 21){
            to = "X";
        } else if(input == 22){
            tt = "X";
        }
        // now for the computers part
        if(tote == 00){
            zz = "O";
        } else if(tote == 01){
            zo = "O";
        } else if(tote == 02){
            zt = "O";
        } else if(tote == 10){
            oz = "O";
        } else if(tote == 11){
            oo = "O";
        } else if(tote == 12){
            ot = "O";
        } else if(tote == 20){
            tz = "O";
        } else if(tote == 21){
            to = "O";
        } else if(tote == 22){
            tt = "O";
        }
        printf ("|%d|%d|%d", zz, zo, zt);
        cout << endl;
        printf ("|%d|%d|%d", oz, oo, ot);
        cout << endl;
        printf ("|%d|%d|%d", tz, to, tt);

        if(zz == "X" && zo == "X" && zt == "X" || oz == "X" && oo == "X" && ot == "X" || tz == "X" && to == "X" && tt == "X" || zz == "X" && oz == "X" && tz == "X" || zo == "X" && oo == "X" && to == "X" || zt == "X" && ot == "X" && tt == "X" || zz == "X" && oo == "X" && tt == "X"){
            cout << endl << "X WINNER";
        break;
        }
        if(zz == "O" && zo == "O" && zt == "O" || oz == "O" && oo == "O" && ot == "O" || tz == "O" && to == "O" && tt == "O" || zz == "O" && oz == "O" && tz == "O" || zo == "O" && oo == "O" && to == "O" || zt == "O" && ot == "O" && tt == "O" || zz == "O" && oo == "O" && tt == "O"){
            cout << endl << "O WINNER";
            break;
        }
    }
    system("pause");
    return 0;
}

A: You need to #include <string>, where the operator== is defined.
And, as already stated by jrok, you are passing a std::string to printf(): use cout instead (as you already using).

A: You're trying to pass std::strings to printf, which is a C library function. Furthermore, the format string says you'll pass integers ("|%d|%d|%d").
printf will only take c-style strings, so if that's what you want, you can say something like:
printf("|%s|%s|%s", ot.c_str(), zz.c_str(), ...);

A: also pertaining to your code
if(zz == "X" && zo == "X" && zt == "X" || oz == "X" && oo == "X" && ot == "X" || tz == "X" && to == "X" && tt == "X" || zz == "X" && oz == "X" && tz == "X" || zo == "X" && oo == "X" && to == "X" || zt == "X" && ot == "X" && tt == "X" || zz == "X" && oo == "X" && tt == "X"){
        cout << endl << "X WINNER";

should be
if((zz == "X" && zo == "X" && zt == "X") || (oz == "X" && oo == "X" && ot == "X") || (tz == "X" && to == "X" && tt == "X") || (zz == "X" && oz == "X" && tz == "X") || (zo == "X" && oo == "X" && to == "X") || (zt == "X" && ot == "X" && tt == "X") || (zz == "X" && oo == "X" && tt == "X")){
        cout << endl << "X WINNER";

Your compares are looking at each individual mark instead of looking for a combination of marks.  The () around each set of 3 will give you your desired result.


text:
Q: MultiChoiceModeListener not working I am trying to implement MultiChoiceModeListener for select multiple item from a ListView. My current progress is shown below. But it doesn't working. It has no action on even long press. is any thing missed in my code or anything wrong? Any help will be greatly appreciated.
public class FragmentFavorite extends Fragment {

    ListView lvFavoriteItems;
    Activity mActivity = null;
    Context mContext;
    ArrayList<String> names = new ArrayList<>(Arrays.asList("My name is a", "My name is b",
            "My name is c", "My name is d", "My name is e", "My name is f"));
    ArrayList<String> phone = new ArrayList<>(Arrays.asList("9895653263", "9895653264", "9895653265",
            "9895653266", "9895653267", "9895653267"));

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if(mActivity == null) {
            this.mActivity = getActivity();
        }
        this.mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.favorite_list, container, false);
        lvFavoriteItems = (ListView) root.findViewById(R.id.lv_item_list);
        FavoriteAdapter fav = new FavoriteAdapter();
        lvFavoriteItems.setAdapter(fav);
        lvFavoriteItems.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        lvFavoriteItems.setMultiChoiceModeListener(new FavMultiChoiceModeListener());
        return root;
    }

    private class FavoriteAdapter extends BaseAdapter {

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

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            View listItem;
            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (convertView == null) {
                listItem = inflater.inflate(R.layout.contact_item_2_line, null);
            } else {
                listItem = convertView;
            }
            TextView tv1 = (TextView) listItem.findViewById(R.id.tv_item_name);
            tv1.setText(names.get(position));
            TextView tv2 = (TextView) listItem.findViewById(R.id.tv_phone);
            tv2.setText(phone.get(position));
            listItem.setId(position);
            return listItem;
        }    }

    private class FavMultiChoiceModeListener implements ListView.MultiChoiceModeListener {

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int i, long l, boolean b) {
            final int checkedCount = lvFavoriteItems.getCheckedItemCount();
            mode.setSubtitle("" + checkedCount + " items selected ");
        }

        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            MenuInflater inflater = mActivity.getMenuInflater();
            inflater.inflate(R.menu.selection_menu, menu);
            actionMode.setTitle("Select Items");
            return true;

        }

        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return true;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            Toast.makeText(mActivity, "Clicked " + menuItem.getTitle(),
                    Toast.LENGTH_SHORT).show();
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    }
}

A: Since you're extending from BaseAdapter, you might need to call convertView.setLongClickable(true) in your getView method.


text:
Q: Rails 3: How to "redirect_to" in Ajax call? The following attempt_login method is called using Ajax after a login form is submitted.
class AccessController < ApplicationController
  [...]
  def attempt_login
    authorized_user = User.authenticate(params[:username], params[:password])

    if authorized_user
      session[:user_id] = authorized_user.id
      session[:username] = authorized_user.username
      flash[:notice] = "Hello #{authorized_user.name}."
      redirect_to(:controller => 'jobs', :action => 'index')
    else
      [...]
    end
  end
end

The problem is that redirect_to doesn't work.
How would you solve this ?

A: There is very easy way to keep the flash for the next request. In your controller do something like
flash[:notice] = 'Your work was awesome! A unicorn is born!'
flash.keep(:notice)
render js: "window.location = '#{root_path}'"

The flash.keep will make sure the flash is kept for the next request.
So when the root_path is rendered, it will show the given flash message. Rails is awesome :)

A: I think this is slightly nicer:
render js: "window.location.pathname='#{jobs_path}'"

A: In one of my apps, i use JSON to carry on the redirect and flash message data. It would look something like this:
class AccessController < ApplicationController
  ...
  def attempt_login
    ...
    if authorized_user
      if request.xhr?
        render :json => {
          :location => url_for(:controller => 'jobs', :action => 'index'),
          :flash => {:notice => "Hello #{authorized_user.name}."}
        }
      else
        redirect_to(:controller => 'jobs', :action => 'index')
      end
    else
      # Render login screen with 422 error code
      render :login, :status => :unprocessable_entity
    end
  end
end

And simple jQuery example would be:
$.ajax({
  ...
  type: 'json',
  success: functon(data) {
    data = $.parseJSON(data);
    if (data.location) {
      window.location.href = data.location;
    }
    if (data.flash && data.flash.notice) {
      // Maybe display flash message, etc.
    }
  },
  error: function() {
    // If login fails, sending 422 error code sends you here.
  }
})

A: Combining the best of all answers:
...
if request.xhr?
  flash[:notice] = "Hello #{authorized_user.name}."
  flash.keep(:notice) # Keep flash notice around for the redirect.
  render :js => "window.location = #{jobs_path.to_json}"
else
...

A: Finally, I just replaced
redirect_to(:controller => 'jobs', :action => 'index')

with this:
render :js => "window.location = '/jobs/index'"

and it works fine!

A: def redirect_to(options = {}, response_status = {})
  super(options, response_status)
  if request.xhr?
    # empty to prevent render duplication exception
    self.status = nil
    self.response_body = nil
    path = location
    self.location = nil

    render :js => "window.location = #{path.to_json}"
  end
end

A: I didn't want to modify my controller actions so I came up with this hack:
class ApplicationController < ActionController::Base
  def redirect_to options = {}, response_status = {}
    super

    if request.xhr?
      self.status        = 200
      self.response_body = ""
    end
  end
end


text:
Q: Type T = Type.GetType(TypeName); T is returning Null Its a simple program where I am passing System.Console and it will return me the Methods it has by using Reflection ... Here Type object T is taking Null even after I am passing System.Console in txtTypeName.Text
My Code :
    string TypeName = txtTypeName.Text;
    Type T  = Type.GetType(TypeName,true);

    MethodInfo[] methods = T.GetMethods();
    foreach (MethodInfo method in methods)
    {
        lstMethod.Items.Add(method.Name);
    }

Type T = Type.GetType(TypeName); T is returning Null

A: The accepted answer is not quite correct.
The behaviour of Type.GetType did not change between framework versions. The documentation in both of them states (my bold):

Parameters
typeName String
The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, it is sufficient to supply the type name qualified by its namespace.

Only types that are in the calling assembly or in the BCL assembly do not need qualification. The difference between the two version of the framework is simply that System.Console got moved to a different assembly, so that is why it is failing. The docs for .NET 6 shows System.Console.dll, while NET 4.7 shows mscorlib.dll
You can, for example, see in these two fiddles what happens if you try System.DateTime without qualification: it works in both cases.
.NET 4.7
.NET 6

A: The behaviour of Type.GetType() has changed for .net Core and later*.
This code works with .net 4.8:
Type? t = Type.GetType("System.Console", true);
Console.WriteLine(t!.FullName);

But it fails in .net Core and later!
Repro showing it not working in .net 6.0: https://dotnetfiddle.net/JlAhqn
Repro showing it working in .net 4.7.2: https://dotnetfiddle.net/ahV7fC
To make this work in .net Core or later you need to specify the assembly-qualified name of the type, which includes the name of the assembly from which this Type object was loaded.
For the type System.Console the assembly name is also "System.Console" so the following works in .net Core and .net Framework:
Type? t = Type.GetType("System.Console, System.Console", true);
Console.WriteLine(t!.FullName);

Repro showing it working in .net 6.0: https://dotnetfiddle.net/dA1ulx

*As noted by the other answer, the behaviour has changed for "System.Console" because it was moved to another assembly.
There have been some other changes in the area that can affect Type.GetType(), specifically because of changes to Assembly.LoadFrom() but those changes aren't causing this effect.
See here for details: https://github.com/dotnet/runtime/issues/12376


text:
Q: Why is there an $E^2$-term in the expression for the polarization density in nonlinear optics In nonlinear optics the polarization density can be expressed as $$P_i=\epsilon_0(X_{ii}^{(1)}E_i+X_{iji}^{(2)}E_jE_i+\dots)$$
As far as I know, $P$ arises from the dipole moment in materials, and $E$ is an applied electric field in this equation. Terms involving $E^2$ and $E^3$ cause the phenomenon of nonlinear optics. However, I don't understand why these $E^2, E^3 \dots$ terms appear in this equation? What's the physical meaning?

A: When an electric field $\mathbf{E}$ interacts with matter, it causes the atoms and molecules to distort and separate into dipole-like blobs, and these dipole blobs then increase the field strength. So, inside of the matter, the total electric field is actually the sum of two components: the external electric field $\mathbf{E}$, plus the electric field induced by the matter itself when it responds to the external field.
Traditionally, this total field times $\varepsilon_0$ is written as $\mathbf{D}=\varepsilon_0\mathbf{E}+\mathbf{P}(\mathbf{E})$, where $\mathbf{P}(\mathbf{E})$ is the electric field generated by the matter as a function of $\mathbf{E}$, and is called the polarization.
Since $\mathbf{P}$ is a function of $\mathbf{E}$, we can Taylor expand $\mathbf{P}$ around the origin:
$$\mathbf{P}(\mathbf{E})=\sum_{n=0}^\infty \frac{(\nabla^n\mathbf{P})(\mathbf{0})\cdot\mathbf{E}^n}{n!},$$
where $\mathbf{E}^n=\mathbf{E}\otimes\mathbf{E}\otimes\mathbf{E}...$ is the $n^\text{th}$ outer product of $\mathbf{E}$, $(\nabla^n\mathbf{P})(\mathbf{0})$ is the $n^\text{th}$ derivative of $\mathbf{P}$ evaluated at the origin, and $\cdot$ is tensor contraction. Defining $\chi^{(n)}=\frac{1}{\varepsilon_0n!}(\nabla^n\mathbf{P})(\mathbf{0})$ and using the fact that in a non-electret material $\mathbf{P}(\mathbf{0})=\mathbf{0}$, we can rewrite this as
$$\mathbf{P}(\mathbf{E})=\varepsilon_0\sum_{n=1}^\infty\chi^{(n)}\cdot\mathbf{E}^n=\varepsilon_0\left(\chi^{(1)}\cdot\mathbf{E}+\chi^{(2)}:(\mathbf{E}\otimes\mathbf{E})\,+\,...\right)
\\
\mathbf{D}(\mathbf{E})=\varepsilon_0\mathbf{E}+\mathbf{P}(\mathbf{E})=\varepsilon_0\left((\mathbf{1}+\chi^{(1)})\cdot\mathbf{E}+\chi^{(2)}:(\mathbf{E}\otimes\mathbf{E})\,+\,...\right)$$
where $\chi^{(n)}$ is the $n^\text{th}$ unitless electric susceptibility tensor (a tensor of rank $n+1$), and $\mathbf{1}$ is the $3\times3$ identity matrix.
In essence, the physical meaning is just a Taylor series of the matter field $\mathbf{P}(\mathbf{E})$. The linear term gives ordinary optics, and the quadratic and higher terms give rise to nonlinear optics.
When I learned nonlinear optics, I was initially confused and had the same questions as you have; as it turned out, the source of the confusion was actually not a question of physics, but rather was a problem with math: I didn't understand how Taylor series worked for vector functions of vector argument.

A: Think of the dipole moment as analogous to a extending/compressing a spring (or rubber band), vis a vis Hooke's Law
$$ X = \frac{1}{k} F $$
As such, $P$ is analogous to the spring displacement $X$, applied $E$ is analogous to force $F$ applied to the spring, and susceptibility $\chi$ is analogous to inverse spring constant $\frac{1}{k}$.  In our case,
$$\textbf{P} = \epsilon_0\chi \textbf{E}.$$
For rest of the discussion, I will ignore the vector nature of $\textbf{E}$ and $\textbf{P}$ and simplify to scalar $E$ and $P$, with unit vector implied.
Thinking of the physical spring for a moment, if you stretch it too much, it reaches a limit and the spring constant starts changing.  Another words, the spring "constant" $k$ is no longer constant and becomes a function of the displacement $X$, or alternatively, a function of force $F$.
For example, let us assume that spring "constant" can be approximated as so,
$$\frac{1}{k} = \frac{1}{k_1} + \frac{1}{k_2} F.$$
Then the displacement equation becomes
$$ X = \frac{1}{k_1} F + \frac{1}{k_2} F^2.$$
Notice that in the final form, we have a $F^2$ but this can be a bit confusing because one multiplicand of $F^2$ is specifically for describing how the spring constant changes, while the other multiplicand is specifically to determine displacement. A more clear (but mathematically excessive) way of writing it would be
$$ X = \frac{1}{k_1} F + \left(\frac{1}{k_2} F\right) F.$$
Now, consider our electric field case. In the same way a spring is limited in the displacement, an electric dipole is limited (by various mechanisms) in polarization.   In our case, our $\chi^{(1)}$ is equivalent to $\frac{1}{k_1}$, and $\chi^{(2)}$ to $\frac{1}{k_2}$, thus
$$\chi = \chi^{(1)} + \chi^{(2)} E.$$
And from that, we arrive at the familiar NL polarization (simplified) expression,
$$ P = \epsilon_0\chi^{(1)} E + \epsilon_0\chi^{(2)} E^2 $$
In the exotic case, where susceptibility of field in one direction (e.g. $E_x$) is affected by a field in another (e.g. $E_y$), we might get
$$ P_x = \epsilon_0\chi_{xx}^{(1)} E_x + \epsilon_0 \left(\chi_{xyx}^{(2)} E_y\right) E_x. $$
Here, polarization $P_x$ is created by presence of $E_x$, but the susceptibility is affected by the presence of $E_y.$  Nevertheless, this is lumped in (incorrectly, in my option) with the family of 2nd order nonlinear effects.
More complex susceptibility function require higher terms, causing higher order E field terms (e.g. $E^3$...) to appear.  Now, it is quite conceivable to instead describe nonlinear optics in terms of transcendental functions of E (e.g. tanh(E) or log(E) or sin(E) or whatever), but as @DumpsterDoofus notes, it has become de facto (for good reasons) to approximate the susceptibility as a Taylor expansion.


text:
Q: Total Number of $4$ Digit Codes with Repeated Digits Suppose I have a 4 digit code that I can make with the 10 digits, repetition allowed. I want to find the total number of codes that have repeated digits. The easiest way would be Total Possible Codes $-$ Non-repeating Digit Codes -> $10^4 - (10 \times 9 \times 8 \times 7)$.
But suppose I want to do a case by case basis looking for the codes with repeating digits. For codes with 2 repeating digits I first find total combinations of $2$ slots out of the $4$, assign them a digit, then assign the remaining two digits. I get : $4 \choose 2$ $(10 \times 9 \times 8)$
Similarly with 3 repeated digits I get $4 \choose 3$ $(10 \times 9)$ and 4 repeating digits $4 \choose 4$ (10). But adding these up gives a different result than doing it using the first method. Why is this? What am I doing wrong?

A: You overlooked codes with two different digits repeated twice, such as 1122. The number of these is $\binom{10}{2}\binom 42=270$. Adding this should balance the scales.


text:
Q: XML validation against XSD: schemaLocation value must have even number of URI's I have a blog.xml and a Blog.xsd to validate the XML file. I am using http://www.xmlvalidation.com/?L=0 to validate both files but I'm getting an error.
Can you kindly tell me whats wrong?
Error:

blog.xml:
http://pastebin.com/He3xCxxC (sorry had to post it to pastebin (Due to SO's word limit)
Blog.xsd:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="blog">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="post" maxOccurs="unbounded" minOccurs="0">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="ptitle"/>
              <xs:element type="xs:string" name="psubtitle"/>
              <xs:element type="xs:anyURI" name="image"/>
              <xs:element type="xs:string" name="author"/>
              <xs:element type="xs:string" name="date"/>
              <xs:element type="xs:string" name="par"/>
              <xs:element type="xs:anyURI" name="source"/>
              <xs:element type="xs:string" name="comments"/>
            </xs:sequence>
            <xs:attribute type="xs:byte" name="id" use="optional"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

A: You have not set the targetNamespace (ie "http://www.w3schools.com") of the schema.
<xs:schema attributeFormDefault="unqualified" targetNamespace="http://www.w3schools.com" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

And schemalocation must specify the namespace and the schema. This is why you must have an even number of elements in schemaLocation.
<a:blog xmlns:a="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com ./Blog.xsd">


text:
Q: Create combo box in python GTK 3.0 where the input of the first box changes the possible input choices for the second box I am looking to create a combo box in GTK where the user selected choice in the first box changes the choices available in the next boxes; ie if the first box contained manufacturers names, the next box would contain products of that manufacture, furthering that example if I selected bmw I could only select cars made by bmw. I know what the basic structure should look like, however I am not sure how to have the signals trigger one another. If someone could provide basic code or pseudo code that would be perfect .

A: The easiest solution would be to have one manufacturer model and many product models. When manufacturer is changed, combobox will emit "changed" signal. In it's handler you can set appropriate model to the second combobox using set_model() method.

A: You can find a simple example in 14.1. at provided link:
http://python-gtk-3-tutorial.readthedocs.io/en/latest/combobox.html


text:
Q: f-strings with variable number of parameters? I need to create messages of the kind Hi John, it's time to eat quantity_1 of food1, quantity_2 of food_2 ..., qunatity_n of food_n. For that I get pandas dataframes, that update every once in a while. For example the dataframes look sometimes like df1=
qantity,food
1,apple

and sometimes like df2=
quantity,food
1,apple
3,salads
2,carrots

I need with every new update to create out of the dataframe a string for a message. For df1 an f-string works neetly and for creating my desired message of Hi John, it's time to eat 1 apple. I can do:
f"Hi John, it's time to eat {df.quantity} {df1.food}

In the cases when I have something like df2, and I don't know explicitly how long df2 is, I would like to have a message of the kind Hi John, it's time to eat 1 apple, 3 salads, 2 carrots.
How can I create such a string? I thought of using the "splat" operator for something like join(*zip(df.quantity, df.food)), but I haven't figured it out. tnx

A: Try this:
result=','.join([str(i[0])+' '+i[1] for i in zip(df.quantity, df.food)])

print(result)

'1 apple, 2 salads, 3 carrots'

And you can add this to get the final result:
"Hi John, it's time to eat " + result

Hi John, it's time to eat 1 apple, 2 salads, 3 carrots

A: There are two ways to approach this.
The first option is to create a message column in the dataframe
df = pd.DataFrame(data={'quantity':  [1],'food': ['apple']})
df['message'] = df.apply(lambda x: f"Hi John, it's time to eat {x.quantity} {x.food}", axis = 1)
print(df['message'])

the second option is to get slice the dataframe object by index to create your messages outside of the dataframe
f"Hi John, it's time to eat {df.quantity[0]} {df.food[0]}"

to handle multiple records in the dataframe, you can iterate through the rows
"Hi John, it's time to eat " + ", ".join(list((f"{df.quantity[i]} {df.food[i]}" for i in df.index)))

A: Try this
df1 = pd.DataFrame({'size':['1','2'], 'Food':['apple', 'banana']})
l_1 = [x + '' + y for x, y in zip(df1['size'], df1['Food'])]
"Hi John, it's time to eat " + ", ".join(l_1)

A: import pandas as pd
df = pd.DataFrame([[1, 'apple'], [2, 'salads'], [5, 'carrots']], columns=['quantity','food'])
menu =  ', '.join(f"{quantity} {food}" for idx, (quantity, food) in df.iterrows())
print(f"Hi John, it's time to eat {menu}.")

output
Hi John, it's time to eat 1 apple, 2 salads, 5 carrots.
using package inflect you can do it with better grammar:
import inflect

p=inflect.engine()
menu = p.join([f"{quantity} {food}" for idx, (quantity, food) in df.iterrows()])
print(f"Hi John, it's time to eat {menu}.")

output:
Hi John, it's time to eat 1 apple, 2 salads, and 5 carrots.

inflect even can construct correct singular/plural form

A: I prefer to use str.format() for complex scenarios as it makes the code easier to read.
In this case:
import pandas as pd
df2=pd.DataFrame({'quantity':[1,3,2],'food':['apple','salads','carrots']})
def create_advice(df):
    s="Hi John, it's time to eat "+", ".join(['{} {}'.format(row['quantity'],row['food']) for index,row in df.iterrows()])+'.'
    return s

create_advice(df2)
>"Hi John, it's time to eat 1 apple, 3 salads, 2 carrots."

You might also want to modify the df slightly before creating the strings:
list_of_portioned_food=['salads']
df2['food']=df2.apply(lambda row: ('portions of ' if row['food'] in list_of_portioned_food else '')+row['food'],axis=1)
df2.iloc[len(df2)-1,1]='and '+str(df2.iloc[len(df2)-1,1])

applying the above function again:
create_advice(df2)
> "Hi John, it's time to eat 1 apple, 3 portions of salads, and 2 carrots."


text:
Q: Looping over list to delete items - unexpected behavior A simplified scenario that's not working as expected. I'm hoping someone can point out why.
nums = [0, 0, 4, 0]
new_list = nums
for i in range(len(nums)):
  if nums[i] !=0:
    break
  del new_list[0]
new_list

I'm trying to remove preceding zeroes. I expect the above loop to delete the first element of the list until it encounters a non-zero number, then break. It's only deleting the first zero, even though my del new_list[0] statement is in the loop.
Expected output: [4, 0]
Actual output: [0, 4, 0]

A: The assignment operator in python (as used in new_list = nums) does not create a new object but just assigns another name to the existing object. Any changes you make to nums will also affect new_list.
To create a new object, you can make a shallow copy instead:
new_list = nums.copy()

A: In python, assignment operator doesn't make you a new instance of your object, in your casenums. I suggest you to read about deep copy and shallow copy in python. As this article says

In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn't. It only creates a new variable that shares the reference of the original object. Sometimes a user wants to work with mutable objects, in order to do that user looks for a way to create "real copies" or "clones" of these objects. Or, sometimes a user wants copies that user can modify without automatically modifying the original at the same time, in order to do that we create copies of objects.

You can make a deep copy using the copy module.
import copy

nums = [0, 0, 4, 0]
new_list = copy.deepcopy(nums) # using deepcopy for deepcopy

A: nums = [0, 0, 4, 0]
new_list = nums # this refer to nums and when you change new_list, nums changes
# do following to make a copy.
new_list = nums[::]
for i in range(len(nums)):
  if nums[i] !=0:
    break
  del new_list[0]
new_list

Output
[4, 0]


text:
Q: How to run partimage after installation on Ubuntu 12.04 if it is not listed in Dash? I have Ubuntu 12.04 on a dual boot laptop with Windows Vista.
I installed partimage through the Software Centre and it says that the package is successfully installed, but the package is not shown in the list of installed software through Dash.
What can I do to get Dash to show partimage as an installed package?
If I can't get Dash to list the package, is there another way to run partimage?

A: Even if PartImage isn't in the Dash it can still be run. Open a Terminal and run PartImage from there:
partimage

The program should run.


text:
Q: API Gateway doesn't pass headers to Lambda I am trying to make a multipart http query through API Gateway to a Lambda. I have set the binary media type to 'multipart/form-data'. The issue is that I need to access the Content-Type header, so that I can parse the body correctly in my lambda logic.
But when I console log the lambda event, I can see that the Content-Type header is missing, even though I can see that it is well sent by my client.
Also, everything works perfectly in local with serverless-offline, without going through API Gateway.
So I'm guessing API Gateway does its own processing of my request and send a different version of it to my Lambda, with different headers.
How can I force API Gateway to pass this header to my Lambda ?
Thank you very much!

A: In the integration request try adding an HTTP Header Content-Type mapped from application/x-www-form-urlencoded.
Then add a mapping template for multipart/form-data
{
    "Content-Type" : "$input.params('Content-Type')",
    "body_base64" : "$util.base64Encode($input.body)"
}

If you are using an OpenAPI template to create the api with terraform or serverless then configure the x-amazon-apigateway-integration: node
requestTemplates:
  multipart/form-data: "{\n    \"Content-Type\"\
    \ : \"$input.params('Content-Type')\",\n    \"body_base64\" : \"$util.base64Encode($input.body)\"\
    \n}"
passthroughBehavior: "never"
type: "aws"


text:
Q: trouble running UIKit Catalog swift sample code I am trying to run the code from the following link:
https://developer.apple.com/documentation/uikit/mac_catalyst/uikit_catalog_creating_and_customizing_views_and_controls
However when I try to run the code, I am given an error that states, Ambiguous use of 'configurationPreferringMulticolor()'. How can I resolve this error and run the sample code? I have attached a screenshot of where the error occurs in the code. screenshot of error.
Any help is greatly appreciated.


text:
Q: Error during centOS 7 installation on physical server (anaconda 21.48.22.93-1 exception report)) I am installing centOS 7 minimal version on server using dvd disk, it has iso image. After choosing the language option it gives me the following error :
anaconda 21.48.22.93-1 exception report
Traceback (most recent call first):
File "/usr/lib/python2.7/site-packages/block/device.py", line 719, in get_map if compare_tables(map.table, self.rs.dmTable):
File "/usr/lib64/python2.7/site-packages/block/device.py", line 838, in active self.map.dev.mknod(self.prefix+self.name)
File "/usr/lib/python2.7/site-packages/blivet/devicetree.py", line 1768, in handleUdevDMRaidMemberFormat rs.activate(mknod=True)
file "/usr/lib/python2.7/site-packages/blivet/devicetree.py", line 1979, in handleUdevDeviceFormat seld.handleUdevDMRaidMemberFormat(info, device)
File "/usr/lib/python2.7/site-packages/blivet/devicetree.py", line 1285, in addUdevDevice serlf.handleUdevDeviceFormat(info, device)
File "/usr/lib7python2.7/site-packages/blivet/devicetree.py", line 2295, in _populate self.addUdevDevice(dev)
file "/usr/lib/python2.7/site-packages/blivet/devicetree.py", line 2228, in populate self._populate()
File "7usr/lib/python2.7/site-packages/blivet/__init__py", line 489, in reset self.devicetree.populate(cleanupOnly=cleanupOnly)
File "/usr/lib/python2.7/site-packages/blivet/__init__py",line 184, in storagelnitialize storage.reset()
File "/usr/lib64/python2.7/threading.py", line 764, in run self.__target(*self.__args, **self.__kwargs)
File"/usr/lib64/python2.7/site-packages/anaconda/threads.py", line 227, in run threading.Thread.run(self, *args, **kwargs)
File"/usr/lib64/python2.7/site-packages/anaconda/threads.py", line 112, in wait self.raise_if_error(name)
File"/usr/lib64/python2.7/site-packages/anaconda/timezone.py", line 75, in time_initialize threadMgr.wait(THREAD_STORAGE)
File"/usr/lib64/python2.7/threading.py", line 764, in run self.__target(*self.__args,**self.__kwargs)
File"/usr/lib64/python2.7/site-packages/pythonanaconda/threads.py" line 227, in run threading.Thread.run(self,*args,**kwargs)
ValueError: invalid map 'nglish (the divide/multiply keys toggle the layout)'

A: The problem can rely in 3 different scenario:

*

*CentOS on VirtualBox: You need to create Root Password and User Creation in the first 30 seconds before the installer starts to install stuff. This might be a bug (CentOS 8). Setup the User Creation and then the Root Password, you will see the installer will go on without problems

*Pre-existing data on the HD: https://bugzilla.redhat.com/show_bug.cgi?id=1441891
In this case first boot in rescue mode then run the command dmraid -r -E /dev/sd<x>


text:
Q: JTable to Excel Apache POI подключен, файл и лист создать получается, но как вывести мою JTable в Excel?
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("mySheet");

        for (int i = 0; i < table.getModel().getRowCount(); i++) {
            row = sheet.createRow(i + 1);
            for (int j = 0; j < table.getModel().getColumnCount(); j++) {
                String type = table.getModel().getColumnClass(j).getName();
                cell = row.createCell(j);

    }
        }
        // fos;
        try (FileOutputStream fos = new FileOutputStream("mY.xls")) {

            wb.write(fos);
            fos.close();
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

Таблица:
static String[] columnNames = {"Столбец",
             "Столбец",
             "Столбец",
             "Столбец",
             "Столбец",
             "Столбец"
   };

   static String[][] data = {
             {"информация", "информация", "информация", "информация", "информация", "информация"},
            {"информация", "информация", "информация", "информация", "информация", "информация"},
{"информация", "информация", "информация", "информация", "информация", "информация"},
   };

JTable table = new JTable(Tables.data, Tables.columnNames);
JScrollPane scrollPane = new JScrollPane(table);

A: cell.setCellValue((String) table.getModel().getValueAt(i, j));

В гайде же все написано: https://poi.apache.org/spreadsheet/quick-guide.html


text:
Q: Авторизация на php Здравствуйте нужна помощь.
Есть у меня файлик с формой авторизации и выглядит он вот так.
<form id="login" method="post" action="login.php">
Забыли?
<input type="text" name="loginEmail" id="loginEmail" value="Email" />
<input type="password" name="loginPass" id="loginPass" value="pass" />
<input type="submit" name="submit" value="Login" />
</form>

Вопрос так ли я прикрепил php файл login.php?
И второй вопрос.
Есть файлик login.php
// Страница авторизации

# Функция для генерации случайной строки
function generateCode($length=6) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHI JKLMNOPRQSTUVWXYZ0123456789";
    $code = "";
    $clen = strlen($chars) - 1;
    while (strlen($code) < $length) {
            $code .= $chars[mt_rand(0,$clen)];
    }
    return $code;
}

# Соединямся с БД
mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("testsite");

if(isset($_POST['submit']))
{
    # Вытаскиваем из БД запись, у которой логин равняеться введенному
    $query = mysql_query("SELECT user_id, user_password FROM users WHERE user_login='".mysql_real_escape_string($_POST['login'])."' LIMIT 1");
    $data = mysql_fetch_assoc($query);

    # Сравниваем пароли
    if($data['user_password'] === md5(md5($_POST['password'])))
    {
        # Генерируем случайное число и шифруем его
        $hash = md5(generateCode(10));

        # Записываем в БД новый хеш авторизации и IP
        mysql_query("UPDATE users SET user_hash='".$hash."' ".$insip." WHERE user_id='".$data['user_id']."'");

        # Ставим куки
        setcookie("id", $data['user_id'], time()+60*60*24*30);
        setcookie("hash", $hash, time()+60*60*24*30);

        # Переадресовываем браузер на страницу проверки нашего скрипта
        header("Location: check.php"); exit();
    }
    else
    {
        print "Вы ввели неправильный логин/пароль";
    }
}

Правильно ли все написано? Пока только учусь.
A: Нашел несколько недоработок и одну ошибку.
HTML

*

*Если у Вас не подключен javascript к
   форме, использование id="login" и других id не
   обязательно, скорее лишнее;

*Имя полей в html должно соответствовать с ключем массива $_POST['key'] в PHP.

PHP

*

*Переменные $_POST['login'] и $_POST['password'], будут пустые, т.е равны значению False, так как у Вас другие имена в html форме;

*Функцию generateCode - можно заменить на $hash = md5(microtime()); или rand()...

*Использование двойного мд5, возможно ошибка ` if($data['user_password'] === md5(md5($_POST['password'])))ёж

*Лучше посчитать сразу, чем давать лишнию нагрузку скрипта. Нагрузка будет не заметна, но все-же (Это так придираюсь) setcookie("hash", $hash, time()+60*60*24*30);

*Использование exit в фрагменте header("Location: check.php"); exit(); - бессмысленно;

*Лучше использовать для вывода текста оператор echo чем print. По оптимизации echo быстрее;

*
Использовать условия такие как у Вас бывают не очень удобные. Лучше использовать так:
if(empty($_POST['submit']))
   exit("Вы ввели неправильный логин/пароль");
// дальше код $query = mysql_query...


text:
Q: Empty String Mystery I am publicly declaring a variable called currentDocName in my View class.
CString currentDocName = (CString)"Emergence1";

Later on in that same class I call an OutputDebugString with currentDocName as its input. However, it appears to be an empty string. How could this be? Nowwhere else am I initialising currentDocName to an empty string.

A: That line of code declares a local variable, not a public variable: It will be destroyed when the enclosing function returns. Does "later on in the same class" mean in some other class function?


text:
Q: I worked on a private repo in GitHub then made it public. Can I make my activity visible? I had a private repo for 6 months that I worked on. Today I finally made it public after submitting a paper. Is it possible to make the activity (those green square) visible? I tried clicking on contribution setting and got the message Visitors will now see your public and anonymized private contributions, but the activity still doesn't show.
Update 1:
I noticed that only changes I did on GitHub (the website rather than pushing code from my machine) were recorded. That is, only the readme file shows as I often updated it on the website.
Update 2:
I ran git --no-pager log -s --format="%ae" to see which emails were used for the commits and got the following:
Some emails are the primary email under GitHub, some are of the form 43555163+Penguin@users.noreply.github.com, some are Penguin@Penguin-MacBook-Pro.local, some are Penguin@econ2-204-32-dhcp.int.university_name.edu.
Also, as I mentioned in one of the comments below, if I go to my repo and specifically look at commits I can see something like: Penguin authored and Penguin committed on May 27  1 parent 1d71ac3 commit cb95c2870de67383ee653849b4c7b40a062f5fd3. But this does not show on my activity.
Lastly, some comments mentioned creating a new repo on GitHub and pushing my previous commits (after filtering the emails somehow which I didn't quite understand). However, I already have several Stargazers on this repo and would like to keep them. By making a new repo I believe these will disappear.
Update 3:
I used git filter-repo to change all the emails to my primary email and now all my previous commits emails appear to be my primary email when I call git --no-pager log -s --format="%ae". However, I still don't see the activity showing. For example, if I go to my repo I can see that one of the commits says Penguin authored and Penguin committed on Apr 8, but this doesn't show in the activity.

A:
I noticed that only changes I did on github (the website rather than pushing code from my machine) were recorded.

That means you need to check, from within your local folder of your cloned repository:
git config user.name
git config user.email

Make sure those match your GitHub user account, and GitHub user email.
Then make some new commits, and push: see if the activity is reflected then.
The OP Penguin confirms in the comments:

Looks like the email wasn't the same (for some reason the email was empty in my local machine).
Now I can push commits through my local machine and they appear as activities.
Is there a way to show my previous commits though?

For that, you need to rewrite your past commit, and force push the result (which is OK if you are the only one working on that repository).
See How to switch GitHub account and retrospectively update commit history? for an example, using git filter-repo (with a mailmap map), or git filter-repo --commit-callback.

Which I don't quite understand. If I'll create a new repo and push everything to it I will lose the stargazers

You would not create a new remote repository, only clone it in a new local cloned repo, and apply git filter-repo there.
Once the local history matches what you expect in terms of commit authorship, you force push back to the original remote repository (with all its Stargazers).
git push --force # at least for the main/master branch

From the discussion

I think git push --force worked. I still see the commits on the commit page as not verified, but the activities appear now.
Is that a problem that they are not verified?
And now it appears that whenever I try to push a commit from my local machine I need to authenticate for some reason

The remote authentication is different from commit authorship and verification.
The verified aspect is due to a lack of commit signature, as mentioned here.
You would need to resign your commits locally (still using git filter-repo), and force push them again.
Once signed (with a key registered to your GitHub profile), they would appear as verified.
The git push with authentication depends on which protocol you are using (HTTPS or SSH), as recently (Nov. 2021 at the time of writing) explained by torek in "Easy way to switch between accounts on git in the terminal on Windows?".

A: This likely has to with you not having signed off the commits with GPG -
which leads to commits, which are not labeled as (identity) "verified".
The documentation also doesn't cover this case, at least not in detail ... while the most easy might be to create a new one repository, add it as remote and then you can push all the changes. And even when the edits you've made are not publicly visible, GitHub still is your third party witness.

A: Contributions should still be shown in that case. Here are some of the reasons your contributions might not be being shown:

*

*GitHub isn't aware of the email address you used in your commit messages

*The commit wasn't made in the default or gh-pages branch

*The repo is a forked repo, not a standalone repo
GitHub also mentions that it will not show commits that were made less than 24 hours ago, so it seems like they have some sort of caching mechanism going on with their contribution graph. It may help to wait 24 hours since you made the repo public, to ensure that cache has a chance to roll over.


text:
Q: Riemann sum estimate of Cauchy residue formula Let $e(k) = \exp \left(\frac{2 \pi i k}{N}\right)$ be a root of unity.
I wanted to numerically verify the Cauchy residue formula in Mathematica.
$$ \lim_{N \to \infty}\frac{1}{N}\sum_{k=0}^{N-1} \frac{e(k) }{e(k) - a} = \frac{1}{2\pi i} \oint_{|z|=1}  \frac{dz}{z - a} = \mathbf{1}( |a| < 1)$$
This computes the winding number of the curve $|z|=1$ (counter-clockwise) around $a \in \mathbb{C}$.
Can this Riemann sum be evaluated exactly?  I would like to know the leading-order correction of the Riemann sum to the integral .

A: Denote the lhs as $f_N(a)$. It can be regarded as a rational function of complex variable $a$. It's straightforward to check that $f_N(a e(i))=f_N(a)$, $i=0,\ldots,N-1$. Which means that $f_N$ is a rational function of $a^N$. From the other hand $\lim_{a\to\infty}f_N(a)=0\;$. This leaves the only possibility
$$
f_N(a)=\frac c{\prod_{i=0}^{N-1}(e(i)-a)}=\frac c{1-a^N}.
$$
Plugging $a=0$ gives $c=1$ so $f_N(a)=\frac1{1-a^N}$. Thus the difference between the sum and the integral is $f_N(a)-1=\frac {a^N}{1-a^N}$.


text:
Q: How to get Mod_pagespeed to output compressed (gzip) css? Ubuntu 14.04
Apache 2.4.7
php-FPM 5.5.9
Using latest stable Pagespeed Module for Apache (1.9.32.3-4448).
I'm in the process of optimizing a WordPress website for speed (bandwidth and rendering).
Mod Deflate is set up.
A plugin (Better Wordpress Minify) compresses and combines all css files into one (thus reducing the number of requests).
With Pagespeed switched off, if I check the produced link (using FeedTheBot) it confirms that the content is compressed using gzip.
But If Pagespeed is switched on, it shows Gzip is not working. Using PageSpeed Insight (chrome extension) confirms this.
Here is what I've tried:

*

*Adding to /etc/apache2/mods-available/pagespeed.conf

 ModPagespeedFetchWithGzip on
 SetOutputFilter DEFLATE

*check that mod Deflate is available and enabled (it appears in the list produced by apache2ctl -t -D DUMP_MODULES). The fact that if pagespeed is switched off, it works for the combined css file is another proof.

Do you have an explanation ?

A: This is the way to enable mod_deflate for html,xml,js,css,php files :
# MOD_DEFLATE COMPRESSION
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css application/x-javascript application/x-httpd-php
DeflateCompressionLevel 9

# This part is optional, it is used for really old browser >

# DEFLATE NOT COMPATIBLE BROWERS
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

# SET VAR
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip


text:
Q: Triangulation Algorithm I want to track device using triangulation algorithm. It works fine with 3 BTS stations at 3 different locations. What should I do if only 1 or 2 BTS exists.

A: With less than 3 sources, you cannot identify the location uniquely. However, if you can put some constraints on the speed at which the device can move, you can use the previous location and dead reckoning to guess the current one.
See also the answer to this question: How to perform trilateration using 3 lat/lon points without distances?


text:
Q: Exercise on linear maps with a nilpotent one sorry for asking to help me with this trivial problem. Unfortunately I'm in a very bad shape with linear algebra, being this the fourth exercise I'm not able to solve.
I need some suggestion.
$f,g:V\to V$ linear maps, with $f$ being nilpotent and
$fg-gf=f$
Prove that $\ker(f)$ is invariant for $g$.
I think I have to prove that $g(\ker(f))\subseteq\ker(f)$.
I know that if $f$ is nilpotent, then there exists a $k>1$ for which $f^k=0$, and, moreover $f$ has the only eigenvalue $\lambda=0$.
This problem shouldn't be hard to solve. In your opinion, what do I have to revise to learn making this exercises? Maybe I should start with something simpler?
Thank you.

A: Let $x$ be an element of $\ker(f)$. Then
$$
0 = f(x) = (fg - gf)(x)
$$
implies (by linearity)
$$
f(g(x)) = g(f(x)) = g(0) = 0
$$
i.e. $g(x) \in \ker(f)$. Since the choice of $x$ was arbitrary, this implies that $g(\ker(f)) \subseteq \ker(f)$.

All you need to know to solve this is what the kernel of a linear map is and that a linear map always sends $0$ to $0$. Then you observe that $f$ and $g$ commute (i.e. $f \circ g = g \circ f$) on $\ker(f)$.


text:
Q: Create PDF file using PHP I need to create a PDF or Word file filled with contents from my database. Then the customer need to download that file. All this should happend when customer click on link.
Anyone have any idea?

A: I have used TCPDF with much success to generate PDF files programatically using PHP.
And to generate word documents: http://www.phpdocx.com/ (this is a paid solution).

A: Try TCPDF
http://www.tcpdf.org/
But google could have told you that

A: dompdf is your best bet

A: You can use for example: html2pdf. It's heavy library but seems to have very advanced functionality.
dompdf is a light library but it lacks a bit unicode support.
If you have access to the server maybe it would be better to install the PECL PDF library. But I never used so cannot tell you if it's good

A: Got one more: FPDF
Hello World:
<?php
 require('fpdf.php');

 $pdf = new FPDF();
 $pdf->AddPage();
 $pdf->SetFont('Arial','B',16);
 $pdf->Cell(40,10,'Hello World!');
 $pdf->Output();
?>

Taken from: FPDF Tutorial 1

A: wkthmltopdf is really THE ONLY solution that worked for me that could produce what I call acceptable results. Still, some minor modifications to the CSS had to be made, however, it worked really well when it comes to rendering the content. All the other packages are really only suitable if you have a rather simply document with one basic table etc. No chance to get them to produce fair results on complex docs with design elements, css, multiple overlapping images etc. If complex documents are in game - do not spend the time (like I did) - go straight to wkhtmltopdf.
Take a look at my own question and solution in this post HTML2PDF in PHP - convert utilities & scripts - examples & demos


text:
Q: Starting new activity gives: Class not found when unmarshalling I'm facing a problem when passing a list of parcelable objects to the intent of one new activity.
Here's what I do:
Intent intent = new Intent(context, CurriculumCorsesActivity.class);
intent.setExtrasClassLoader(CurriculumCourseCard.class.getClassLoader());
intent.putParcelableArrayListExtra("courses", card.getCourses());
context.startActivity(intent);

And when I call the startActivity I get the following error:
E/Parcel﹕ Class not found when unmarshalling: pt.tecnico.fenixmobile.person.CurriculumCourseCard, e: java.lang.ClassNotFoundException: pt.tecnico.fenixmobile.person.CurriculumCourseCard

CurriculumCourseCard implements the Parcelable interface. Here's is the implementation:
public class CurriculumCourseCard implements Serializable, Parcelable{
private static final long serialVersionUID = 765578940083L;
private String courseName;
private String finalGrade;
private String ects;

public CurriculumCourseCard(Parcel in) {
    this.courseName = in.readString();
    this.finalGrade = in.readString();
    this.ects = in.readString();
}

public String getCourseName() {
    return courseName;
}

public String getFinalGrade() {
    return finalGrade;
}

public String getEcts() {
    return ects;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(this.courseName);
    parcel.writeString(this.finalGrade);
    parcel.writeString(this.ects);
}

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
    public CurriculumCourseCard createFromParcel(Parcel in) {
        return new CurriculumCourseCard(in);
    }

    public CurriculumCourseCard[] newArray(int size) {
        return new CurriculumCourseCard[size];
    }
};}

And this is how I'm getting the list in the new activity:
Intent intent = getIntent();
intent.setExtrasClassLoader(CurriculumCourseCard.class.getClassLoader());
ArrayList<CurriculumCourseCard> courses = intent.getParcelableArrayListExtra("courses");

In the new activity I see as much items as there are in the list, but no content at all. And the only error is the one described before.
Hope you can help me.


text:
Q: PHP How to descending sort tree child's by param I have  a tree like this
array(
array('name'=>'n1', 'timestamp'=>1000, 'children'=> array()),
array('name'=>'n2', 'timestamp'=>2000, 'children'=> array(
    array('name'=>'n3', 'timestamp'=>3000, 'children'=> array()),
    array('name'=>'n4', 'timestamp'=>4000, 'children'=> array(
        array('name'=>'n5', 'timestamp'=>4000, 'children'=> array()),
        array('name'=>'n6', 'timestamp'=>3000, 'children'=> array())
    )),
)),
array('name'=>'n7', 'timestamp'=>3000, 'children'=> array())
)

-n1
-n2
    -n3
    -n4
        -n5
        -n6
-n7

and I would like to sort it by timestamp on each level DESC, so in result will be
-n7
-n2
    -n4
        -n5
        -n6
    -n3
-n1

A: function timestamp_sort(&$a, &$b)
{
  if (!empty($a['children']))
    usort($a['children'], 'timestamp_sort');
  if ($a['timestamp'] == $b['timestamp'])
    return 0;
  return $a['timestamp'] < $b['timestamp'] ? 1 : -1;
}

usort($tree, 'timestamp_sort');

I'm assuming you're familiar with the usort function - if not, you should read the documentation.
Beyond the basic usage of usort we're doing 2 additional things:

*

*Sorting recursively - the timestamp_sort function calls itself when the array contains items that themselves need to be sorted.

*Passing the parameters to the function by reference - that way when we do sort the child arrays, our changes update the original array. Again, if you're not familiar with references, you should read up on it.


text:
Q: MySQL: Selecting rows ordered by character count In MySQL, how can I order my query by character count?

A: Try using the LENGTH function:
SELECT * FROM table ORDER BY LENGTH(myField);

Depending on what you're doing, you might want to use CHAR_LENGTH instead:

A multi-byte character counts as a single character. This means that for a string containing five two-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.

If you don't know what that means, you probably want LENGTH.


text:
Q: KendoUi list view "press to load more" not working using MVVM style I have a list view that is created using MVVM style. I am trying to use the "Press to load more" function from Kendoui mobile. Here is my full code on Jsbin.com Please help me. http://jsbin.com/OTInERo/3/edit

A: Try removing the inset style.   The documentation states that grouping is not supported for 'press to load more' but in my experience I think the inset style breaks it too, certainly using MVC wrappers on the latest build it does.  I'm going to let them know.


text:
Q: Правила перезаписи RewriteRule Здрaвствуйте. Можете объяснить, как работает RewriteRule в данном примере? Представим, что есть WordPress с включенным ЧПУ и страницей с адресом example.com/privet
RewriteEngine On
RewriteBase /

<IfModule mod_rewrite.c>
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Допустим, мы заходим по адресу example.com/privet
Вопрос: как для сервера будет выглядеть адрес страницы example.com/privet после первого прохода по правилам перезаписи?
Правильно ли я понял, что любой существующий адрес после первого прохода преобразуется в example.com/index.php?

A:
Можете объяснить, как работает RewriteRule в данном примере?

Эти правила означают буквально следующее: если по указанному адресу не обнаружен физический каталог или файл, то запрашивается index.php в корне сайта.
Далее в работу вступают подключаемые файлы и, в соответствии с настройками ЧПУ, роутинг пытается отдать релевантную страницу.


text:
Q: How to combine output of netsh wlan show networks | findstr /L /I "SSID authentication"? Batch script:
for /f "tokens=2*delims=: " %%i in ('netsh wlan show networks^|find /i "SSID"') do ( echo %%i.%%j )
for /f "tokens=2*delims=: " %%i in ('netsh wlan show networks^|find /i "authentication"') DO (echo %%i )

I need output like this:
1. SSIDname1 : WPA2-personal
2. SSIDname2 : Open
3. ....

I have tried this way but failed:
for /f "tokens=2*delims=: " %%a in ('netsh wlan show networks^|find /i "authentication"') do (
    for /f "tokens=2*delims=: " %%i in ('netsh wlan show networks^|find /i "SSID"') do (
        echo %%i.%%j = %%a))

A: Here's a complete batch file solution, to meet the requirements at the time of posting.
@Echo Off
SetLocal DisableDelayedExpansion
Set "#=0"
For /F "Tokens=1* Delims=:" %%G In (
    '^""%__AppDir__%netsh.exe" WLAN Show Networks 2^> NUL ^|^
     "%__AppDir__%findstr.exe" "^SSID\> \<Authentication\>"^"'
) Do Set "i=%%G" & For /F "Tokens=*" %%I In ("%%H") Do (Set /A # %%= 2
    SetLocal EnableDelayedExpansion
    Set "i=!i:~,-1!. " & If !#! Equ 0 (If "%%I"=="" (
            Set /P "_=!i:* =!*Cloaked*: "<NUL) Else Set /P "_=!i:* =!%%I: "<NUL
        ) Else Echo !_!%%I
    EndLocal & Set /A # += 1)
Pause

As you've made no attempt at the task yourself, there will be no explanation of the provided code, and no modifications will be made to it, should you decide to modify your question, or requirements, after its submission.


text:
Q: What is the difference between a definition and an equivalence class? In what way is 'the definition of $x$ is $y$' ($x:=y$) not the same as '$x$ is equivalent to $y$' ($x=y$)? I can find no justification for making the distinction aside from 'it feels right'. It seems that every property of $:=$ is also a property of $=$ and that neither possesses a property that the other does not.
Furthermore, trying to casually force a distinction either renders one relation meaningless, with the other assuming the meaning of 'equality', or leads to glaringly obvious contradictions (ex $1:=S(0)\land S(0):\neq1\implies 1\in\Bbb{N}\land 1\notin\Bbb{N}$ using the Peano axioms).
Is there any objective distinction between a term and its definition (without explicit typing)?
I know its a bit (okay, extremely) pedantic to insist on a formal distinction between the definition of an object and the equivalence class to which that object belongs, but making this distinction effectively sets the limits on the definability of objects within a theory.

Note: the definition of an object is an equivalence class in the sense that a definition is specified via the conjunction of a sequence of formulae $(\Phi_i)_{i\in I}$, and the collection of objects $X=\{x\mid\bigwedge_{i\in I}\Phi_i(x)\}$ is an equivalence class since the relation $x\sim y\iff \left(\bigwedge_{i\in I}\Phi_i(x)\right)\land\left(\bigwedge_{i\in I}\Phi_i(y)\right) \iff x\in X\land y\in X$ is an equivalence relation. There are more technical details regarding the nature of this relation depending on whether or not a universe of discourse has been specified, but that's another thing entirely.

A: Equality, in many system and particularly for first-order logic with equality, is a relation of the logic. Most logical systems don't have a mechanism for making a definition. It simply makes no sense to say $(1:=S(0))\land P$ in these systems. A definition isn't a claim. It's not a statement that has a truth value.
So, not only are equality and definition not the same, they aren't even the same sort of thing. The most common way to handle definitions is meta-logically and informally. A definition like $1:=S(0)$ is an instruction to you, as the reader, to mentally replace $1$ with $S(0)$ everywhere you see it. You then trivially get $1=S(0)$ be reflexivity, because this really means $S(0)=S(0)$.
There are several ways of formalizing the notion of definitions. The typical way would be an extension by definition. For this perspective, a (meta-logical) definition like $1:=S(0)$ means: "Add the constant $1$ and the axiom $1=S(0)$ to the current theory, then continue with this new theory." Note how operational this is. It's instruction to create a new theory. "Add the constant $1$ and the axiom $1=S(0)$ to the current theory, then continue with this new theory," is not a statement that is true or false.
Some logical systems have an internal mechanism for making definitions. One example is the system used by Coq. The $\delta$-reductions do a formal version of the "mental replacement" described earlier. To over-simplify, it basically states that when you are in a context with a definition like $1:=S(0)$, then $1$ reduces to $S(0)$. The typing judgment is (supposed to be) sensitive only to normal forms of the reduction relation. There are constraints on the rules that introduce definitions to avoid (or clearly define the behavior of) multiple, potentially inconsistent definitions.

A: The notion of equality in mathematics that you've touched upon is something very deep.
Every axiomatic system in mathematics (that I am aware of) has some way of imbuing the canonical $=$ sign (if there even is a canonical notion of equality, which there sometimes is not) with some definitional value that is distinguished from just-any-other equivalence class defined over a structure.
In most (all?) versions of set theory, two sets are equal in the purest sense if they contain the same elements, and the elements of a set themselves are also just composed out of smaller sets (where axiomatically we only assume the existence of the empty set and a few ways of constructing new sets out of that) so all of the equality follows this same definition (in some sense, it reduces to being able to compare the empty set to any other set), whereas the same cannot be said of just any arbitrary equivalence relation over a set (although sometimes the equivalence of cosets under a quotient can confuse this).
If you're partial to constructive mathematics, then in certain forms of the calculus of inductive constructions, equality is just another inductive data type with nothing particularly special about it. Depending on the exact implementation of your type system though, you could end up with a definition of equality that basically boils down to two things having the same data representation on the computer. Or you could just as well come up with a very different kind of equality.
The real answer is that there are many different takes on this topic under many different systems, and to understand some of the variety involved I can only recommend checking out some type theory, axiomatic set theory, and category theory. This is a very good question, though, and one I wish I had a better answer for.


text:
Q: How should a Task signal a Windows service shutdown correctly? I'm working on a bug for a Windows service. The service uses a field to track a reference to a single Task. OnStart, the task executes a single method. The method has a loop inside it and calls a database on a configurable interval to monitor the work another system is doing.
protected override void OnStart(string[] args)
{
    _processorTask = Task.Run(() => StartProcessor());
}

We've occasionally had an issue where the Task dies and logs the exception just fine, but the existing plumbing wasn't telling the service to stop, so our service monitors didn't know anything was wrong.
At first, I tried to add just add a call to Stop().
private void StartProcessor()
{
    var processor = new PEMonitoringProcessor(_tokenSource.Token);

    try
    {
        // The process loop is in the function. If this method exits, good or bad, the service should stop.
        processor.ProcessRun();
    }
    catch (Exception ex)
    {
        // An exception caught here is most likely fatal. Log the ex and start the service shutdown.
        if (log.IsFatalEnabled) { log.Fatal("A fatal error has occurred.", ex); };
    }
    finally
    {
        Stop();
    }
}

However, one of my fellow devs noticed in the OnStop method that a token is used to signal the Task to stop and then it waits. If the Task calls Stop and waits for Stop to return and OnStop is waiting for the Task to end, that does not bode well for this code.
protected override void OnStop()
{
    _tokenSource.Cancel();

    try
    {
        _processorTask.Wait();
    }
    // logging & clean-up...
}

I considered a separate Task that doesn't get waited on by OnStop that checks the status of the first and calls Stop if the first Task is Completed, Faulted, etc., but that seemed a touch weird. I also considered raising an Event and trying something like BeginInvoke.
Intentionally stopping the service works fine because the OnStop signals via Token that a shutdown is happening. I'm trying to cover the possibility that the Task method returns or throws unexpectedly and I want the service to stop instead of becoming a zombie.

A: The most straightforward way I see is something like this:
protected override void OnStart(string[] args) {
    _processorTask = Task.Run(() => StartProcessor());
    _processorTask.ContinueWith(x => {
        // x.Exception contains exception if any, maybe log it here
        Stop();
    }, TaskContinuationOptions.NotOnCanceled);
}

protected override void OnStop() {
    //or !_processorTask.IsCompleted && !_processorTask.IsCanceled && !_processorTask.IsFaulted
    if (_processorTask.Status == TaskStatus.Running) {
        // only cancel and wait if still running. Won't be the case if service is stopping from ContinueWith above
        _tokenSource.Cancel();
        _processorTask.Wait();
    }
}

Alternative way to do the same:
protected override async void OnStart(string[] args) {
    _processorTask = Task.Run(() => StartProcessor());
    bool cancelled = false;
    try {
        await _processorTask;
    }
    catch (OperationCanceledException) {
        // cancelled
        cancelled = true;
    }
    catch (Exception ex) {
        // log it?
    }

    if (!cancelled)
        Stop();
}

// OnStop stays the same


text:
Q: Why this is true?$\exists x \in U, [P(x) \land Q(x)] \Leftrightarrow [(\exists x \in U, P(x)) \land (\exists x \in U, Q(x))]$ $$
  [\exists x \in U, P(x) \land Q(x)]   \Leftrightarrow [(\exists x \in U, P(x)) \land (\exists x \in U, Q(x))]
$$

A: This is false, its like saying there is someone who is the president of America and there is someone who is president of France, but to say there is someone who is president of both America and France is quite a different thing.


text:
Q: JavaScript alert does not work correctly with div tag There are 16 boxes in html.

I want to write js code that will do following:
When I click on any box, it will alert it's order number from 1 to 16.
There is my js code below:

But every time it alerts 16.
What is the problem?
Could you help me, please?

A: Using the classical IIFE: Immediately Invoked Function Expression you can write:

var boxArray = document.getElementsByClassName("box");
for (var i = 0; i < boxArray.length; i++) {
  boxArray[i].onclick = (function (i) {
    return function (e) {
      var say = function (i) {
        alert(i);
      };
      say(i);
    };
  })(i);
}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

A: This has to do with javascript's scope. i is outside the scope of the for loop because you used var, so when you do alert(i), it takes the value that i is left with after the loop (since the loop has already run).
Change your for loop from
for (var i = 0; i < boxArray.length; i++)

to
for (let i = 0; i < boxArray.length; i++)

And it should fix your problem.

A: You can use addEventListener with a local declared variable, like this

var boxArray = document.getElementsByClassName("box");
for (var i = 0; i < boxArray.length; i++) {
  boxArray[i].addEventListener('click', (function(e) {
    var num = i;
    return function() {
      alert(num);
    }
  })());
}

1

2

3

4

5

6

7

8

A: You can do this so much simpler if you use jQuery's .index()
It's as simple as doing this:
$(".box").click(function(){

  var i = $(this).index();
  alert(i);

});

DEMO: http://jsbin.com/zoxirafufo/edit?html,js,console,output


text:
Q: ggplot2: combine fill and alpha legends There are many questions out there pertaining to this topic, but none of the answers I have tried have worked for me so far.
I have a plot that is a heatmap with fill and alpha mapped to different values, i.e. different variables in my data create different colors and alpha values. I want to get a finished product here to see if this figure is worthwhile, so let's not discuss whether this is a good idea at the moment.
What I want to do is combine my fill and alpha legend such that I have the four different transparencies of blue, the four different transparencies of red, and for yellow. I can get those legends separately, or just one of them, but not two in one.
My best guess for code thus far has been
dummy <- data.frame(model=c(rep("X",23),rep("Y",23)),
                    longvarname=rep(c("CBH","NDMI","CovType","CH","CBD","NDVI_NF_750","Slope","TPI_Valley_1200", "TPI_Ridge_1200",
                                      "TPI_Ridge_100","TPI_Valley_100", "TSHarv","Treat","RxBurn",
                                      "TSTreat","TSRx","Deficit","SpecHumid","MaxRH","MinTemp","MaxTemp", "MaxGustDir", "MaxGustSpd"),2),
                    vargrp=rep(c(rep("Veg",6), rep("Topo",5), rep("Mgmt",5),rep("Clim",7)),2),
                    value=runif(46, min=0, max=1),
                    binary_slope=sample(c("negative","positive", "zero"), 46, replace=TRUE))

ggplot(dummy, aes(x=model, y=longvarname)) +
  geom_tile(aes(fill=binary_slope, alpha=value))+
  scale_alpha_binned(breaks=c(0.4, 0.6, 0.8, 1))+
  facet_grid(vargrp~., scales='free_y', space="free_y")+
  xlab("Model")+
  ylab("Variable")+
  scale_fill_manual(values=c("midnightblue","yellow1","red4"))+
  # guides(fill=guide_legend(override.aes = list(fill=c(rep("#191970",4),
  #                                                     rep("#FFEA00",4),
  #                                                     rep("#8b0000",4)),
  #                                              alpha=rep(c(0.4,0.6,0.8,1),3))))+
  theme(panel.background = element_blank(),
        axis.text.x = element_text(angle = 45, hjust=1),
        strip.text.y = element_blank(),
        axis.ticks = element_blank())

The above code produces both legends which you can see in the example I attached. If you uncomment the guides() lines, the error I am getting is Error in [[<-.data.frame(*tmp*, i, value = c("#191970", "#191970",  :
replacement has 12 rows, data has 3.
But most of my efforts have just resulted in only the fill legend at alpha=1. Another thought I had which I thought might get me there was in guides(), putting the alpha hex codes in front of each color hex code and then making alpha guide = "none", but no dice.
Thanks very much for your help!

A: Instead of making use of both fill and alpha one option would be to make use of just fill like so:

*

*Add a column with your desired fill colors to your dataset using e.g. a left_join.

*Manually compute your alpha levels using e.g. cut.

*Adjust the transparency of th colors according to the alpha values using colorspace::adjust_transparency

*Map the resulting colors on the fill aes and make use of scale_fill_identity. Add guide=guide_legend to get a legend.

library(ggplot2)
library(dplyr)
library(colorspace)

cols <- c(negative = "midnightblue", positive = "yellow1", zero = "red4")
cols <- tibble::enframe(cols, name = "binary_slope", value = "fill")

dummy <- left_join(dummy, cols, by = "binary_slope")
dummy <- mutate(dummy,
  alpha = cut(value, breaks = c(0, 0.4, 0.6, 0.8, 1), labels = c(0.4, 0.6, 0.8, 1)),
  alpha = as.numeric(as.character(alpha)),
  fill = colorspace::adjust_transparency(fill, alpha)
)

ggplot(dummy, aes(x = model, y = longvarname)) +
  geom_tile(aes(fill = fill)) +
  scale_fill_identity(guide = guide_legend()) +
  facet_grid(vargrp ~ ., scales = "free_y", space = "free_y") +
  xlab("Model") +
  ylab("Variable") +
  theme(
    panel.background = element_blank(),
    axis.text.x = element_text(angle = 45, hjust = 1),
    strip.text.y = element_blank(),
    axis.ticks = element_blank()
  )


text:
Q: Isabelle/HOL: access interpretation in another locale There's an Isabelle/HOL library that I want to build on with new definitions and proofs.  The library defines locale2, which I'd like to build upon.  Inside locale2, there's an interpretation of locale1.
To extend locale2 in a separate theory, I define locale3 = locale2.  Inside locale3, however, I can't figure out how to access locale2's interpretation of locale1.  How can I do that?  (Am I even going about this in the right way at all?)
Below is an MWE.  This is the library theory with the locale I want to extend:
theory ExistingLibrary
  imports Main
begin

(* this is the locale with the function I want *)
locale locale1 = assumes True
begin

fun inc :: "nat ⇒ nat"
  where "inc n = n + 1"

end

(* this is the locale that interprets the locale I want *)
locale locale2 = assumes True
begin

interpretation I: locale1
  by unfold_locales auto

end
end

This is my extension theory.  My attempt is at the bottom, causing an error:
theory MyExtension
  imports ExistingLibrary
begin

locale locale3 = locale2
begin

definition x :: nat
  where "x = I.inc 7" (* Undefined constant: "I.inc" *)

end
end

A: Interpretations inside a context last only until the end of the context. When the context is entered again, you have to repeat the interpretation to make the definitions and theorems available:
locale 3 = locale2 begin
interpretation I: locale1 <proof>

For this reason, I recommend to split the first interpretation step into two:

*

*A lemma with a name that proves the goal of the interpretation step.

*The interpretation command itself which can be proved by(rulelemma)
If you want the interpretation to take place whenever you open the locale and whenever you interpret the locale, then sublocale instead of interpretation might be better.