text:
Q: column not allowed here oracle with getText I tried to save / edit / delete a new row in the database. writing in the gui values to be saved with getText ()
here is the code
Connection conn = Connessione.ConnecrDb();
   Statement stmt = null;
   ResultSet emps = null;

   try{

   String sql;
        sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
                + "VALUES (txt_isbn, txt_disp, txt_titolo, txt_casa, txt_autore, txt_genere, txt_prezzo)";

        stmt = conn.createStatement();

        emps = stmt.executeQuery(sql);

    String ISBN= txt_isbn.getText();
    String DISPONIBILITA= txt_disp.getText();
    String TITOLO= txt_titolo.getText();
    String CASA_EDITRICE= txt_casa.getText();
    String CODICE_AUTORE= txt_autore.getText();
    String GENERE= txt_genere.getText();
    String PREZZO = txt_prezzo.getText();

           JOptionPane.showMessageDialog(null, "SALVATO");

               }catch(SQLException | HeadlessException e)
   {
        JOptionPane.showMessageDialog(null, e);
   }
   finally
   {
       try{
           if (emps != null)
                emps.close();
        }
        catch (SQLException e) { }
        try
        {
            if (stmt != null)
                stmt.close();
        }
        catch (SQLException e) { }
    }

Getting this error: column not allowed here
Above code just takes care of insert operation. How can I delete and modify table record?

A: You have asked 2 different questions here
1. Column not allowed here
This happened because you have not passed values for any of parameter into insert statement.
I am not sure about your requirement however I will use PreparedStatement for this scenario.
Example
String insertTableSQL = "INSERT INTO DBUSER"
        + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
        + "(?,?,?,?)";
        PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
        preparedStatement.setInt(1, 11);
        preparedStatement.setString(2, "MindPeace");
        preparedStatement.setString(3, "system");
        preparedStatement.setTimestamp(4, getCurrentTimeStamp());
        preparedStatement .executeUpdate();

2. This code is only to save the data, delete, and modify an entire row how can I do?
Answer is very simple. You have to write code for the same :)
You need 3 SQL statement which has DELETE and UPDATE operation just like insert in above example.

A: String sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, "
        + "CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
        + "VALUES (?, ?, ?, ?, ?, ?, ?)";

try (PreparedStatement stmt = conn.createStatement()) {

    NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);
    String ISBN = txt_isbn.getText();
    String DISPONIBILITA = txt_disp.getText();
    String TITOLO = txt_titolo.getText();
    String CASA_EDITRICE = txt_casa.getText();
    String CODICE_AUTORE = txt_autore.getText();
    String GENERE = txt_genere.getText();
    BigDecimal PREZZO = new BigDecimal(
            numberFormat.parse(txt_prezzo.getText()).doubleValue())
           .setScale(2);
    stmt.setString(1, ISBN);
    stmt.setString(2, DISPONIBILITA);
    stmt.setString(3, TITOLO);
    stmt.setString(4, CASA_EDITRICE);
    stmt.setString(5, CODICE_AUTORE);
    stmt.setString(6, GENERE);
    stmt.setBigDecimal(7, PREZZO);

    int updateCount = stmt.executeUpdate();

    JOptionPane.showMessageDialog(null, "SALVATO");
} catch(SQLException | HeadlessException e) {
    JOptionPane.showMessageDialog(null, e);
}

Try-with-resources closes the stmt automatically.
The prepared statement replaces the value in the SQL with something like:
INSERT INTO table(column1, colum2, ....)
VALUES('De\'l Rey',
       1234.50,
       ...)

for:
 "De'l Rey"
 1.234,50

updateCount should be 1 on success.

A: Wooow..true!!
I created three buttons to delete / update / insert and now it all works and automatically updates the tables.
you've been very very great. Thank you very much.
one last thing.
if I wanted to insert an error message when I delete / update etc "book not found" I tried to create an if:
Boolean found = false;
  try{
    sql= delete......
       etc
   if (!found)

JOptionPane.showMessageDialog(null, "NOT FOUND","ERRORE",JOptionPane.WARNING_MESSAGE);
etc...
 Connection conn = Connessione.ConnecrDb();
   Statement stmt = null;
   ResultSet emps = null;

    try{

        String sql= "DELETE FROM progetto.libro WHERE isbn =?";  /

        pst=(OraclePreparedStatement) conn.prepareStatement(sql);

        pst.setString (1, txt_isbn.getText());

        pst.execute();

         JOptionPane.showMessageDialog(null, "ELIMINATO");
         Update_table();

         txt_isbn.setText("");
         txt_disp.setText("");
         txt_titolo.setText("");
         txt_casa.setText("");
         txt_autore.setText("");
         txt_genere.setText("");
         txt_prezzo.setText("");

    }

    catch (Exception e)
     {
      JOptionPane.showMessageDialog(null,e);

    }

if you find the book must exit the book removed, or "not found". but as I deployed I always come out "deleted". why?
thanks again


text:
Q: i keep gettin ModuleNotFoundError: No module named 'bs4' error I am trying to write a parser for a website, because I need all the content from this website. Here is my code so far:
import urllib.request
from bs4 import BeauitfulSoup

def get_html(url):
    response = urllib.request.urlopen(url)
    return response.read()

def main():
    print(get_html('http://marryme.md'))

if __name__ == '__main__':
    main()

I have installed bs4 in my virtual environment and I see in my pip list that is successfully installed. Also I found the bs4 folder in my virtualenv directory, but when I run my code I keep getting this error.

A: You either need to activate the virtualenv first:
. venv/bin/activate
python script.py

or explicitly specify the Python interpreter:
venv/bin/python script.py

Of course replace venv with the name/path to your virtualenv.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fibered example of topologically slice knots Is there any known example of fibered knot which is topologically slice but not (expected to be) smoothly slice?

A: A common source of topologically slice knots are those with Alexander polynomial $1$. However these are not fibered. This follows from a classical result, that $2\mathrm{genus}(K) = \mathrm{deg}(\Delta_K(t))$ for fibered knots, which I learned in a paper of Stefan Friedl and Taehee Kim ("The Thurston Norm, Fibered Manifolds and Twisted Alexander Polynomials"). Of course there are other sources of topologically slice knots, so this doesn't settle the question.

A: Such a knot would yield a counterexample to one of two important conjectures in the area.  A preliminary definition: a slice knot is homotopically ribbon if the inclusion of the knot into the slice disk complement induces a surjection on the fundamental group. It's easy to see that a ribbon knot is homotopically ribbon; note that homotopically ribbon doesn't require any smoothness (but you still want local flatness to avoid trivialities). This criterion is viewed as the right substitute for ribbon in the topological setting.
The remarkable theorem of Casson-Gordon (A loop theorem for duality spaces and fibred ribbon knots; Invent. Math. 74, 119-137 (1983)) says that a fibered knot is homotopically ribbon if and only if its monodromy (filled in over a disk) extends over a handlebody.  The if part constructs a smooth slice smooth homotopy ball with boundary the 3-sphere (if your knot lay in the 3-sphere.)  So in particular, a fibered knot that is topologically homotopy ribbon is smoothly homotopically ribbon!!!  So an example of the sort that you ask for would either be slice but not homotopically ribbon (contradicting the conjecture that this doesn't happen) or would give a smooth slice  counterexample to the 4-dimensional Poincaré conjecture.
So to summarize, no such example is known.
PS If there were an MO question asking for "your favorite paper that people don't think about enough", the Casson-Gordon paper mentioned above might top my list.


text:
Q: How to find a dynamic element or attribute in XML using xpath?
From the above image(XML), i want to get NL15 as value or what will be XPATH of NL15 ? NL15 is dynamic text it can be anything like AK15, SI22 ?
    {
    "impact_matrix": {
        "id": 290,
        "id_of_source": 289,
        "impact_matrix_number": 271,
        "status": null,
        "revision": "AC",
        "reviser": {
            "user_id": "saingale",
            "full_name": "Sagar Ingale",
            "email": "sagar.ingale@asml.qas",
            "department_name": "IT Solution Delivery PLM/CM Conf&Change",
            "abbreviation": "SINJ"
        },
        "revision_description": "PARTS ADDED",
        "date_revised": "2022-10-04T21:51:23.167+00:00",
        "title": "impact matrix bys sagar",
        "contexts": [
            {
                "type": "CHANGENOTICE",
                "name": "I am some CN By SAGAR",
                "context_id": "410079",
                "status": "2"
            }
        ],
        "is_auto_layout_enabled": null
    },
    "parts": [
        {
            "id": 1854,
            "id_of_source": 1852,
            "status": null,
            "impact_matrix_id": 290,
            "source": null,
            "intention": {
                "product_id": "4022.123.1111",
                "revision": null,
                "name": null,
                "description": "ITEM 1",
                "vqi": "12121",
                "procurement_type": "E",
                "material_type": null,
                "serial_number_profile": "Z004",
                "critical_configuration_item_indicator": false,
                "regular_part_indicator": "true",
                "history_indicator": null,
                "predecessor_cross_plant_status": null,
                "cross_plant_status": "R1",
                "cross_plant_status_to_be": null,
                "tool_pack_category": "C",
                "tc_change_control": true,
                "sap_change_control": false,
                "allow_bom_restructuring": true,
                "unit_of_measure": null,
                "item_usage": null,
                "is_phantom": null,
                "failure_rate": "111",
                "in_house_production_time": null,
                "sl_abc_code": [
                    "U",
                    "W",
                    "J"
                ],
                "production_plant": null,
                "limited_driving12_nc": null,
                "limited_driving12_ncflag": null,
                "multi_plant": "TESTING MULTI PLANT",
                "part_bom_intention_type": "UNI",
                "plant_specific": {
                    "NL15": {
                        "object_dependency": "aa",
                        "ref_material": "WW",
                        "is_discontinued": true
                    }
                },
                "id": "52996cf0-ed0b-4e8e-9234-1d6c43c6058a",
                "assigned_release_packages": [
                    {
                        "id": "410079-01",
                        "title": "New CR",
                        "release_package_number": "410079-01",
                        "release_package_title": "New CR",
                        "status": "1",
                        "ecn": null
                    }
                ],
                "change_indication": "NEW",
                "type": "D_M"
            },
            "layouts": {
                "DBOM": {
                    "x": -515.0,
                    "y": -159.5,
                    "height": 170.0,
                    "width": 278.0
                }
            },
            "views": [
                "DBOM",
                "MBOM"
            ],
            "item_references": null,
            "change_indication": null,
            "is_parent_part_bom_changed": null,
            "hidden_bom_parents": null,
            "hidden_bom_children": null
        },
        {
            "id": 1855,
            "id_of_source": 1853,
            "status": null,
            "impact_matrix_id": 290,
            "source": null,
            "intention": {
                "product_id": "4022.123.11112",
                "revision": null,
                "name": null,
                "description": "ITEM 2",
                "vqi": "RREE",
                "procurement_type": "E",
                "material_type": "ASSY",
                "serial_number_profile": "ZN02",
                "critical_configuration_item_indicator": true,
                "regular_part_indicator": "true",
                "history_indicator": null,
                "predecessor_cross_plant_status": null,
                "cross_plant_status": "R2",
                "cross_plant_status_to_be": null,
                "tool_pack_category": "E",
                "tc_change_control": false,
                "sap_change_control": true,
                "allow_bom_restructuring": true,
                "unit_of_measure": null,
                "item_usage": "DBOM",
                "is_phantom": null,
                "failure_rate": "21",
                "in_house_production_time": null,
                "sl_abc_code": [
                    "6",
                    "9"
                ],
                "production_plant": null,
                "limited_driving12_nc": null,
                "limited_driving12_ncflag": null,
                "multi_plant": "TEST DATA",
                "part_bom_intention_type": "UNI",
                "plant_specific": {
                    "US21": {
                        "object_dependency": "EEWWW",
                        "ref_material": "",
                        "is_discontinued": true
                    },
                    "US22": {
                        "object_dependency": "RR",
                        "ref_material": "",
                        "is_discontinued": false
                    }
                },
                "id": "bfa9d58b-de19-4af5-83e3-b2a5f77097dd",
                "assigned_release_packages": [
                    {
                        "id": "410079-01",
                        "title": "New CR",
                        "release_package_number": "410079-01",
                        "release_package_title": "New CR",
                        "status": "1",
                        "ecn": null
                    }
                ],
                "change_indication": "NEW",
                "type": "D_ONLY"
            },
            "layouts": {
                "DBOM": {
                    "x": -454.0,
                    "y": -58.5,
                    "height": 170.0,
                    "width": 278.0
                }
            },
            "views": [
                "DBOM"
            ],
            "item_references": null,
            "change_indication": null,
            "is_parent_part_bom_changed": null,
            "hidden_bom_parents": null,
            "hidden_bom_children": null
        }
    ],
    "boms": null,
    "notes": null,
    "frames": null
}

Here is json from which i generated xml.
Here is XML
<?xml version = "1.0" encoding = "UTF-8"?>
<ns0:ActivityOutputClass xmlns:ns0="http://www.tibco.com/namespaces/tnt/plugins/json">
    <ns1:ImpactMatrixAggregate xmlns:ns1="http://www.tibco.com/schemas/bin_bpm_sap_material/Resources/Schemas/Schema.xsd">
        <ns1:impact_matrix>
            <ns1:id>290</ns1:id>
            <ns1:id_of_source>289</ns1:id_of_source>
            <ns1:impact_matrix_number>271</ns1:impact_matrix_number>
            <ns1:status/>
            <ns1:revision>AC</ns1:revision>
            <ns1:reviser>
                <ns1:user_id>saingale</ns1:user_id>
                <ns1:full_name>Sagar Ingale</ns1:full_name>
                <ns1:email>sagar.ingale@asml.qas</ns1:email>
                <ns1:department_name>IT Solution Delivery PLM/CM Conf&Change</ns1:department_name>
                <ns1:abbreviation>SINJ</ns1:abbreviation>
            </ns1:reviser>
            <ns1:revision_description>PARTS ADDED</ns1:revision_description>
            <ns1:date_revised>2022-10-04T21:51:23.167Z</ns1:date_revised>
            <ns1:title>impact matrix bys sagar</ns1:title>
            <ns1:contexts>
                <ns1:type>CHANGENOTICE</ns1:type>
                <ns1:name>I am some CN By SAGAR</ns1:name>
                <ns1:context_id>410079</ns1:context_id>
                <ns1:status>2</ns1:status>
            </ns1:contexts>
            <ns1:is_auto_layout_enabled/>
        </ns1:impact_matrix>
        <ns1:parts>
            <ns1:id>1854</ns1:id>
            <ns1:id_of_source>1852</ns1:id_of_source>
            <ns1:status/>
            <ns1:source/>
            <ns1:intention>
                <ns1:product_id>4022.123.1111</ns1:product_id>
                <ns1:revision/>
                <ns1:name/>
                <ns1:description>ITEM 1</ns1:description>
                <ns1:vqi>12121</ns1:vqi>
                <ns1:procurement_type>E</ns1:procurement_type>
                <ns1:material_type/>
                <ns1:serial_number_profile>Z004</ns1:serial_number_profile>
                <ns1:critical_configuration_item_indicator>false</ns1:critical_configuration_item_indicator>
                <ns1:regular_part_indicator>true</ns1:regular_part_indicator>
                <ns1:history_indicator/>
                <ns1:predecessor_cross_plant_status/>
                <ns1:cross_plant_status>R1</ns1:cross_plant_status>
                <ns1:cross_plant_status_to_be/>
                <ns1:tool_pack_category>C</ns1:tool_pack_category>
                <ns1:tc_change_control>true</ns1:tc_change_control>
                <ns1:sap_change_control>false</ns1:sap_change_control>
                <ns1:allow_bom_restructuring>true</ns1:allow_bom_restructuring>
                <ns1:unit_of_measure/>
                <ns1:item_usage/>
                <ns1:is_phantom/>
                <ns1:failure_rate>111</ns1:failure_rate>
                <ns1:in_house_production_time/>
                <ns1:sl_abc_code>U</ns1:sl_abc_code>
                <ns1:sl_abc_code>W</ns1:sl_abc_code>
                <ns1:sl_abc_code>J</ns1:sl_abc_code>
                <ns1:production_plant/>
                <ns1:limited_driving12_nc/>
                <ns1:limited_driving12_ncflag/>
                <ns1:multi_plant>TESTING MULTI PLANT</ns1:multi_plant>
                <ns1:part_bom_intention_type>UNI</ns1:part_bom_intention_type>
                <ns1:plant_specific>
                    <NL15>
                        <object_dependency>aa</object_dependency>
                        <ref_material>WW</ref_material>
                        <is_discontinued>true</is_discontinued>
                    </NL15>
                </ns1:plant_specific>
                <ns1:id>52996cf0-ed0b-4e8e-9234-1d6c43c6058a</ns1:id>
                <ns1:assigned_release_packages>
                    <ns1:id>410079-01</ns1:id>
                    <ns1:title>New CR</ns1:title>
                    <ns1:release_package_number>410079-01</ns1:release_package_number>
                    <ns1:release_package_title>New CR</ns1:release_package_title>
                    <ns1:status>1</ns1:status>
                    <ns1:ecn/>
                </ns1:assigned_release_packages>
                <ns1:change_indication>NEW</ns1:change_indication>
                <ns1:type>D_M</ns1:type>
            </ns1:intention>
            <ns1:layouts>
                <ns1:DBOM>
                    <ns1:x>-515.0</ns1:x>
                    <ns1:y>-159.5</ns1:y>
                    <ns1:height>170.0</ns1:height>
                    <ns1:width>278.0</ns1:width>
                </ns1:DBOM>
            </ns1:layouts>
            <ns1:views>DBOM</ns1:views>
            <ns1:views>MBOM</ns1:views>
            <ns1:item_references/>
            <ns1:change_indication/>
            <ns1:is_parent_part_bom_changed/>
            <ns1:hidden_bom_parents/>
            <ns1:hidden_bom_children/>
            <impact_matrix_id>290</impact_matrix_id>
        </ns1:parts>
        <ns1:parts>
            <ns1:id>1855</ns1:id>
            <ns1:id_of_source>1853</ns1:id_of_source>
            <ns1:status/>
            <ns1:source/>
            <ns1:intention>
                <ns1:product_id>4022.123.11112</ns1:product_id>
                <ns1:revision/>
                <ns1:name/>
                <ns1:description>ITEM 2</ns1:description>
                <ns1:vqi>RREE</ns1:vqi>
                <ns1:procurement_type>E</ns1:procurement_type>
                <ns1:material_type>ASSY</ns1:material_type>
                <ns1:serial_number_profile>ZN02</ns1:serial_number_profile>
                <ns1:critical_configuration_item_indicator>true</ns1:critical_configuration_item_indicator>
                <ns1:regular_part_indicator>true</ns1:regular_part_indicator>
                <ns1:history_indicator/>
                <ns1:predecessor_cross_plant_status/>
                <ns1:cross_plant_status>R2</ns1:cross_plant_status>
                <ns1:cross_plant_status_to_be/>
                <ns1:tool_pack_category>E</ns1:tool_pack_category>
                <ns1:tc_change_control>false</ns1:tc_change_control>
                <ns1:sap_change_control>true</ns1:sap_change_control>
                <ns1:allow_bom_restructuring>true</ns1:allow_bom_restructuring>
                <ns1:unit_of_measure/>
                <ns1:item_usage>DBOM</ns1:item_usage>
                <ns1:is_phantom/>
                <ns1:failure_rate>21</ns1:failure_rate>
                <ns1:in_house_production_time/>
                <ns1:sl_abc_code>6</ns1:sl_abc_code>
                <ns1:sl_abc_code>9</ns1:sl_abc_code>
                <ns1:production_plant/>
                <ns1:limited_driving12_nc/>
                <ns1:limited_driving12_ncflag/>
                <ns1:multi_plant>TEST DATA</ns1:multi_plant>
                <ns1:part_bom_intention_type>UNI</ns1:part_bom_intention_type>
                <ns1:plant_specific>
                    <US21>
                        <object_dependency>EEWWW</object_dependency>
                        <ref_material/>
                        <is_discontinued>true</is_discontinued>
                    </US21>
                    <US22>
                        <object_dependency>RR</object_dependency>
                        <ref_material/>
                        <is_discontinued>false</is_discontinued>
                    </US22>
                </ns1:plant_specific>
                <ns1:id>bfa9d58b-de19-4af5-83e3-b2a5f77097dd</ns1:id>
                <ns1:assigned_release_packages>
                    <ns1:id>410079-01</ns1:id>
                    <ns1:title>New CR</ns1:title>
                    <ns1:release_package_number>410079-01</ns1:release_package_number>
                    <ns1:release_package_title>New CR</ns1:release_package_title>
                    <ns1:status>1</ns1:status>
                    <ns1:ecn/>
                </ns1:assigned_release_packages>
                <ns1:change_indication>NEW</ns1:change_indication>
                <ns1:type>D_ONLY</ns1:type>
            </ns1:intention>
            <ns1:layouts>
                <ns1:DBOM>
                    <ns1:x>-454.0</ns1:x>
                    <ns1:y>-58.5</ns1:y>
                    <ns1:height>170.0</ns1:height>
                    <ns1:width>278.0</ns1:width>
                </ns1:DBOM>
            </ns1:layouts>
            <ns1:views>DBOM</ns1:views>
            <ns1:item_references/>
            <ns1:change_indication/>
            <ns1:is_parent_part_bom_changed/>
            <ns1:hidden_bom_parents/>
            <ns1:hidden_bom_children/>
            <impact_matrix_id>290</impact_matrix_id>
        </ns1:parts>
        <ns1:boms/>
        <ns1:notes/>
        <ns1:frames/>
    </ns1:ImpactMatrixAggregate>
</ns0:ActivityOutputClass>

Under Plant Specific , there can be different objects with same attributes , which you will see in the xml / json ?
My input will be productId= 4022.xxx.xxx and PlantName=US21, so now i need to give information related to that productId for Plant US21 , but there can be different plants info avaialble for same product id.


text:
Q: adding a rule to remove leading 0 to an existing regex I have some numeric-only input in a textbox that I modify with regex like this:
if (Text.charAt(0) === '0') {
   Text= Text.substring(1);} }

Text= Text.replace(/(\d{1})?(\d{2})?(\d{2})?(\d{2})?(\d{2})?/, '$1 $2 $3 $4 $5');

The desired output should be 1 23 45 67 89. My question is this: how can I add a rule to the regex so that the leading 0 is stripped?
Thanks.

A: You can do this:
Text = Text.replace(/^0?(\d{1})?(\d{2})?(\d{2})?(\d{2})?(\d{2})?/, '$1 $2 $3 $4 $5');

The single replacement will also remove an optional single leading zero.
Working demo: http://jsfiddle.net/jfriend00/n9V6n/


text:
Q: Cocoa (Snow Leopard) NSTextView's textStorage -setAttributes:range: removes characters! I'm not sure what I'm doing wrong.  I have a NSTextView and am registered as the delegate for its textStorage attribute.  When I receive -textStorageDidProcessEditing:notification: I'm trying to apply attributes to ranges of characters within the text.  It certainly does "something" to the characters, but not what I expect... they just disappear!
A heavily distilled code example.  This should make sure the second character in the text field is always red:
-(void)textStorageDidProcessEditing:(NSNotification *)notification {
  NSTextStorage *textStorage = [textView textStorage];
  if ([[textStorage string] length] > 1) {
    NSColor *color = [NSColor redColor];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:color, NSForegroundColorAttributeName, nil];
    [textStorage setAttributes:attributes range:NSMakeRange(1, 1)];
  }
}

Instead, as I type the sequence "abcdefg" I get "a", then when I hit "b" seemingly nothing happens, then when I hit "cdefg" typing occurs as normal, making the end result "acdefg"... the "b" is missing!
If I start hitting backspace I have to hit backspace 7 times, as if the "b" is actually there, but just not being drawn (cursor stalls as it deletes the "b", then on the next backspace deletes the "a" as expected).
If I apply attributes to some default text in the view using the same -setAttributes:range: method before the view is drawn then it does exactly as I expect.
Any clues?  It seems like a fairly normal use of a NSTextStorageDelegate :)
I've tried calling -setNeedsDisplay on the text field to no avail.

A: Figured it out.  Using NSTextStorage's -addAttribute:value:range works.  I still don't fully understand why but at least I can get over it and move on.
-(void)textStorageDidProcessEditing:(NSNotification *)notification {
  // ... SNIP ...
  [textStorage addAttribute:NSForegroundColorAttributeName
                      value:[NSColor redColor]
                      range:NSMakeRange(1, 1)];
}

Makes the code a bit less cluttered too.

A: I'm not sure how relevant this is for you after so many years but I think the reason for it was that you were setting attributes with a dictionary which does not contain NSFontAttributeName, effectively removing it from the textview.
So I think this should work:
-(void)textStorageDidProcessEditing:(NSNotification *)notification {
  NSTextStorage *textStorage = [textView textStorage];
  if ([[textStorage string] length] > 1) {
    NSColor *color = [NSColor redColor];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:color, NSForegroundColorAttributeName, [NSFont ...whatever...], NSFontAttributeName, nil];
    [textStorage setAttributes:attributes range:NSMakeRange(1, 1)];
  }
}


text:
Q: How to end transactions in progress properly and to close the database in Android? I develop simple application in android. Its execute successfully but some time its stopped unfortunately and throw error like these
A SQLiteConnection object for database '/data/data/com.h2o/databases/MyDBName.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
What i do to avoid above error
Here my db code:
public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String ADDRESS_TABLE_NAME = "address";
    public static final String ADDRESS_COLUMN_ID = "id";
    public static final String ADDRESS_COLUMN_ADDRESSTYPE = "addrtype";
    public static final String ADDRESS_COLUMN_LINE1 = "line1";
    public static final String ADDRESS_COLUMN_LINE2 = "line2";
    public static final String ADDRESS_COLUMN_CITY = "city";
    public static final String ADDRESS_COLUMN_ZIPCODE = "zipcode";
    public static final String ADDRESS_COLUMN_COUNTRY = "country";
    public static final String ADDRESS_COLUMN_STATE = "state";
    public static final String ADDRESS_COLUMN_LANDMARK = "landmark";

    //private HashMap hp;

    public DBHelper(Context context)
    {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table address " +
                        "(id integer primary key autoincrement,addrtype text not null unique, line1 text not null,line2 text not null,city text not null,zipcode text not null, country textnot null,state text not null,landmark text)"
        );

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS address");

        onCreate(db);

    }

    public boolean insertAddress(String addrtype, String line1, String line2, String city, String zipcode, String country, String state, String landmark)
    {

        SQLiteDatabase db;

        db= this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("addrtype", addrtype);
        contentValues.put("line1", line1);
        contentValues.put("line2", line2);
        contentValues.put("city", city);
        contentValues.put("zipcode", zipcode);
        contentValues.put("country", country);
        contentValues.put("state", state);
        contentValues.put("landmark", landmark);

        String selectQuery = "select * from address where addrtype ='"+addrtype+"'";
        Cursor cursor = db.rawQuery(selectQuery,null);

        if (cursor.getCount()==1){

            db.update("address",contentValues,"addrtype ='"+addrtype+"'",null);
            return true;
        }
        else {

            db.insert("address", null, contentValues);
            return true;
        }

    }

    public Cursor getData(int id){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from address where id="+id+"", null );
        return res;
    }

    public int numberOfRows(){
        SQLiteDatabase db = this.getReadableDatabase();
        int numRows = (int) DatabaseUtils.queryNumEntries(db, ADDRESS_TABLE_NAME);
        return numRows;
    }

    public boolean updateAddress (Integer id,String addrtype, String line1, String line2, String city, String zipcode,String country,String state,String landmark)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("addrtype", addrtype);
        contentValues.put("line1", line1);
        contentValues.put("line2", line2);
        contentValues.put("city", city);
        contentValues.put("zipcode", zipcode);
        contentValues.put("country", country);
        contentValues.put("state", state);
        contentValues.put("landmark", landmark);
        db.update("address", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
        return true;
    }

    public Integer deleteAddress (Integer id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("address",
                "id = ? ", new String[] { Integer.toString(id) });
    }

    public ArrayList<String> getAllAddress()
    {
        ArrayList<String> array_list = new ArrayList<String>();

        //hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from address", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){
            array_list.add(res.getString(res.getColumnIndex(ADDRESS_COLUMN_ADDRESSTYPE)));
            res.moveToNext();
        }
        return array_list;
    }

}

AddressFragment.java:
mydb = new DBHelper(this.getActivity());

Cursor rs = mydb.getData(Value);
                id_To_Update = Value;

                rs.moveToFirst();
                String addr_type = rs.getString(rs.getColumnIndex(DBHelper.ADDRESS_COLUMN_ADDRESSTYPE));
                String addr_line1 = rs.getString(rs.getColumnIndex(DBHelper.ADDRESS_COLUMN_LINE1));
                String addr_line2 = rs.getString(rs.getColumnIndex(DBHelper.ADDRESS_COLUMN_LINE2));
                String addr_city = rs.getString(rs.getColumnIndex(DBHelper.ADDRESS_COLUMN_CITY));
                String addr_zipcode = rs.getString(rs.getColumnIndex(DBHelper.ADDRESS_COLUMN_ZIPCODE));
                addr_country_index = rs.getString(rs.getColumnIndex(DBHelper.ADDRESS_COLUMN_COUNTRY));
                addr_state_index = rs.getString(rs.getColumnIndex(DBHelper.ADDRESS_COLUMN_STATE));
                String addr_landmark = rs.getString(rs.getColumnIndex(DBHelper.ADDRESS_COLUMN_LANDMARK));

                if (!rs.isClosed())
                {
                    rs.close();
                    mydb.close();
                }

Please anyone fix it!
Thanks in advance

A: I think you are getting this error because you are not closing 'Cursor' object.
 Each Cursor should be closed when you're finished with it. The safe way to do this is:
Cursor res =  db.rawQuery( "select * from address", null);
    try {
        // read data from the cursor in here
    } finally {
        res.close();
    }

A: I used this way:
@Override
    protected void onDestroy () {
        super.onDestroy();
        //myDb is Database Helper Class
        if(myDb.getReadableDatabase().isOpen())myDb.getReadableDatabase().close();
        if(myDb.getWritableDatabase().isOpen())myDb.getWritableDatabase().close();
    }


text:
Q: Repetitive Multiplication/Division I have a number x = 10000 (for example), I want to divide it by a number y = 1.2 (for example) continuously until the result is equal or less than 1.
for example:
10000 / 1.2 = 8333.333
8333.333 / 1.2 = 6944.444
6944.444 / 1.2 = 5787.037
...etc

.
The question is:
Is there a way to find how many divisions occur until we reach the "1" without actually going through all of them?
Thanks.

A: I'm going to assume $x$ and $y$ are greater than $1$. You want to find an integer $n$ such that
$$
\frac{1}{y} < \frac{x}{y^n} \leq 1.
$$
We can rewrite this inequality as
$$
y^{n-1} < x \leq y^n.
$$
Now take logarithms and divide by $\log y$:
$$
n-1 < \frac{\log x}{\log y} \leq n.
$$
It follows that
$$
n = \bigg\lceil\frac{\log x}{\log y}\bigg\rceil,
$$
where $\lceil\cdot\rceil$ is the ceiling function.


text:
Q: asp.net mvc 5 sent email attachments are damaged I am trying to send an email using the method described in this tutorial with a model structure form this tutorial and im partially successfull in doing so. The only issue I am having is the fact that files sent as attachments are damaged. I have tried to get it working in so many ways that I lost count. Obviously haven't been trying hard enough since I didn't find the answer, but decided to ask while I continue looking for an answer.
My controller action is as follows:
public async Task<ActionResult> Index( [Bind(Include = "column names..")] Contact contact, HttpPostedFileBase upload){
  if (ModelState.IsValid && status)
  {
    var message = new MailMessage();
    if (upload != null && upload.ContentLength > 0)
    {
       // 4MB -> 4000 * 1024
       const int maxFileSize = 4096000;
       if (upload.ContentLength < maxFileSize)
       {
         var document = new File
         {
           FileName = System.IO.Path.GetFileName(upload.FileName),
           FileType = FileType.Document,
           ContentType = upload.ContentType
         };
         var supportedTypes = new[] {"doc", "docx", "pdf", "jpg"};
         var extension = System.IO.Path.GetExtension(document.FileName);
         if (extension != null)
         {
            var fileExt = extension.Substring(1);
            if (!supportedTypes.Contains(fileExt))
            {
               ModelState.AddModelError("document", "Wrong format");
               return View();
            }
            //this is the line that sends damaged attachments,
            //I believe I should be using document in some way (using reader bit below),
            //but whatever I use the code complains or crashes.
            message.Attachments.Add(new Attachment(upload.InputStream, Path.GetFileName(upload.FileName)));

            using (var reader = new System.IO.BinaryReader(upload.InputStream))
            {
            document.Content = reader.ReadBytes(upload.ContentLength);
            //message.Attachments.Add(new Attachment(document.Content, document.FileName));
            }
            contact.Files = new List<File> {document};
        }
      }else
      {
        ModelState.AddModelError("document", "File too big. Max 4MB.");
      }
   }

EDIT: A lot of times the code cannot  find the file, how do I make sure I give it correct path each time?


text:
Q: Why won't these images load on mobile? - HTML/CSS On this page, the images look fine on desktop but are white/not found on mobile devices. I have no idea why this is happening. I'm just calling an img tag but it says its not found on mobile even though it is there

A: I have checked your files, @MrVimes is correct your should finish your html which will help validate better on slower devices.
However the problem is purely down to size of the image. Chrome Dev tools shows me that they are massive in size, Enable emulator and select iPhone 5 and see what happens. It is just taking a long time to download.
Try using Picturefil.js to serve smaller images or make them smaller in your software application.
This was the picture I got from Google Dev Tools (which is free and amazing):

Also I noticed that your need to change the way the images are handled in CSS, if you open dev tools:

Position:center

Is not valid, maybe set it to relative or static depending on how you want your page structure to look.
I also saw you may want to update your header with this css:
z-index: 99999;

This will make your header appear on top, as the z-index changes the layers of the html elements (much like the fillings in a sandwhich)

A: sorry my friend but this is false COMPRESSSING THE IMAGES TO 50KB the big images won't appear because your cache browser is full you have to empty your history/cookies/cache of the browser

IOS DEVICE SUPPORT 32 MEGAPIXEL SIZE OF IMAGE IN SAFARI

take a look here for maximum image size and resolution support Apple IOS developper
to delete your cache just go to "Setting=>Safari=>Cleare cache=>clear cache" and that's it
Note: Check the avaible space on your IOS DEVICE should be greater then 50MB
You have to Enjoy the technologie by let the images greater then 1.5mb and works in both of computers/devices


text:
Q: Convert mailchimp double opt in to single I am trying to create a single opt in mailchimp form.
I think they've removed the check box to disable double in verification. wufoo.com creates a form that integrates with mailchimp, it works, but it's their form, and shows a large reference to their site.
Can I modify the mailchimp-generated form to create a single opt effect as well?

<link href="//cdn-images.mailchimp.com/embedcode/horizontal-slim-10_7.css" rel="stylesheet" type="text/css">

<form action="//mynewhealingsite.us3.list-manage.com/subscribe/post?u=1234a5678b80av686fd86a7d7&id=269cdca319" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

  Subscribe to our mailing list
  <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>

<input type="text" name="b_1234a5678b80av686fd86a7d7_269cdca319" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

A: All forms provided directly by MailChimp, including their embed code option, only allow double opt-in. So their is no modification of their original form(s) capable of providing single opt-in.
This guide from their docs denotes this: Double Opt-In Signup Form FAQ's
That said, their API can be used to build out custom single opt-in forms. Alternatively, if that is not an option finding a form integration provider like Wufoo as you've done, that have pre-built a single opt-in solution, may be best.
This page from their API 3.0 docs goes over working with subscribers: Manage Subscribers

A: On Nov. 3, 2017, MailChimp added single opt-in functionality to signup forms. Here is the announce.
Here is the instruction on how to switch between single opt-in and double opt-in. It doesn't change form HTML, so there is no need to change existing markup.


text:
Q: No results for AND operator in sql query Why am i not getting answer if i use and operator in my query?
MY TABLE
+-----------+--------+----------+------+----------+-------------+--------------+
| course_id | sec_id | semester | year | building | room_number | time_slot_id |
| BIO-301   | 1      | Summer   | 2010 | Painter  | 514         | A            |
| CS-101    | 1      | Fall     | 2009 | Packard  | 101         | H            |
| CS-101    | 1      | Spring   | 2010 | Packard  | 101         | F            |
| CS-190    | 1      | Spring   | 2009 | Taylor   | 3128        | E            |
+-----------+--------+----------+------+----------+-------------+--------------+

SQL QUERY WITH OUTPUT
MariaDB [university2038]>

    select course_id from section where semester='Fall' AND semester='Spring';

Empty set (0.00 sec)

A: WHERE semester='Fall' AND semester='Spring' will always result in no rows because a cell cannot be the value 'Fall' AND the value 'Spring' at the same time. You are looking for the OR condition.

A:
semester='Fall' AND semester='Spring'

How can be the value of semester both "Fall" and "Spring" at the same time?
This is a common error that emerges from the sloppiness of the spoken language. We say "I want to get the courses scheduled during the next spring AND fall".
But the logical (boolean) conditions behind this statement are "the courses that are scheduled during the spring OR during the fall".
One can express this in SQL as:
SELECT course_id FROM section WHERE semester = 'Fall' OR semester = 'Spring'

A shorter (and easier to understand) way to write the same thing is achieved using the IN operator:
SELECT course_id FROM section WHERE semester IN ('Fall', 'Spring')

A: You haven't actually said what you want the outlook to look like so any of the following may be appropriate.
MariaDB [sandbox]> drop table if exists p;
Query OK, 0 rows affected (0.13 sec)

MariaDB [sandbox]> create table p
    -> ( course_id VARCHAR(10), sec_id INT, semester VARCHAR(100), year INT, building VARCHAR(10), room_number INT, time_slot_id varchar(1));
Query OK, 0 rows affected (0.27 sec)

MariaDB [sandbox]>  insert into p values
    -> ( 'BIO-301'   , 1      , 'Summer'   , 2010 , 'Painter'  , 514         , 'A'),
    -> ( 'CS-101'    , 1      , 'Fall'     , 2009 , 'Packard'  , 101         , 'H'),
    -> ( 'CS-101'    , 1      , 'Spring'   , 2010 , 'Packard'  , 101         , 'F'),
    -> ( 'CS-190'    , 1      , 'Spring'   , 2009 , 'Taylor'   , 3128        , 'E');
Query OK, 4 rows affected (0.03 sec)
Records: 4  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> SELECT COURSE_ID
    -> FROM   P
    -> WHERE SEMESTER IN ('Fall','Spring')
    -> GROUP BY COURSE_ID HAVING COUNT(*) > 1;
+-----------+
| COURSE_ID |
+-----------+
| CS-101    |
+-----------+
1 row in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> select *
    -> from p
    -> where course_id in
    -> (SELECT COURSE_ID
    -> FROM   P
    -> WHERE SEMESTER IN ('Fall','Spring')
    -> GROUP BY COURSE_ID HAVING COUNT(*) > 1
    -> )
    -> ;
+-----------+--------+----------+------+----------+-------------+--------------+
| course_id | sec_id | semester | year | building | room_number | time_slot_id |
+-----------+--------+----------+------+----------+-------------+--------------+
| CS-101    |      1 | Fall     | 2009 | Packard  |         101 | H            |
| CS-101    |      1 | Spring   | 2010 | Packard  |         101 | F            |
+-----------+--------+----------+------+----------+-------------+--------------+
2 rows in set (0.00 sec)

MariaDB [sandbox]> select p.*
    -> from p
    -> join
    -> (select course_id,
    -> sum(case when semester in('Spring','Fall') then 1 else 0 end) as cnt
    -> from p
    -> group by course_id
    -> ) s
    -> on s.course_id = p.course_id
    -> where s.cnt = 2
    -> ;
+-----------+--------+----------+------+----------+-------------+--------------+
| course_id | sec_id | semester | year | building | room_number | time_slot_id |
+-----------+--------+----------+------+----------+-------------+--------------+
| CS-101    |      1 | Fall     | 2009 | Packard  |         101 | H            |
| CS-101    |      1 | Spring   | 2010 | Packard  |         101 | F            |
+-----------+--------+----------+------+----------+-------------+--------------+
2 rows in set (0.00 sec)


text:
Q: How to print floats with for loop without other functions BUT range() I want to Print all the numbers between 5 to 8, with jumps of 0.3.
I got 2 problems doing it:

*

*It's not very accurate (I know the reason, what I dont know is how to get 5.89999999999 to become 5.9)

*I dont know how to do it without any imports and functions (without numpy and without xrange which btw does not exist in python 3.x anymore as I understood)
This is just for a Homework question, I'm a new python learner, so I dont realy know ALL the tools and tricks of python.
max = 9
min = 5
step = 0.3
while min <= max:
    min += step
    print(min)

Expected:
5,
5.3,
5.6,
5.9,
6.2,
...

Actual reasults:
5.3,
5.6,
5.89999999995,
6.1999999999,
6.4999999999,
...

A: Just round min using round() before printing it. If you want the original value of the variable to be also printed, you'll want to change the position of the print statement.
while min <= max:
    print(min)
    min+=step
    # rounds min to the first decimal place
    min = round(min,1)

Results:
5
5.3
5.6
5.9
6.2
6.5
6.8
7.1
7.4
7.7
8.0
8.3
8.6
8.9
9.2


text:
Q: Sharing transparently proxied Internet connection with PS3 I am trying to play a Japanese karaoke game on a PS3 but the latency is just horrendous and downloading songs takes forever. One recommendation I got was to turn my laptop into a SOCKS proxy by logging in via OpenSSH to my friend's server in Japan.
[server]----(ssh tunnel)---[wlan0 < laptop > eth0]---[PS3]
So that's what I did:
ssh -ND 4711 login@friend.server

At that moment I tried reaching google.com from my laptop using Firefox (with SOCKS proxy settings) and I got redirected to google.co.jp. Great.
Then I wanted to connect my PS3 to my laptop via Ethernet.
I first assigned a static IP to eth0 with:
ip link set dev eth0 up
ip addr add 139.96.30.100/24 dev eth0

I then started a DHCP server on my laptop to give an IP to the PS3 with:
systemctl start dhcp4.service

And finally I enabled NAT with some iptables magic:
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

I went to "Networks Settings" and tested the connection from my PS3 and nice, it seemed to work. I launched the web browser and google.com got redirected to google.fr. How stupid, I forgot to forward the connection to the right port.
After a lot of connection forwarding through iptables that didn't work I decided to try using a transparent proxy: redsocks. http://darkk.net.ru/redsocks/
After installation I modified /etc/redsocks.conf to suit my needs:
redsocks {
    local_ip=0.0.0.0; // documentation says: "use 0.0.0.0 if you want to listen on every interface"
    local_port=31388;
    ip=127.0.0.1;
    port=4711;
}

with the rest left out as it was in https://github.com/darkk/redsocks/blob/master/redsocks.conf.example
I used the basic redsocks.rules provided in the package I installed:
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
:REDSOCKS - [0:0]

# Redirect all output through redsocks
-A OUTPUT -p tcp -j REDSOCKS

# Whitelist LANs and some other reserved addresses.
# https://en.wikipedia.org/wiki/Reserved_IP_addresses#Reserved_IPv4_addresses
-A REDSOCKS -d 0.0.0.0/8 -j RETURN
-A REDSOCKS -d 10.0.0.0/8 -j RETURN
-A REDSOCKS -d 127.0.0.0/8 -j RETURN
-A REDSOCKS -d 169.254.0.0/16 -j RETURN
-A REDSOCKS -d 172.16.0.0/12 -j RETURN
-A REDSOCKS -d 192.168.0.0/16 -j RETURN
-A REDSOCKS -d 224.0.0.0/4 -j RETURN
-A REDSOCKS -d 240.0.0.0/4 -j RETURN

# Redirect everything else to redsocks port
-A REDSOCKS -p tcp -j REDIRECT --to-ports 31338

COMMIT

That allowed me to stop using the SOCKS proxy settings on Firefox and luakit which I confirmed with the google.com turning into google.co.jp test.
I figured I still had to enable NAT so I redid:
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

The PS3 apparently bypassed the system-wide proxy and google.com got redirected to google.fr. I then used the redsocks.rules file as it was without masquerading. I believed that anyway I wouldn't need NAT since the redsocks server apparently listens on every interface.
I tried connecting the PS3 again and I got the following message (after the PS3 acquired an IP from my DHCP server and failed at getting an internet connection):
"An error occured during communication with the server. This is a DNS error."
That's where I am right now. I guess it might be a problem with redsocks though, since it uses a DNS server called dnstc which does this according to the documentation:
dnstc {
    // fake and really dumb DNS server that returns "truncated answer" to
    // every query via UDP, RFC-compliant resolver should repeat same query
    // via TCP in this case.
    local_ip = 127.0.0.1;
    local_port = 5300;
}

My wild guess is that my PS3 requests DNS resolution via UDP and that dnstc replies with "truncated answer" all the time. If I understand correctly, it should resend the request through TCP but apparently it produces a DNS error instead??
What should I do? Or more precisely:

*

*Is redsocks unnecessary? Am I just iptables-illiterate?

*Should I install a DNS server and forward the DNS requests? If so, how?

Thanks for reading that wall-of-text! Hope it doesn't suck too much for a first question...

A: You could set the PS3 to use a static DNS server. You could try OpenDNS, which has servers on 208.67.222.222 and 208.67.220.220, or try Google's public DNS server on 8.8.8.8 and 8.8.4.4.


text:
Q: Database error during the test: cannot change column I changed one field of the model, to create migrations and applied it. There were no errors. But when I try to run the tests, there's an error.
django.db.utils.OperationalError: (1833, "Cannot change column 'rfiid': used in a foreign key constraint 'elements_attachments_rfi_id_bc723558_fk_rfis_rfiid' of table 'test_smap_production.elements_attachments'")

field that I changed - rfiid. I switched it from AutoField to CharField.
models.py
class Rfis(models.Model):
    rfiid = models.CharField(max_length=6, primary_key=True)
    ....

The migration was successful, and there is no already created instance of the model in the database. Why such an error occurs and how to correct it?
p.s.
class ElementsAttachments(models.Model):
    e = models.ForeignKey('Elements', models.DO_NOTHING)
    attachment = models.ForeignKey('Attachments', models.DO_NOTHING)
    rfi = models.ForeignKey('Rfis', models.DO_NOTHING)
    timestamp = models.DateTimeField(auto_now=True)
    active = models.IntegerField()
    vendor_response = models.IntegerField(blank=True, null=True)

A:
A not clean way and risky is to delete all previous migrations and make a new migration.

Warning: This is risky and can provoke damages if you already have data in your databases.


text:
Q: Form Recognizer labels not loading My Tags/Labels bar on the right side of screen doesn't work. Its loading all the time. Theres Just spinner.
When I click on adding table tags it works Just to create, but after creation I can't maintain it.
Does anybody has idea what could cause the problem?

A: I found a solution - there was a problem with visibility of invoices inside of the blob - form recognizer couldn't process one of them and had a problem with labels.
I've changed the sets of invoices and everything worked just fine.


text:
Q: Continuity of the characteristic function of the subset of algebraic numbers Let $f : [0,1] \to \Bbb R$ be defined as follows:
$$f(x) =  \begin{cases} 1, & \text{if } x \text{ is algebraic} \\ 0, & \text{otherwise.} \end{cases} $$
I know that the set of points of discontinuity of $f$ is the subset of algebraic numbers in $[0,1]$ but I don't know how to prove it. Please help me. Thanks.

A: Try with an $\epsilon-\delta$ proof: let $x_0$ be an algebraic number, so $f$ is continuous in $x_0$ iff $\forall \epsilon>0 \, \exists\delta>0$ such that $|f(x_0)-f(y)|<\epsilon \, \forall y$ such that $|x_0-y|<\delta$. Try to take $\epsilon=\frac 1 2$ and use the fact that all the rational numbers are algebraic and the property that exists always a rational number between two real numbers.


text:
Q: VirtualBox, problem with booting guest. Windows 11 P2V conversion 1 I used the VMware standalone converter to convert my physical Windows 11 to virtual. The physical Win11 installation satisfied hardware requirements; I did not employ any bypasses or hacks.
2 I converted the resulting vmdk file to vdi.
3 I created a virtual machine and added the above-mentioned vdi.
4 I tried to run the VM on a Kubuntu 22.04 host, with EFI enabled in the guest settings.
VirtualBox version is: Graphical User Interface Version 6.1.34_Ubuntu r150636
It drops me to the UEFI interactive shell, and when I enter fs0, it says that the command is not recognized.
5 If I untick EFI in the guest settings, it says bootable medium not found.
If I understand right, VirtualBox 6 does not support secure boot and TPM 2.0. So that's the problem here? Is there anything to do about it at this point -- is there a beta version of VM 7 available, or maybe I can modify the guest somehow?


text:
Q: MySQLi query not working. Multiple AND statements Im trying to add an extra AND statement to my SQL query.
I work fine as:
SELECT * FROM tsv WHERE YEAR(`Reporting Date`) = 2017 AND MONTH(`Reporting Date`) = 6

But when I try to add the extra line (AND ISRC = QZERG1727327) in the end it dosen´t work any more
SELECT * FROM tsv WHERE YEAR(`Reporting Date`) = 2017 AND MONTH(`Reporting Date`) = 6 AND ISRC = QZERG1727327

It´s hard to find any solutions online, I really don´t know what to do.

A: Strings in SQL have to be enclosed in single quotes, so your query should be
SELECT * FROM tsv
WHERE YEAR(`Reporting Date`)=2017 AND MONTH(`Reporting Date`)=6
  AND ISRC='QZERG1727327'


text:
Q: How can I create a generic function that only accepts instances of classes with a particular static member? I want to create a generic function which only accepts arguments if their type has a specific static member:
class A {
    static Param = class {
        foo: number
    }
}

class B {
}

// How do I require T to have a static Param member?
function test<T>(first: T) {

}

test(new A());    // this should pass type check
test(new B());    // this should fail

A: You can't.
Though I do have a workaround for you.
Typescript does not include static members as part of the type that a class represents. The following is in TS Playground so you can see the error messages. I add ParamClass because we need some way to refer to the type of Param in the generic function.
class ParamClass {
    foo: number = 0
}

class A1 {
    Param: typeof ParamClass = class {
        foo: number = 0
    }
}

class A2 {
    static Param: typeof ParamClass = class {
        foo: number = 0
    }
}

const a1: A1 = {}  //fails type check: Property 'Param' is missing in type '{}' but required in type 'A1'.(2741)

const a2: A2 = {}  //passes type check, static class member is not part of type A2

function test1<T extends {Param: typeof ParamClass}>(c: T): T {
  return c
}

test1(new A1())  //passes

test1(new A2())  //fails: Property 'Param' is missing in type 'A2' but required in type '{ Param: typeof ParamClass; }'.(2345)

// But what if we define T to have a static member?
// You can't. It's not legal Typescript:
//
//      'static' modifier cannot appear on a type member.(1070)
//
function test2<T extends {static Param: typeof ParamClass}>(c: T): T {
  return c
}

my workaround
in playground
class ParamClass {
    foo: number = 0
}

class A3 {
    static Param: typeof ParamClass = class {
        foo: number = 0
    }
    get Param() {
        return A3.Param
    }
}

class B {
}

function test1<T extends {Param: typeof ParamClass}>(c: T): T {
  const param = c.Param
  // now you can do whatever you want with class Param, e.g.
  const paramInstance = new param()
  return c
}

test1(new A3())  // passes type check

test1(new B())  // fails type check


text:
Q: Session data still not persistent between routes, even though session management is done via connect-mongo in MongoDB Even though I let MongoStore handle my sessions, my sessions are still undefined when I try to access sessions from a different api route.
For example in my /login route:
app.route("/login")
    .post(async (req, res) => {
        var username = req.body.username,
            password = req.body.password;

        console.log('\t@/login');
        try {
            var user = await User.findOne({ username: username }).exec();
            if (!user) {
                res.redirect("/login");
            }
            user.comparePassword(password, (error, match) => {
                if (!match) {
                    console.log('redirecting to /login')
                    res.redirect("/login");
                }
            });
            req.session.user_sid = {user};
            console.log('\treq.session:');
            console.log(req.session)             // output screenshot provided below

        } catch (error) {
            console.log(error)
        }
    });

And it outputs as:

However, when I try to access the req.session from my /dashboard route, I get undefined. The /login route and its corresponding log is below:
app.get("/dashboard", (req, res) => {

    console.log("\t@/dashboard route:")
    console.log("\treq.session:");
    console.log(req.session);          // session is undefined even though it wasnt in my login route
    if (req.session.user && req.cookies.user_sid) {
        // res.sendFile(__dirname + "/public/dashboard.html");
        console.log(req.session);
        res.send("send something")
    } else {
        res.send("go back to /login");
    }
});

I let mongo manage my sessions like:
const MongoStore = require("connect-mongo");
app.use(session({
    secret: 'mysecret',
    resave: false,
    store: MongoStore.create({
        mongoUrl: sessionDbUrl,
        collection: 'sessions',
        ttl : 14 * 24 * 60 * 60, // 14 days
      }),
    //  store: new MongoStore({ mongooseConnection: db }),
    saveUninitialized: true,
    cookie: { maxAge: 1000 * 60 * 60 * 24, secure: true }, // 24 hours
  }));

My problem is that the session do not persist within my routes, even though I tried Mongo. When I let mongo handle my sessions, does these sessions get stored in Mongo that I can view in Compass? My understanding is that, session management done via mongodb simply makes sessions data persistent throughout the app without actually needing to store the sessions as collections in the database. Please correct my understanding if I'm wrong, I've been stuck on this for days. TIA


text:
Q: #define template types doen't seem to work suppose the following code:
#define __INIT_TYPE(type) { template<typename type>struct S{ };}

__INIT_TYPE(int);

int main(){
}

the second line produces the following error
Function definition for '\__INIT_TYPE' not found. Expected a declaration.

*

*Why does it happen? so far as I know the macro has to be replaced with the templated struct and which will be declared and then defined.

*If I am just missing something and there is a solution to q.1, is it considered a bad practice to nest types in the program with macros like this?

A: In C++ avoid macros for as long as you can they are mostly bad practice.
They are type unsafe and in general do not make code more readable (for other people). Just stick to standard C++ if you can.
In your case __INIT_TYPE is not initializing anything, only creating a template instance of S.
If you want an initialized instance of S
Just make a function template that creates your struct.
template<typename type_t>
struct S
{
};

template<typename>
auto make_S()
{
    return S<typename type_t>{};
}

int main()
{
    auto s = make_S<int>();
}

A: You defined the macros as a function with the body in braces, like a function body w/o a function name:
#define __INIT_TYPE(type) { template<typename type>struct S{ };}

Braces are not allowed outside functions. You might want
#define __INIT_TYPE(type) template<typename type>struct S{ };

Suggest that you take a look at What are the rules about using an underscore in a C++ identifier? to avoid further errors.


text:
Q: Google Cloud App Engine (Django) and Google Cloud Storage working on a Single Domain with Custom URLs I have a Django application working on supereye.co.uk.
Django handles all URL routing such as supereye.co.uk/signin supereye.co.uk/watch etc.
I am also using Google Cloud Storage that is working with Google Cloud App Engine on gs://production2.supereye.co.uk
How shall I handle the routing so both App Engine and Storage can be accessible through the supereye.co.uk domain. For instance :
supereye.co.uk      -> Django App, Google Cloud App Engine
data.supereye.co.uk -> Google Cloud Storage bucket, gs://production2.supereye.co.uk

Is there any way to achieve this without relating Django App to bucket at all ?
Can the bucket be accessible by its own resources while using a proper https custom domail such as "https://data.supereye.co.uk" rather than for instance "https://storage.googleapis.com/production-supereye-co-uk/video/DFeMfXUk4Te/thumbnail/Mx73lhda8n8x.webp" ?
Is there any internal Google Cloud tool that will let me achieve this ?

A: As mentioned in the stackoverflow answer, you can do this using a load balancer. You can set up a URL map to match the desired paths, and point different requests to the backend bucket and app engine, respectively.
If you just wanna name your bucket with a domain name then I suggest you go through Domain-named bucket verification. This link focuses mainly on requirements for creating buckets with domain names.


text:
Q: Can "distinguish" be used as an in-place replacement for "classify" or "categorize"? By "in-place replacement" I mean to replace the word without changing the sentence structure. For example:

To distinguish narcotics as either soft or hard.

Can we say that?
In other words, can "distinguish" be used with "as either... or" instead of "between... and"?
I know I could say "to classify" or "to categorize" but I think that these words convey a notion of a somewhat elaborate (or at least non-trivial) process, while I want to convey the meaning of a very simple and direct action.
Another word that I am also not sure I could use is "to differentiate". I think "differentiate" really needs "between... and", right?  I can hardly imagine being able to say "To differentiate narcotics as either soft or hard."
The actual (technical) sentence I am working on, if it matters, is "we achieve so-and-so by  distinguishing connections as either inputs or outputs."

A: I think the word you need is identifying. Identify means:

to perceive or state the identity of (someone or something) (M-W)

If you identify someone or something, you name them or say who or what they are.

*

*They identified six plants as having potential for development into pharmaceutical drugs. (Collins)

Distinguish something as something is possible, but less common. It basically means distinguishing that something from the rest, like this other ELU post shows:

Jim looked out the window of the moving car and saw a variety of large buildings dotting the landscape, each with a large mural facing the road. One had a picture of an octopus. Another had a picture of helicopter. Jim didn't know what they all meant, except for one, which had the picture of a happy cow. Jim distinguished it as an old dairy. Here the context implies that Jim is distinguishing this building from the rest of the buildings. He does this by identifying it as an old dairy, whereas he could not identify the other buildings.


text:
Q: How to run easy_install in cygwin? I am trying to install some package in cygwin's python, but I'm getting the following error: "easy_install: command not found".
I have tried to run "easy_install.py", the result is also "easy_install.py: command not found". I have tried to search the whole of cygwin's /usr tree for anything named with the prefix "easy", none found.
Am I missing something? AFAIK, easy_install tool should be batteries included in python 2.5. Or is there a package that needs to be installed for that that I missed?

A: Easy Install is a python module (easy_install) bundled with setuptools, which can be found here: http://pypi.python.org/pypi/setuptools . You must install setuptools by yourself.

*

*If you want to install it into windows python than use setuptools install script from cmd shell or use MS Windows installer

*If you need python with setuptools to work within cygwin than:

*

*use cygwin's own python (you can install one using cygwin's setup.exe)

*use setuptools source

A: From cygwin prompt, do:
$ wget http://peak.telecommunity.com/dist/ez_setup.py
$ python ez_setup.py

This will install easy_install on your cygwin.
Easy as py.

A: easy_install is part of the setuptools package. This package is provided by cygwin. To install it, rerun the cygwin setup[...].exe installer, and at the package selection step, tick "Python/python-setuptools".
The easy_install script has the version number attached.  Instead of running easy_install, run easy_install-2.7 or easy_install-3.4 (or whatever x.y version of Python you have installed).

A: In addition to installing setuptools (as described in other answers), you also need to make sure C:\Python25\Scripts is in your PATH.


text:
Q: Dot puzzle wrapped around a pillar near the end of The Witness Near the end of The Witness, there are a series of puzzles wrapped around pillars.
I'm having trouble with the one composed of a 6x5 grid mostly covered with dots ⬣. I've already tried drawing it on paper, but still couldn't figure it out. I need some hints.
              |
--*--*--*--*--*--*--
  |  |  |  |     |
--*--*--*--*  *--*--
  |  |  |     |  |
--*--*--*  *--*--*--
  |  |     |  |  |
--*--*  *--*--*--*--
  |     |  |  |  |
--O--O--O--*--*--*--

A: Sorry, no spoiler tags here because it doesn't work correctly with code blocks. So...
Spoiler warning! 3...
Spoiler warning! 2...
Spoiler warning! 1...
Since a dot requires a line passing through it, we can pick which dots have only two possible connections:
              |
--*--*--*--*--*--*--
  |  |  |  |     |
--*--*--*--┛  ┏--*--
  |  |  |     |  |
--*--*--┛  ┏--*--*--
  |  |     |  |  |
--*--┛  ┏--*--*--*--
  |     |  |  |  |
--O--O--O--*--*--*--

Extending the lines from those six dots leads to four more dots being connected:
              |
--*--*--*--*--*--*--
  |  |  |  ┃     |
--*--*--┏━━┛  ┏━━*--
  |  |  ┃     ┃  |
--*--┏━━┛  ┏━━┛--*--
  |  ┃     ┃  |  |
--*━━┛  ┏━━┛--*--*--
  |     ┃  |  |  |
--O--O--O--*--*--*--

Now, we can repeat the same idea and create two new corners based on the four dots we've just connected:
              |
--*--*--*--*--*--*--
  |  ┃  |  ┃     |
--*━━┛--┏━━┛  ┏━━*--
  |  |  ┃     ┃  |
--*--┏━━┛  ┏━━┛--*--
  |  ┃     ┃  |  |
--*━━┛  ┏━━┛--┏━━*--
  |     ┃  |  ┃  |
--O--O--O--*--*--*--

This leads to two dots that can only be connected horizontally:
              |
--*--┏━━━━━┓--*--*--
  |  ┃  |  ┃     |
--*━━┛--┏━━┛  ┏━━*--
  |  |  ┃     ┃  |
--*--┏━━┛  ┏━━┛--*--
  |  ┃     ┃  |  |
--*━━┛  ┏━━┛--┏━━*--
  |     ┃  |  ┃  |
--O--O--O━━━━━┛--*--

Which leads to three more corners:
              ┃
━━┓--┏━━━━━┓--┗━━*━━
  ┃  ┃  |  ┃     |
--*━━┛--┏━━┛  ┏━━*--
  |  |  ┃     ┃  |
--*--┏━━┛  ┏━━┛--*--
  |  ┃     ┃  |  |
--*━━┛  ┏━━┛--┏━━*--
  |     ┃  |  ┃  ┃
━━O--O--O━━━━━┛--┗━━

Almost there, only two dots and two free ends are left:
              ┃
━━┓--┏━━━━━┓--┗━━━━━
  ┃  ┃  |  ┃     |
--┗━━┛--┏━━┛  ┏━━*--
  |  |  ┃     ┃  |
--*--┏━━┛  ┏━━┛--*--
  |  ┃     ┃  |  |
--*━━┛  ┏━━┛--┏━━┓--
  |     ┃  |  ┃  ┃
━━O--O--O━━━━━┛--┗━━

Which finally leads to the solution:
              ┃
━━┓--┏━━━━━┓--┗━━━━━
  ┃  ┃  |  ┃     |
--┗━━┛--┏━━┛  ┏━━┓--
  |  |  ┃     ┃  ┃
━━┓--┏━━┛  ┏━━┛--┗━━
  ┃  ┃     ┃  |  |
--┗━━┛  ┏━━┛--┏━━┓--
  |     ┃  |  ┃  ┃
━━O--O--O━━━━━┛--┗━━

So... Drawing this on the computer, using characters, worked better for me than drawing on a piece of paper.


text:
Q: Representation of nullhomologous loop on compact surface as a product of commutators. Why this sentence is true?:
Assume that $M$ is compact surface and $f: S^1 \to M$ is nullhomologous and without selfintersections. Letting $g$ be the genus and $b$ the number of boundary components of $M$, it follows that there is a generating set $S=\{\alpha_1, \beta_1, ..., \alpha_g, \beta_g, x_1, ..., x_b\}$ such that:
$$ \pi_1(M, *) = \langle a_1, b_1, \ldots , a_g, b_g, x_1, \ldots , x_b \mid [a_1, b_1]\cdots [a_g, b_g]= x_1\cdots x_b \rangle . $$
and such that:
$f$ is homotopic to $[\alpha_1, \beta_1] \cdots [\alpha_{g'}, \beta_{g'}]$ for some $g'<g$.
I know Hurewicz teorem, so I know that $f$ belongs to comutant of fundamental group, but why representation of $f$ is such as above? In particular why in this representation doesn't $x_i$ appear?
Could anybody help me or show me the book,where I can read about it in a algebraic topology way (I'm not familiar with differential topology)?
[Edit]: I forgot to write, that $f$ is without selfintersections

A: Updated after OP's edit:
Here's the idea: A simple closed curve $\gamma$ in an orientable genus $g$ surface $M$ is nullhomologous if and only if $M \setminus \gamma$ consists of two connected components, one of which is a surface $N$ with $\partial N = \gamma$. Since $\gamma$ is the one and only boundary component of $N$, all of the boundary components corresponding to $x_1,\ldots,x_b$ lie in the second connected component (which has a total of $b+1$ boundary components, when you include its copy of $\gamma$). Since $N$ is an orientable surface of genus $g'\leq g$, we can choose standard generators $\alpha_1,\beta_1,\ldots,\alpha_{g'},\beta_{g'}$ of $\pi_1(N)$ such that $\gamma$, the boundary of $N$, has homotopy class $[\alpha_1,\beta_1]\cdots[\alpha_{g'},\beta_{g'}]$. Then $\alpha_i,\beta_i$ are also generators in $\pi_1(M)$. The other generators $\alpha_{g'+1},\beta_{g'+1},\ldots,\alpha_g,\beta_g,x_1,\ldots,x_b$ come from the second connected component.
Remark. Note that we must allow $g'\leq g$, not "$g'<g$". Suppose $M$ has $b$ punctures and $\gamma$ is a small loop around these punctures. On one side, $\gamma$ bounds a disk with $b$ punctures. On the other side, $\gamma$ bounds a genus $g$ surface with a disk removed. Thus $\gamma$ is nullhomologous, but in terms of the standard generators its homotopy class is $[\alpha_1,\beta_1]\cdots[\alpha_g,\beta_g]$.

A: What you are trying to prove is false: The least number of products of commutators needed to represent the given element x of the derived subgroup is called the "commutator length" of x. The theorem is that in any torsion free noncyclic hyperbolic group (like surface group of genus at least 2) there are elements of arbitrary high (finite) commutator length. In fact, take any nontrivial element y of the derived subgroup, then the commutator length of $y^n$ will diverge linearly to infinity. You can find a proof and much more in the book by D.Calegari "scl" (which is an acronym for "stable commutator length").


text:
Q: PHP mail() error 500 As part of the registration process on a website, I have added mail confirmation. But for some reason, the mail function throws an Internal server error in there.
The strange thing is that if I create a test script, with the exact same email (all the same parameters) it works fine, and sends the email.
The mail is sent from a function in a Class, in case that helps. I didn't post the code because it isn't really relevant, even if I try mail('email@email.com','subject','email'); it fails with the 500 error!
The server error logs don't show anything at all, anyone knows what may cause such a problem?
Technology:
The server is running php through mod_fastcgi, although this problem also happens if I switch to mod_suphp.
Updates:
UPDATE:
I'll try to explain this better, the mail function works perfectly if called from another file, with the same parameters. The problem here is something that combined with the mail function causes an error 500. The rest of the file where it's called is fine too, if I comment the mail function everything works. The way it gets called is an AJAX request to a file that calls a function where the mail is sent (Just in case this helps)
UPDATE 2:
In response to answers so far, here is more information I did not share previously:
OS: CentOS release 5.8
When I say error 500, I mean that the server returns only an HTTP 500 status code.
The server does not show anything in any error log
The most important thing is that if I create a file called test.php, with only mail('address@domain.com','Subject','Message'), it works just fine. When called from this other file, 500 status code returned.
What I am asking is if anyone knows, probably from experience, what could be causing this.
UPDATE 3:
Someone had the same problem yesterday: PHP's mail() function causes a 500 Internal Server Error only after a certain point in the code
UPDATE 4:
After some testing, I have discovered that the 500 stats code is only returned when the script is called via AJAX. If I create a file called test.php, and I simply place the mail function and test it, it works. Calling it via AJAX doesn't, any ideas?

A: Your question is very confused.
You've not said what operating system you are running on, nor provided details of the configuration: on MSWindows php's mail function acts as an SMTP client. On POSIX OS's (including Linux) it executes a command program to send the email. The SMTP client needs to know the server and port to connect to. The POSIX function needs the config to tell it which program to run.
You keep refering to a 500 error - do you mean an HTTP 500 status code at the browser?
What does the log for the mail program / server show? If this is a posix platform, try changing the php.ini to run a shell script to log actions and parameters.

A: With the amount of input you have provided, it is very hard to tell, how that error occured.
Error: 500 are Interval Server Errors and can have more than one reasons for occuring.

*

*A malformed php cgi script

*An invalid directive in an .htaccess or other config file

*Limitation imposed by file system and server software.
   May be you are attachcing a file to be to be sent

*Missing Line Breaks (\r\n) in the headers

Try every solution listed from this cPanel Forums

A: After some more hours of testing I have found the problem!
I was using window.location to redirect the user to a new page after the AJAX call was completed, in it's callback function.
Apparently if you modify it after an AJAX call to a php script that uses the mail() function, the server returns a 500 status code in the request


text:
Q: "But maybe you just don't?" You could at least have called her, let her know that you care. But maybe you just don't?
Is the highlighted part completely natural in continuation to the rest to mean but maybe you just don't care? or would you rephrase it?

A: This is completely natural in neutral-register spoken English. It's also completely natural and slightly informal in written English (e.g. emailing an acquaintance).
You are correct; don't stands in for don't care.
For comparison:

*

*I would like to learn Chinese; I'm afraid I just can't.

*I asked him to stop by the supermarket, but he probably [just] won't.

More subtly:

*

*The prosecutor accused her of embezzling funds, but she claimed she didn't [or hadn't].


text:
Q: PEGKit combine matched symbols on stack I'm writing a grammar for PEGKit to parse a Twine exported Twee file. This is my first time using PEGKit and I'm trying to get to grips with how it works.
I have this twee source file that I'm parsing
:: Passage One
P1 Line One
P1 Line Two

:: Passage Two
P2 Line One
P2 Line Two

Currently I've worked out how to parse the above using the following grammar
@before {
    PKTokenizer *t = self.tokenizer;
    [t.symbolState add:@"::"];
    [t.commentState addSingleLineStartMarker:@"::"];

    // New lines as symbols
    [t.whitespaceState setWhitespaceChars:NO from:'\n' to:'\n'];
    [t.whitespaceState setWhitespaceChars:NO from:'\r' to:'\r'];
    [t setTokenizerState:t.symbolState from:'\n' to:'\n'];
    [t setTokenizerState:t.symbolState from:'\r' to:'\r'];
}

start                   = passage+;
passage                 = passageTitle contentLine*;
passageTitle            = passageStart Word+ eol+;
contentLine             = singleLine eol+;
singleLine              = Word+;
passageStart            = '::'!;
eol                     = '\n'! | '\r'!;

and the result I get is
[Passage, One, P1, Line, One, P1, Line, Two, Passage, Two, P2, Line, One, P2, Line, Two]::/Passage/One/
/P1/Line/One/
/P1/Line/Two/
/
/::/Passage/Two/
/P2/Line/One/
/P2/Line/Two/
^

Ideally, I'd like the parser to combine the words matched for the passageTitle into a single string similar to how the built in PEGKit QuotedString grammar works. I would also like the words matched for a contentLine to be combined as well.
So, eventually, I would have this on the stack
[Passage One, P1 Line One, P1 Line Two, Passage Two, P2 Line One, P2 Line Two]

Any thoughts on how to achieve this would be appreciated.

A: Creator of PEGKit here.
I understand your ultimate strategy (to collect/combine lines as single string objects), and agree that it makes sense, however, I disagree with your proposed tactic to achieve that (to alter tokenization to try to combine what are essentially multiple separate tokens into single tokens).
Combining lines into convenient string objects makes sense, but altering tokenization to achieve that, doesn't make sense IMO (at least not with a recursive descent parsing kit PEGKit) when the lines in question don't have obvious 'bracketing' characters like quotes or brackets.
You could treat the passageTitle lines starting with :: as single-line Comment tokens, but I probably wouldn't since I gather they are semantically not comments.
So instead of merging multiple tokens via the tokenizer, you should merge multiple tokens in the more natural way for PEGKit: in the parser delegate callbacks.
We have two different cases to deal with here:

*

*The passageTitle lines

*The contentLine lines

In your grammar, remove this line so we won't be treating passageTitles as Comment tokens (you didn't have that completely correctly configured anyhow, but never mind that):
[t.commentState addSingleLineStartMarker:@"::"];

And also in your grammar, remove the ! from your passageStart rule so that those tokens won't be discarded:
passageStart            = '::';

That's all for the grammar. Now in your Parser Delegate callbacks, implement the two necessary callback methods for the title and content lines. And in each callback, pull all of the necessary tokens off the PKAssembly's stack, and merge them into a single string (in reverse).
@interface TweeDelegate : NSObject
@end

@implementation TweeDelegate

- (void)parser:(PKParser *)p didMatchPassageTitle:(PKAssembly *)a {
    NSArray *toks = [a objectsAbove:[PKToken tokenWithTokenType:PKTokenTypeSymbol stringValue:@"::" doubleValue:0.0]];
    [a pop]; // discard `::`

    NSMutableString *buf = [NSMutableString string];

    for (PKToken *tok in [toks reverseObjectEnumerator]) {
        [buf appendFormat:@"%@ ", tok.stringValue];
    }

    CFStringTrimWhitespace((CFMutableStringRef)buf);

    NSLog(@"Title: %@", buf); // Passage One
}

- (void)parser:(PKParser *)p didMatchContentLine:(PKAssembly *)a {
    NSArray *toks = [a objectsAbove:nil];

    NSMutableString *buf = [NSMutableString string];

    for (PKToken *tok in [toks reverseObjectEnumerator]) {
        [buf appendFormat:@"%@ ", tok.stringValue];
    }

    CFStringTrimWhitespace((CFMutableStringRef)buf);

    NSLog(@"Content: %@", buf); // P1 Line One
}

@end

I receive the following output:
Title: Passage One
Content: P1 Line One
Content: P1 Line Two
Title: Passage Two
Content: P2 Line One
Content: P2 Line Two

As for what to do with these strings once you have created them, I'll leave up to you :). Hope that helps.


text:
Q: Temporally share of category by timestamps using pandas Lets say we have a changing object with timestamps for each state resulting in the following DataFrame:
id  category timestamp
0   A        2022-10-04T00:00:00.000Z
1   B        2022-10-04T02:00:00.000Z
2   C        2022-10-04T10:00:00.000Z
3   A        2022-10-04T11:00:00.000Z
4   B        2022-10-04T12:00:00.000Z

How to get the temporally shares of id 0-3 category using the timestamps:
A: 3h / 0.2500
B: 8h / 0.6667
C: 1h / 0.0833

A: With the dataframe you provided:
df = pd.DataFrame(
    {
        "id": [0, 1, 2, 3, 4],
        "category": ["A", "B", "C", "A", "B"],
        "timestamp": [
            "2022-10-04T00:00:00.000Z",
            "2022-10-04T02:00:00.000Z",
            "2022-10-04T10:00:00.000Z",
            "2022-10-04T11:00:00.000Z",
            "2022-10-04T12:00:00.000Z",
        ],
    }
)

Here is one way to do it:
# Change dtype
df["timestamp"] = pd.to_datetime(df["timestamp"])

# Evaluate delta between rows
df["delta"] = df["timestamp"].shift(-1).dt.hour - df["timestamp"].dt.hour
df["delta"] = df["delta"].fillna(0)

# Sum results and get percentages
df = (
    df.groupby("category")["delta"]
    .agg(sum)
    .reset_index()
    .assign(perc=lambda df_: df_["delta"] / df_["delta"].sum())
)

print(df)
# Output
  category  delta      perc
0        A    3.0  0.250000
1        B    8.0  0.666667
2        C    1.0  0.083333


text:
Q: Passing array as argument to enum constructor: syntax issues I am creating an enigma simulation program for some practice with enums.
The following is a preliminary draft for the enum of a machine, so I don't have any of the specifics, yet.
The issue is that my IDE keeps saying that the curly braces are not supposed to be there, at the point I am trying to pass an array into the enum constructor.
Is there something wrong with my enum constructor or the enum constant declaration? How can I correct this to make it work?
public enum MACHINETYPE {
    WehrmachtEnigma (4, {true, true, true, false}),
    KriegsmarineM4(4, {true, true, true, true}),
    Abwehr(4, {true, true, true, true});

    private final int ROTORS_COUNT;
    private final boolean[] STEPPING;

    private MACHINETYPE(int rotors, boolean[] stepping){
        ROTORS_COUNT = rotors;
        STEPPING = stepping;
    }
}

A: You are not declaring your arrays properly. They should be declared using new boolean[] { ... }. However as your arrays are arguments to a constructor you could shorten your declarations by using a varargs notation. This will remove your error message.
enum MACHINETYPE{
    WehrmachtEnigma (4, true, true, true, false),
    KriegsmarineM4(4, true, true, true, true),
    Abwehr(4, true, true, true, true);

    private final int ROTORS_COUNT;
    private final boolean[] STEPPING;

    private MACHINETYPE(int rotors, boolean... stepping){
        ROTORS_COUNT = rotors;
        STEPPING = stepping;
    }
}


text:
Q: av_interleaved_write_frame return 0 but no data written I use the ffmpeg to stream the encoded aac data , i use the
av_interleaved_write_frame()

to write frame.
The return value is 0,and it means success as the description.

Write a packet to an output media file ensuring correct interleaving.
The packet must contain one audio or video frame. If the packets are already correctly interleaved, the application should call av_write_frame() instead as it is slightly faster. It is also important to keep in mind that completely non-interleaved input will need huge amounts of memory to interleave with this, so it is preferable to interleave at the demuxer level.
Parameters
s  media file handle
pkt    The packet containing the data to be written. pkt->buf must be set to a valid AVBufferRef describing the packet data. Libavformat takes ownership of this reference and will unref it when it sees fit. The caller must not access the data through this reference after this function returns. This can be NULL (at any time, not just at the end), to flush the interleaving queues. Packet's stream_index field must be set to the index of the corresponding stream in s.streams. It is very strongly recommended that timing information (pts, dts duration) is set to correct values.
Returns
0 on success, a negative AVERROR on error.

However, I found no data written.
What did i miss ? How to solve it ?

A: av_interleaved_write_frame() must hold data in memory before it writes it out. interleaving is the process of taking multiple streams (one audio stream, one video for example) and serializing them in a monotonic order. SO, if you write an audio frame, it will keep in in memory until you write a video frame that comes 'later'. Once a later video frame is written, the audio frame can be flushed' This way streams can be processed at different speeds or in different threads, but the output is still monotonic. If you are only writing one stream (one acc stream, no video) then use av_write_frame() as suggested.


text:
Q: How make web application color scheme changeable using react? Let's say, we have a react web application, developed with react-bootstrap. This application has to be customizable with a color picker. The user selects the base color and the color scheme with several automatically chosen secondary colors is adopted throughout the whole web application GUI.
Remembering that react-way is to use inline styles for each individual component, I'm wondering how to do this in react with react-bootstrap?

A: You might want to look in React CSS Modules, which will allow you to use dynamic style objects. The code can be read easily and will function properly. This will however require to have predefined themes.
The second approach is having the color defined in redux store or adjacent component, that passes it as prop to all of it's children.
However I advise not to let user pick any color with a custom color picker. If you let the user pick a color with RGB, remember there are 16777216 color combinations. You cannot just make alternative color all that easily by darkening any given color, since there is a great chance that changing only e.g. the brightness to lower might reduce contrast with the secondary color.

A: If you want to make your app themable you might need:

*

*Tool to create themes

*Approach to implement this themes to your app

As a tool you might try this storybook-addon-material-ui (wich allows to create theme objects for all purposes despite the presence of Material-UI in the title)
Then to provide your themes to your app you may use react-theme-provider. It just pass theme data into your Components via context, so you can implement any framework or set your colors manualy when you need it. It also has an API for theme switching.


text:
Q: Running google chrome puppeteer on Vultr, Digital Ocean, Heroku, Or GAE I have tried to run Google Chrome puppeteer on Heroku, GAE flex, Digital Ocean, and Vultr but at the route where I use puppeteer the instance just hangs until it errors with 502. I'm using this simple code:
var express = require('express');
var router = express.Router();
const puppeteer = require('puppeteer');

router.get('/', function(req, res, next) {
    (async() => {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto('http://example.com');
        await page.screenshot({path: 'example.png'});

        browser.close();
        res.send('screen grabbed');
    })();
});

module.exports = router;

I know puppeteer works with node 6 now but I'm setting package.json as follows:
{
  "name": "puppeteer",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www",
    "deploy": "gcloud app deploy --version dev"
  },
  "engines": {
    "node": "8.4.0"
  },
  "dependencies": {
    "body-parser": "~1.17.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.3",
    "express": "~4.15.2",
    "morgan": "~1.8.1",
    "pug": "~2.0.0-beta11",
    "puppeteer": "^0.10.2",
    "serve-favicon": "~2.4.2"
  }
}

In Vultr Ubuntu 16.04 x64 I get the following error:

Error: Failed to launch chrome!
/root/mysite/node_modules/puppeteer/.local-chromium/linux-497674/chrome-linux/chrome: error while loading shared libraries: libpangocairo-1.0.so.0: cannot open shared object file: No such file or directory

A: I tried the above answer but no luck in DigitaOcean Ubuntu droplet.
So I installed google-chrome-stable in the droplet, that works.

*

*Add Key:
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -

*Set repository:
echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | sudo tee /etc/apt/sources.list.d/google-chrome.list

*Install package:
sudo apt-get update
sudo apt-get install google-chrome-stable

A: I solved by making sure the following dependencies for puppeteer were installed if not :
Installed all the dependencies
sudo apt-get install gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget

Then pass args to the puppeteer launch command like so:
(async() => {

const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
const page = await browser.newPage();
await page.goto('http://example.com');
await page.screenshot({path: 'example.png'});
res.send('screen grabbed');
browser.close();
})();


text:
Q: Reading a private authenticated image from Amazon S3 with Imagick PHP I am fairly new to both Amazon S3 and the Imagick PHP library, but so far have been able to accomplish what I want with it (ie: uploading files and generating a range of thumbnail images). Currently, I am hung up on determining if it is possible for Imagick to read an authenticated image from S3. I would like to be able to do this in order to read back in original images for editing.
The following works when permissions for my file are set to grantee: Everyone (a public read), but not otherwise. (I've set the overall policy for my bucket to restrict access to only certain domains, including localhost where I am testing now):
$sourcePath = "https://s3.amazonaws.com/myBucket/folder/exampleFile-9203914980.43.jpg";
$image = new Imagick($sourcePath);

The above code fails to execute. Is there any setting in either S3 or Imagick that will enable the image to be read? Thanks in advance for your help!

A: I managed to avoid having to save the image before creating the Imagick object by using the S3 Stream Wrapper:
https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-stream-wrapper.html
$client->registerStreamWrapper();
$data = file_get_contents('s3://bucket/key');
$im = new Imagick();
$im->readImageBlob($data);

$client is the same as $s3 in Jeremy Lindblom's answer - you need to create an S3 client first as shown there.

A: You should probably download the image locally before trying to work with it in Imagick. You could use the AWS SDK for PHP to do this with some code like the following:
$s3 = Aws\S3\S3Client::factory(array(
    'key'    => '<your-aws-access-key-id>',
    'secret' => '<your-aws-secret-key>'
));

$bucket = 'myBucket';
$key = 'folder/exampleFile-9203914980.43.jpg';
$tempImage = '/tmp/' . $bucket . '/' . $key;

$s3->getObject(array(
    'Bucket' => $bucket,
    'Key'    => $key,
    'SaveAs' => $tempImage
));

$image = new Imagick($tempImage);

// do stuff
// ...

unlink($tempImage);

You can learn more about how to use the S3 client on the SDK's user guide for S3.


text:
Q: WPForms - Get Recaptcha value to perform manual control I'm using the 'wpforms_frontend_form_action' filter to change the action attribute of my WPforms form.
I also use Google recaptcha v3 on that form, but its effect is limited and i still receive spam because bots get the modified action attribute which contains my final url directly in the script to bypass control.
What i'd need is to get the recaptcha value of my WPform and then perform the control myself before sending data to my final url.
How to get the WPforms recaptcha value ? The 'wpforms[recaptcha]' field is empty...
EDIT : I guess the recaptcha challenge is not launched until the user submits the form, so maybe there is an other way to change the action url of my WPForm AFTER the submission and not through the 'wpforms_frontend_form_action' filter ?
Thanks for help


text:
Q: Crash when save a photo I have a strange crash when I save a UIImage into camera roll.
I Use this code:
UIImageWriteToSavedPhotosAlbum (_originalImage, self,  @selector(photoSaved:didFinishSavingWithError:contextInfo:), nil);

-(void)photoSaved:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
if(!error){
    NSLog(@"Photo saved to library!");
} else{
    NSLog(@"Saving failed :(");
}

}
This is the Log:
2012-11-10 20:43:29.868 MyApp[5012:1a303] Photo saved to library!

This is the BT:
(lldb) bt
* thread #1: tid = 0x1f03, 0x024e509b libobjc.A.dylib`objc_msgSend + 15, stop reason = EXC_BAD_ACCESS (code=1, address=0x3094a576)
frame #0: 0x024e509b libobjc.A.dylib`objc_msgSend + 15
frame #1: 0x01b84a8b PhotoLibrary`-[PLUILibraryViewController updateNavigationItemButtons] + 216
frame #2: 0x01b6f054 PhotoLibrary`-[PLLibraryViewController(OverridePoints) updateInterfaceForHasContentChange] + 867
frame #3: 0x01c3c228 PhotoLibrary`-[PLAbstractLibraryViewController _updateHasContent] + 295
frame #4: 0x01c3c7d0 PhotoLibrary`-[PLAbstractLibraryViewController _updateAlbumsWithNotification:] + 681
frame #5: 0x01c3b870 PhotoLibrary`-[PLAbstractLibraryViewController albumListDidChange:] + 272
frame #6: 0x01b84c5b PhotoLibrary`-[PLUILibraryViewController albumListDidChange:] + 236
frame #7: 0x01525a29 Foundation`__57-[NSNotificationCenter addObserver:selector:name:object:]_block_invoke_0 + 40
frame #8: 0x0267d855 CoreFoundation`___CFXNotificationPost_block_invoke_0 + 85
frame #9: 0x0267d778 CoreFoundation`_CFXNotificationPost + 1976
frame #10: 0x0146a234 Foundation`-[NSNotificationCenter postNotification:] + 121
frame #11: 0x02d217a4 PhotoLibraryServices`-[PLChangeNotificationCenter _postEnqueuedNotifications] + 425
frame #12: 0x02d1f771 PhotoLibraryServices`-[PLChangeNotificationCenter _sendNotificationsForSplitChanges] + 307
frame #13: 0x02d23614 PhotoLibraryServices`-[PLChangeNotificationCenter managedObjectContext:didProcessRemoteContextSave:usingObjectIDs:] + 56
frame #14: 0x02d017cc PhotoLibraryServices`-[PLSharedManagedObjectContext _mergeChangesFromDidSaveDictionary:usingObjectIDs:] + 229
frame #15: 0x03edfd2f CoreData`__+[NSManagedObjectContext(_NSCoreDataSPI) _mergeChangesFromRemoteContextSave:intoContexts:]_block_invoke_4 + 159
frame #16: 0x03e67d03 CoreData`developerSubmittedBlockToNSManagedObjectContextPerform + 99
frame #17: 0x01af18d9 libdispatch.dylib`_dispatch_barrier_sync_f_slow_invoke + 93
frame #18: 0x01af2509 libdispatch.dylib`_dispatch_main_queue_callback_4CF + 353
frame #19: 0x025e9803 CoreFoundation`__CFRunLoopRun + 2003
frame #20: 0x025e8d84 CoreFoundation`CFRunLoopRunSpecific + 212
frame #21: 0x025e8c9b CoreFoundation`CFRunLoopRunInMode + 123
frame #22: 0x02a2d7d8 GraphicsServices`GSEventRunModal + 190
frame #23: 0x02a2d88a GraphicsServices`GSEventRun + 103
frame #24: 0x00b63626 UIKit`UIApplicationMain + 1163
frame #25: 0x000026ca MyApp`main + 170 at main.m:16

A: Full disclosure: I hope this makes sense as I'm pretty new to Objective-C, but I recently had a similar problem.  I found out that my image was not being retained when I called the didFinishSavingWithError:contextInfo: method after selecting an image from the Camera Roll.  What worked for me was adding the withObject: argument to my method call, as shown here:
[self performSelector:@selector(image:didFinishSavingWithError:contextInfo:) withObject:_originalImage];
This way, the image was retained when the didFinishSavgngWithError:contextInfo: method was called where previously it was not.  Again, I'm new to Objective-C but I hope that helps...or at least points you in the right direction.  What would also be helpful is if you could tell me at what point your app crashes (i.e. when you call the imagePicker, when you select an image from the camera roll, etc.).