text:
Q: How to display the searched data on the jgrid this is related to my previous question about jqgrid. im doing now a search button that would search my inputed text from the server and display those data (if there is) in the jqgrid. Now, what i did is i create a global variable that stores the filters. Here's my javascript code for my searching and displaying:
    filter = ''; //this is my global variable for storing filters
    $('#btnsearchCode').click(function(){
       var row_data = '';
       var par = {
          "SessionID": $.cookie("ID"),
          "dataType": "data",
          "filters":[{
             "name":"code",
             "comparison":"starts_with",
             "value":$('#searchCode').val(),
          }],
          "recordLimit":50,
          "recordOffset":0,
          "rowDataAsObjects":false,
          "queryRowCount":true,
          "sort_descending_fields":"main_account_group_desc"
       }
       filter="[{'name':'main_account_group_code','comparison':'starts_with','value':$('#searchCode').val()}]";
       $('#list1').setGridParam({
        url:'json.php?path=' + encodeURI('data/view') + '&json=' + encodeURI(JSON.stringify(par)),
        datatype: Settings.ajaxDataType,
       });
       $('#list1').trigger('reloadGrid');

       $.ajax({
           type: 'GET',
           url: 'json.php?' + $.param({path:'data/view',json:JSON.stringify(par)}),
           dataType: Settings.ajaxDataType,
           success: function(data) {
              if ('error' in data){
                 showMessage('ERROR: ' + data["error"]["msg"]);
              }
              else{
                 if ( (JSON.stringify(data.result.main.row)) <= 0){
                     alert('code not found');
                 }
                 else{
                     var root=[];
                     $.each(data['result']['main']['rowdata'], function(rowIndex,  rowDataValue) {
                     var row = {};
                     $.each(rowDataValue, function(columnIndex, rowArrayValue) {
                        var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
                        row[fldName] = rowArrayValue;
                     });
                     root[rowIndex] = row;
                     row_data += JSON.stringify(root[rowIndex]) + '\r\n';
                });
             }
             alert(row_data);  //this alerts all the data that starts with the inputed text...
          }
      }
    });
  }

i observed that the code always enter this (i am planning this code to use with my other tables) so i put the filter here:
   $.extend(jQuery.jgrid.defaults, {
       datatype: 'json',
       serializeGridData: function(postData) {
          var jsonParams = {
            'SessionID': $.cookie("ID"),
            'dataType': 'data',
            'filters': filter,
            'recordLimit': postData.rows,
            'recordOffset': postData.rows * (postData.page - 1),
            'rowDataAsObjects': false,
            'queryRowCount': true,
            'sort_fields': postData.sidx
          };

          return 'json=' + JSON.stringify(jsonParams);
      },
      loadError: function(xhr, msg, e) {
        showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
      },
    });

now, my question is, why is it that that it displayed an error message "Server Error: Parameter 'dataType' is not specified"? I already declared dataType in my code like above but it seems that its not reading it. Is there anybody here who can help me in this on how to show the searched data on the grid?(a function is a good help)

A: I modified your code based on the information from both of your questions. As the result the code will be about the following:
var myGrid = $("#list1");

myGrid.jqGrid({
    datatype: 'local',
    url: 'json.php',
    postData: {
        path: 'data/view'
    },
    jsonReader: {
        root: function(obj) {
            var root = [], fields;

            if  (obj.hasOwnProperty('error')) {
                alert(obj.error['class'] + ' error: ' + obj.error.msg);
            } else {
                fields = obj.result.main.metadata.fields;
                $.each(obj.result.main.rowdata, function(rowIndex, rowDataValue) {
                    var row = {};
                    $.each(rowDataValue, function(columnIndex, rowArrayValue) {
                        row[fields[columnIndex].name] = rowArrayValue;
                    });
                    root.push(row);
                });
            }

            return root;
        },
        page: "result.main.page",
        total: "result.main.pageCount",
        records: "result.main.rows",
        repeatitems: false,
        id: "0"
    },
    serializeGridData: function(postData) {
        var filter = JSON.stringify([
            {
                name:'main_account_group_code',
                comparison:'starts_with',
                value:$('#searchCode').val()
            }
        ]);

        var jsonParams = {
            SessionID: $.cookie("ID"),
            dataType: 'data',
            filters: filter,
            recordLimit: postData.rows,
            recordOffset: postData.rows * (postData.page - 1),
            rowDataAsObjects: false,
            queryRowCount: true,
            sort_descending_fields:'main_account_group_desc',
            sort_fields: postData.sidx
        };

        return $.extend({},postData,{json:JSON.stringify(jsonParams)});
    },
    loadError: function(xhr, msg, e) {
        alert('HTTP error: ' + JSON.stringify(msg) + '.');
    },
    colNames:['Code', 'Description','Type'],
    colModel:[
        {name:'code'},
        {name:'desc'},
        {name:'type'}
    ],
    rowNum:10,
    viewrecords: true,
    rowList:[10,50,100],
    pager: '#tblDataPager1',
    sortname: 'desc',
    sortorder: 'desc',
    loadonce:false,
    height: 250,
    caption: "Main Account"
});
$("#btnsearchCode").click(function() {
    myGrid.setGridParam({datatype:'json',page:1}).trigger("reloadGrid");
});

You can see the code live here.
The code uses datatype:'local' at the beginning (at the 4th line), so you will have no requests to the server if the "Search" button is clicked. The serializeGridData the data from the postData parameter of serializeGridData will be combined with the postData parameter of jqGrid (the parameter "&path="+encodeURIComponent('data/view') will be appended). Additionally all standard jqGrid parameters will continue to be sent, and the new json parameter with your custom information will additionally be sent.
By the way, if you want rename some standard parameters used in the URL like the usage of recordLimit instead of rows you can use prmNames parameter in the form.
prmNames: { rows: "recordLimit" }


text:
Q: how to update value in a table from other table I need to update value in table with (own value) - (value in other table Like) for an id
I have tried this
UPDATE FULLTABLE
            SET FULLTABLE.Balance = FULLTABLE.Balance - AdvBalance.balance
            WHERE FULLTABLE.id= AdvBalance.advid;

and this
 update fulltable f set f.balance = ( f.balance -

select a.balance from advbalance a where a.advid=f.advertiserID)

first one is throwing error that invalid identifier. second one some other error.
I am using oracle db.
Please suggest a way to do this.
Thanks

A: You need a subselect to get the value from another table:
UPDATE FULLTABLE ft
  SET ft.Balance = ft.Balance - (SELECT ab.balance
                                   FROM AdvBalance ab
                                 WHERE ft.id = ab.advid);

This will fail if it is possible that the subquery will return more than one row, but if this is the case, then you must decide how to find the right value to be subtracted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Distance of binary strings to produce the lexicographical order Indexing objects like elements of a Cantor Set or nodes of a Binary Tree can result in a enconding system of binary strings like illustrated bellow:

The illustrated indexes form a finite set,  $$C_3=\{0,00,000,001,... ,111\}$$
We can provide the set $C_3$  of a comparison operation, offering the same elements in a sequence with the lexicographical order (also illustred with the sequence into square breakets), that is a total order relation.
The same set can be mapped into a set of numerical pairs (bitLength,value), $$V_3=\{(1,0), (2,0), (3,0), (3,1), (2,1), ... , (3,7)\}$$
where 0=(1,0), 00=(2,0), 000=(3,0), 001=(3,1), 01=(2,1), ... etc. Any element $x$ is a pair $(x_{bitLength},x_{value})$.  A generic $V_k$ have elements with $bitLength \le k$. In fact this generic set was defined in this other question as:
$$V_k = \{\forall x = (l,n) ~|~  l,n \in \mathbb{N} ~\land~ bitLength(n) \le l \le k  \}$$
where the function $bitLength(n>0)=\lceil log_2(n)+1 \rceil$ and the bit-length of zero is one.
Now we can express a distance $d(x,y,k)$  of two elements $x$ and $y$ of $V_k$, that can be used as mathematical reference to the lexicographical order... What is the $d(x,y,k)$ function? How to proof that is the correct function for any $k$?

... Or more simples, What the comparison function $cmp(x,y,k)$?
There are no special "metric", the aim is to sort, that is, to check the value of comparison. As usual convention is $cmp(x,y,k)=1$ when  $x>y$, $cmp(x,y,k)=0$ when $x=y$ and $cmp(x,y,k)=-1$ when $x>y$.

NOTES
Supposing that there are someting as dyadics that can be used in the proof... Seems good in some tests, but I do not know how use mathematical foundations or how to proof: d(x,y) = x.value/2^x.bitLength - y.value/2^y.bitLength
Some raw  data to tests, illustrating with all elements of $C_4$ and $V_4$:
(bits,value)    Binary representation
(1,0)           0
(2,0)           00
(3,0)           000
(4,0)           0000
(4,1)           0001
(3,1)           001
(4,2)           0010
(4,3)           0011
(2,1)           01
(3,2)           010
(4,4)           0100
(4,5)           0101
(3,3)           011
(4,6)           0110
(4,7)           0111
(1,1)           1
(2,2)           10
(3,4)           100
(4,8)           1000
(4,9)           1001
(3,5)           101
(4,10)          1010
(4,11)          1011
(2,3)           11
(3,6)           110
(4,12)          1100
(4,13)          1101
(3,7)           111
(4,14)          1110
(4,15)          1111

Some distances to test:

*

*d(00,01) = d(10,11)

*|d(000,0)| = |d(1,111)|

*d(1101,11) < d(1100,1101)

*...

A: The distance function $d(x,y,k)$ is arbitrary and can be simple... With scalar values we can use $d(x,y)=x-y$. In this problem $x$ and $y$ are vectors: $x=(x_l,x_n)$ and $y=(y_l,y_n)$. To keep simple we can suppose that exists a "score function" that transforms the vectors into scalars.
Lets start with the suggested score, based on  dyadic numbers: $score1(x)=x_n/2^{x_l}$. The only problem is about 0, 00, etc. (also 101 and 1010, etc.) that need different scores. A simple correction is to add a fraction $\alpha x_l$  that is less tham the minor value of $score1$, that is $\alpha k<score1(1)$. So:
$$score2(x,k) ~=~ score1(x)+\alpha_k x_l ~=~ x_n/2^{x_l}+\frac{x_l}{k \times 2^{k+1}}$$
Using the example of $k=4$ (the set $V_4$), the result is:
x               Binary      Score1      Score2
(1,0)           0           0.000       0.008
(2,0)           00          0.000       0.016
(3,0)           000         0.000       0.023
(4,0)           0000        0.000       0.031
(4,1)           0001        0.063       0.094
(3,1)           001         0.125       0.148
(4,2)           0010        0.125       0.156
(4,3)           0011        0.188       0.219
(2,1)           01          0.250       0.266
(3,2)           010         0.250       0.273
(4,4)           0100        0.250       0.281
(4,5)           0101        0.313       0.344
(3,3)           011         0.375       0.398
(4,6)           0110        0.375       0.406
(4,7)           0111        0.438       0.469
(1,1)           1           0.500       0.508
(2,2)           10          0.500       0.516
(3,4)           100         0.500       0.523
(4,8)           1000        0.500       0.531
(4,9)           1001        0.563       0.594
(3,5)           101         0.625       0.648
(4,10)          1010        0.625       0.656
(4,11)          1011        0.688       0.719
(2,3)           11          0.750       0.766
(3,6)           110         0.750       0.773
(4,12)          1100        0.750       0.781
(4,13)          1101        0.813       0.844
(3,7)           111         0.875       0.898
(4,14)          1110        0.875       0.906
(4,15)          1111        0.938       0.969

Concluding: there are many possible functions, this one seems simple,
$$d(x,y,k)=score2(x,k)-score2(y,k)  ~=~ x_n/2^{x_l}-y_n/2^{y_l}+\frac{x_l-y_l}{k \times 2^{k+1}}$$

Algorithm of  lexicographical comparison
When using $d()$ as comparison function, it can be optimized; for example for $x_l=y_l$ can be replaced by the usual $d(x,y) ~=~ x_n-y_n$. Here a Javascript function to compare arbitrary-precision integers in the form x=(x.l,x.n), where  x.l is the bitLength (a small integer) and x.n the value, a BigInt.
function cmp_lexic(a,b) {
  let bdif = a.l - b.l
  if (bdif) {
   dif = (bdif>0)
     ? a.n/BigInt(2**bdif) - b.n     // normalize a
     : a.n - b.n/BigInt(2**(-bdif)); // normalize b
   if (!dif) dif = bdif;
  } else
   dif = a.n - b.n
  return dif? ((dif>0n)? 1: -1) : 0;
}

The comparison not depends on the maximal length k.


text:
Q: Win 10 - Display where Known Folder ?FOLDERID_Documents points to via Command line or Powershell Does anyone know a method for displaying where the Known Folder ?FOLDERID_Documents currently points to within Windows 10 (Version 1703)?
I need a method than can be carried out from the DOS Command line or from Powershell, as I am trying to troubleshoot a problem on a machine that will not allow me to use anything more groovy.
I'm not really a Powershell user so if I would ask for a nice and gentle approach if that is the way to go.
Is it possible to expose the value of ?FOLDERID_Documents with VB Script ?
I understand that ?FOLDERID_Documents is not an environment variable in the traditional sense. I also know that the environment variable %USERPROFILE% may point to the root location of where ?FOLDERID_Documents points to, but I live in hope that there must be a simple way of displaying the value of ?FOLDERID_Documents with a nice simple command.
According to the Microsoft Dev Centre (Ref: https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid):

KNOWNFOLDERID constants represent GUIDs that identify standard folders
  registered with the system as Known Folders. These folders are
  installed with Windows Vista and later operating systems, and a
  computer will have only folders appropriate to it installed.

It would appear that some applications, like SAS Version 9.4, make use of these KNOWNFOLDERIDs to direct themselves to the physical locations represented by generic folder such as My Documents and other applications do not. My problem is that for a pair of my SAS users, their Windows 10 installations appear to have suddenly forgotten where ?FOLDERID_Documents points to. They have only had this problem in the last few days.
As this problem is not affecting all users, I am trying to find a simple way to expose the value held by ?FOLDERID_Documents on an affected and an un-affected Windows installation so that I can raise it with our in-house technical support.

A: reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Personal


text:
Q: How to use foreach to loop through a file with variable variable? The following PHP code using foreach does not seem to work. I believe it has to do with "".
I've shared the entire codebase.
Does anyone know what is wrong with my statement?
// include/functions.php
<?php

    // Defining the basic cURL function
    function curl($url) {
        // Assigning cURL options to an array
        $options = Array(
            CURLOPT_RETURNTRANSFER => TRUE,  // Setting cURL's option to return the webpage data
            CURLOPT_FOLLOWLOCATION => TRUE,  // Setting cURL to follow 'location' HTTP headers
            CURLOPT_AUTOREFERER => TRUE, // Automatically set the referer where following 'location' HTTP headers
            CURLOPT_CONNECTTIMEOUT => 120,   // Setting the amount of time (in seconds) before the request times out
            CURLOPT_TIMEOUT => 120,  // Setting the maximum amount of time for cURL to execute queries
            CURLOPT_MAXREDIRS => 10, // Setting the maximum number of redirections to follow
            CURLOPT_USERAGENT => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1a2pre) Gecko/2008073000 Shredder/3.0a2pre ThunderBrowse/3.2.1.8",  // Setting the useragent
            CURLOPT_URL => $url, // Setting cURL's URL option with the $url variable passed into the function
        );

        $ch = curl_init();  // Initialising cURL
        curl_setopt_array($ch, $options);   // Setting cURL's options using the previously assigned array data in $options
        $data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable
        curl_close($ch);    // Closing cURL
        return $data;   // Returning the data from the function
    }

    // Defining the basic scraping function
    function scrape_between($data, $start, $end){
        $data = stristr($data, $start); // Stripping all data from before $start
        $data = substr($data, strlen($start));  // Stripping $start
        $stop = stripos($data, $end);   // Getting the position of the $end of the data to scrape
        $data = substr($data, 0, $stop);    // Stripping all data from after and including the $end of the data to scrape
        return $data;   // Returning the scraped data from the function
    }
?>

// code.php
<?php

//include functions
include_once("include/functions.php");

// Set URL
$url = "https://www.instituteforsupplymanagement.org/ismreport/mfgrob.cfm";
$source = curl($url);

// Collect dataset

$arr = array("PMI","New Orders");
    foreach ($arr as $value) {

       $data = scrape_between($source,"$$value","
");

       print_r($data);

}

?>

A: within the string the second $ is being treated as a string, so you end up with strings like '$PMI'. why not just assign your variable variable to a temp variable:
$start = $$value;
$data = scrape_between($source,"$start","
");

also I don't know how you plan to use "New Orders" as a variable name what with the space and all.
maybe you're trying to use "PMI" and "New Orders" in the string, in which case just drop the extra $


text:
Q: How to read save docx file contents in flask with flask-sqlalchemy? I am trying to save the contents of a docx file in my flask application, using the python-docx libray. It seems to work outside of flask, but not sure where I am making a mistake. Help needed.
I have been able to save the simple .txt files using the read() function.

Blockquote

@app.route('/add_document', methods = ['GET','POST'])
@login_required
def add_document():
    if request.method == 'POST':
        title=request.form['title']
        file = request.files['file']
        allowed_extensions = ['txt','doc','docx']
        filename = file.filename
        file_extension = filename.split('.', 1)[1].lower()
        content=''
        if file:
            if file_extension in allowed_extensions:
                if file_extension == 'txt':
                    content = str(file.read())
                if file_extension == 'docx':
                    content = ''.join([para.text for para in Document(filename).paragraphs])
        else:
            content = request.form['text']
        summary = auto_summarize(content,20,topicing,2)
        topic = ', '.join([i for i in topicing(content,3)])
        document = Document(title=title, content=content, summary=summary,
                            topic=topic, owner=current_user)
        db.session.add(document)
        db.session.commit()
        # reader.close()
        flash('Document uploaded! Please visit MyDocs to see it!','success')
        return redirect(request.url)
    return render_template('add_document.html')

Blockquote

A: the for loop for reading docx file is just fetching the first line of the file.
below is just a demo code that might fit in right.
import docx
doc = docx.Document("abc.docx")
fullText = []
a=''
for para in doc.paragraphs:
  fullText.append(para.text)
a='\n'.join(fullText)
print(a)

A: for loop read paragraph by paragraph from your .docx file
from docx import Document

document = Document("file_path/file_name.docx")
for p in document.paragraphs:
    print(p.text)


text:
Q: Dynamically set ListFillRange in Excel ComboBox I tried doing something like:
 cmbMyBox.ListFillRange = "E2"

But the combobox does not seem to populate.

A: Ok, don't mean to answer my own question again but this ListFillRange property on combobox for Excel was absolutely maddening. Here's the final code that I implemented.
   Sheet1.Range("E3").CurrentRegion.Select
   Dim example as Range
   Set example = Selection

   With cmbMyBox
     .ListFillRange = example.Address(0, 0, x1A1, True)
   End With

The trouble here was that I was trying to dynamically set the combobox using a dynamic range which changes depending on what user inputted values were given. As far as I understand I couldn't use a named range because named ranges are FIXED, e.g (A3:Z20) and cannot be adjusted.

A: I was facing similar issue, not being able to populate the ActiveX ComboBox with list reference peeked from a cell's validation rule.
Similarly to Firedrawndagger's own solution I went for manually translating the validation rule to a format that is understood by the .ListFillRange.
I realised also, that it needs to be in a Workbook-scope  format, otherwise the call will not work from other sheets.
This works with All validation source formats, including: $A$1 / =NamedRange / =INDIRECT("Table1[Col2]")
The translation was:
Dim xStr As String
xStr = Target.Validation.Formula1
xStr = Right(xStr, Len(xStr) - 1)
xStr = Split(Range(xStr).Address(, , , True), "]")(1)
'...other irrelevant code
.ListFillRange = xStr

A: First of all, for trying to set the listfillrange from VBA, you need to include the '=' sign, like this:
combobox.ListFillRange = "=E3:E13"

and not combobox.ListFillRange = "E3:E13", this won't work.
You could have a dynamic named range, for example:
listItems: "=Sheet1!$A$1:INDEX(Sheet1!$A:$A;COUNTA(Sheet1!$A:$A))"

Use VBA to set the ListFillRange like this: combobox.ListFillRange = "=listItems"
Again, use the '=' sign!!
This dynamic range listItems grows/shrinks dynamically, depending on what values you have in column A.
I know I'm answering really late, but I noticed a lot of people thinking named ranges always have to be fixed, while they can be dynamic as well...
How do you do this?
In Excel 2007 and higher, you go to the ribbon-tab "Formulas" and click on the button "Name Manager"
Instead of selecting cells and giving them a name in that upper-left box, you can manage all your defined named ranges here.
Create a new one, and give it the value (without quotes):
"=Sheet1!$A$1:INDEX(Sheet1!$A:$A;COUNTA(Sheet1!$A:$A))".
There you go...
P.S. When you let the dynamic named range change, you should use VBA to re-set the .ListFillRange such that the combobox will refresh its list-items.

A: Private Sub ComboBox1_Change()

Me.ComboBox2.ListFillRange = "=" & ComboBox1.Value

End Sub

This also works. But you have to do either the defined names with the index and counta as already suggested, or you can refer to them twice while in a table. What I mean by that, is make your data a table. Refer to the column you want as the title of your option from Combobox1 and add a one to the name, For example Fruits1, then define a secondary named range that refers to Fruits1 and is called Fruits.
Fruits
Fruits1

A: Alternatively, this is how I do it:
Define a range name that includes header and trailer rows plus one data row to start, say "DataList"
Then define the following data range name sans the header and trailer records using the offset function.
Say "DataRange" = Offset(DataList,1,0,Rows(DataList)-2)

A: This is working fine on Excel 2010:
I have a list of items in column "AN" that changes (get bigger/shorter) every week. I have created a variable called "c" which contains the number of items in the list. By using this variable, the ComboBox (positioned on cells S7:U7) will now dinamically show the items actually contained in the list (no empty spaces or missing items in the combobox).
Code:
Dim rng As Range

Set rng = ActiveSheet.Range("S7:U7")
ActiveSheet.DropDowns.Add(rng.Left, rng.Top, rng.Width, rng.Height).Select
With Selection
    .ListFillRange = "AN1:AN" & c
    .LinkedCell = "$V$7"
    .DropDownLines = 8
    .Display3DShading = False
End With

A: I had a similar problem, i had an ActiveX Listbox in the worksheet. What worked for me is this:
Sheets(1).OLEObjects("ListBox1").ListFillRange = "Sheet2!A1:C20"

ActiveX OLEObjects are pretty straight forward.


text: Q: How can I install dual operating system in UEFI boot method. I have original UEFI windows 8.1 in my laptop. I want to install windows 7 also on the same laptop. I tried some ways but it was failure and got succeeded when I installed both legacy operating systems.Is it possible..? someone can help me..?


text:
Q: java.lang.IllegalStateException: Fragment already active I am creating a walkthrough activity with a ViewPager and fragments, I have been able to successfully create the walkthrough, but the issue is, I can only swipe to the front, if I try to swipe back the app crashes, I tried replicating it on another test app which worked perfectly both front and back, although that one uses a TextView while this one uses an ImageView.
I need help figuring out why it crashes while swiping to back.
public class WalkThroughActivity extends AppCompatActivity {

    ViewPager mPager;
    LinearLayout mLinearLayout;
    CustomPagerAdapter mAdapter;
    MyPageIndicator mIndicator;

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

        mPager = (ViewPager) findViewById(R.id.pager);
        mLinearLayout = (LinearLayout) findViewById(R.id.pagesContainer);
        List < Fragment > fragments = new ArrayList < >();
        fragments.add(ContentFragment.newInstance(R.drawable.walkthrough_card_1));
        fragments.add(ContentFragment.newInstance(R.drawable.walkthrough_card_2));
        fragments.add(ContentFragment.newInstance(R.drawable.walkthrough_card_3));

        mAdapter = new CustomPagerAdapter(getSupportFragmentManager(), fragments);
        mPager.setAdapter(mAdapter);
        mIndicator = new MyPageIndicator(this, mLinearLayout, mPager, R.drawable.indicator_circle);
        mIndicator.setPageCount(fragments.size());
        mIndicator.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mIndicator.cleanup();
    }

    static class CustomPagerAdapter extends FragmentStatePagerAdapter {

        List < Fragment > mFrags = new ArrayList < >();

        public CustomPagerAdapter(FragmentManager fm, List < Fragment > frags) {
            super(fm);
            mFrags = frags;
        }

        @Override
        public Fragment getItem(int position) {
            int index = position % mFrags.size();
            return mFrags.get(index);
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

    }
}

ContentFragment
public class ContentFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";

    private int mParam1;

    public ContentFragment() {
        // Required empty public constructor
    }

    public static ContentFragment newInstance(int param1) {
        ContentFragment fragment = new ContentFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getInt(ARG_PARAM1);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.indicator_fragment, container, false);;
        ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
        imageView.setImageResource(mParam1);
        return view;
    }

    public int getmParam1() {
        return mParam1;
    }

}

Error Log
FATAL EXCEPTION: main
    Process: com.simpumind.shoopa, PID: 8207
        java.lang.IllegalStateException: Fragment already active
            at android.support.v4.app.Fragment.setInitialSavedState(Fragment.java:576)
            at android.support.v4.app.FragmentStatePagerAdapter.instantiateItem(FragmentStatePagerAdapter.java:114)
            at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1034)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1216)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
            at android.support.v4.view.ViewPager$3.run(ViewPager.java:273)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
            at android.view.Choreographer.doCallbacks(Choreographer.java:670)
            at android.view.Choreographer.doFrame(Choreographer.java:603)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: I believe that offending lines of code are
    @Override
    public Fragment getItem(int position) {
        int index = position % mFrags.size();
        return mFrags.get(index);
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

I'm not sure what you are trying to achieve but this code is very bad. It makes the ViewPager believe that you have much more fragments than you actually have AND reuse the same fragement several times. Assume that mFrags.size() is 2 and  the ViewPager asks for #0, #1 and #2 - you would return the fragment #0 twice and the ViewPager  might try to pass the same fragment through lifecycle twice. This re-usage of fragments is most probably the source of the exception you see.
By the way, what's wrong with straightforward?
    @Override
    public Fragment getItem(int position) {
        return mFrags.get(position);
    }

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


text:
Q: Why does my boolean return 'undefined'? I'm working through Eloquent Javascript and there's an exercise to make an every function, which takes an array and a function and returns true or false depending on what all the items in the array return after going through the function.
I'm confused because when I do console.log() within the function, I get the boolean twice...but when I do console.log(every(arr, func)), I get undefined.
var every = function(arr, req){
    arr.map(function(item){
        return req(item);
    }).reduce(
        function(total, num){

            // this returns: true
            //               true
            console.log(total && num);

            return total && num;
    });

}

// This returns undefined
console.log(every([NaN, NaN, NaN], isNaN));

So why do I get true twice inside my function, and why do I get undefined?
I'm using node as a console.

A: You need to add a return statement to your outermost function, like this:
var every = function(arr, req){
    return arr.map(function(item){
        return req(item);
    }).reduce(
        function(total, num){
            return total && num;
    });
}

// This returns true
console.log(every([NaN, NaN, NaN], isNaN));

EDIT: Fixed return value, thanks @Kevin B


text:
Q: How to get the screen bit depth of iPhone? In NSScreen Class Reference of Mac OS there is a "depth" method of NSSCreen which can get the bit depth of the screen, but that doesn't exsit in UIScreen class of iOS.Does any one know how can detect the bit depth of the screen on iPhone?
NSScreen Class Reference of Mac OS

A: All current Mac OS X and iOS devices always run in 32-bit color.
It used to be the case that Mac OS X supported 8- and 16-bit color modes, but that is no longer the case. iOS has always run in 32-bit color, so there is no need for a method to query the color depth.

A: 32-bit color refers to 8 bits each for R, G, and B, and 8 bits for alpha transparency. Hence the screen depth would seem to relate to the RGB values.


text:
Q: Limit of the mean value of partial sums? I'm supposed to construct a sequence of real numbers ${a_{n}}$ such that $\limsup_{n\to\infty} a_n=\infty$ but $\lim_{n\to\infty} b_n= \frac {a_{1}+a_{2}+...+a_{n}}{n} =0$.

A: Hint: Use the sequence $$\sqrt{1},-\sqrt{1}, \sqrt{2},-\sqrt{2},\sqrt{3},-\sqrt{3},\sqrt{4},-\sqrt{4},\sqrt{5},\dots.$$

A: What you need is that $a_n$ is big only from time to time.
One example I can think of is to take
$$
a_n=\begin{cases}n^{1/2},&\ n=2^{k/2}\ \text{ for some }k\in\mathbb Z\\0,&\ \text{ otherwise }\end{cases}
$$
Then $\limsup a_n=\infty$, but if $2^{k}\leq n\leq 2^{k+1}$ then
$$
\frac{a_1+\ldots+a_n}n\leq\frac{a_1+\ldots+a_{2^{k+1}}}{2^k}
=\frac1{2^k}\,\sum_{j=0}^k2^{j/2}=\frac{2^{(k+1)/2}-1}{2^k(\sqrt2-1)}
\leq\frac{2^{(k+1)/2}}{2^k}\leq\frac1{2^k}\leq\frac2n
$$

A: Let $a_n = (-1)^{n-1}\ln(\lfloor \frac{n+1}{2} \rfloor)$.
$\forall k , \,\, a_{2k} = -\ln(k) = - a_{2k-1}$. Thus
$$\forall k , \,\, m_{2k} = \frac{1}{2k}\sum_{i=1}^{2k} a_{i} = 0$$
and
$$\forall k , \,\, m_{2k+1} = \frac{1}{2k+1}\sum_{i=1}^{2k+1} a_{i} = \frac{a_{2k+1}}{2k+1}$$
Clearly $a_{2k+1} \to +\infty$ and $\frac{a_{2k+1}}{2k+1} \to 0$ so the sequence $(a_n)$ is what you are looking for.
P.S. The general idea here is to pick an increasing sequence $(s_n)$ that tends to infinity at a rate slower than $n$. For example you can take $s_n = \ln(n)$ or $s_n = n^\gamma$ with $0 < \gamma < 1$. Just make sure that $s_n \to  +\infty$and that $\frac{s_n}{n} \to 0$. Then the  sequence defined as $s_1, -s_1, s_2, -s_2, \cdots$ will be a good one.

A: Intuitively, hardly any $a(n)$ are large so that $b(n)$ can go to $ 0$, and when $a_n$ is large, it is not "large compared to $n$". For example if $a(n)=0$ when $n$ is not a power of $2$ and $a(2^n)=n$. Note that the sequence $(a_n)_n$ cannot be monotonic. Remark : In general if a sequence $(x_n)_n$ converges to a finite limit $L$ then the sequence $y_n=(1/n)\sum_{j=1}^{j=n}x_n$ also converges to $L$, but the converse statement is false.

A: Let $a_{2^n} = n$ and $a_k = 0$ for all $k$ that are not a power of 2.  The partial averages behave like $O(n^2/2^n)$ but $\limsup_n a_n = 0$.


text:
Q: spring data jpa unnecessary left join I have the following model:

I want to get all Institutions (Intituciones) with specified sectorId.
In the tbInstitucion model I have a relationship with tbSector:
 @ManyToOne(fetch=FetchType.LAZY)
 @JoinColumn(name="`sectorId`")
 private Sector sector;

is there a way to obtain a query like:
select *
from tbInstitucion
where sectorId = ?

I tried with: findBySector(Sector sector)
but with this I need an additional query to find the sector and findBySector is generating the following query:
select
        generatedAlias0.institucionId,
        generatedAlias0.institucionNombre
    from
        Institucion as generatedAlias0
    left join
        generatedAlias0.sector as generatedAlias1
    where
        generatedAlias1=:param0

tried with this other one:
findBySector_sectorId

which generates the above query as well.
Wouldn't be better to form a query like:
select *
from tbInstitucion
where sectorId = ?

Is there a way to get the above query?
Why is JPA generating the left join?

A: Left join is a default implicit joining strategy, also when using the @EntityGraph feature.
I would recommend using explicit @Query definition:
@Query("select i from institution i inner join i.sector s where s.id = :sectorId")
public Institution getBySector(@Param("sectorId") Integer sectorId);

A:
A quick review of the entity model

@Entity
class Institucion {
  @ManyToOne(fetch=FetchType.LAZY)
  @JoinColumn(name="`sectorId`")
  private Sector sector;
}

is equivalent to:
@Entity
class Institucion {
  @ManyToOne(cascade = {}
             , fetch=FetchType.LAZY
             , optional = true
             , targetEntity = void.class)
  @JoinColumn(columnDefinition = ""
             , foreignKey = @ForeignKey
             , insertable = true
             , name="`sectorId`"
             , nullable = true
             , referencedColumnName = ""
             , table = ""
             , unique = false
             , updatable = false)
  private Sector sector;
}

Note @ManyToOne(optional = true) and @JoinColumn(nullable = true). This signifies to the ORM that the sector attribute of Institucion is optional and may not be set (to a non-null value) all the time.

How the entity model impacts repository queries

Now consider the following repository:
public interface InstitucionRepository extends CrudRepository<Institucion, Long> {
  List<Institucion> findAllByInstitucionNombre(String nombre);

  List<Institucion> findAllByInstitucionEmail(String email);
}

Given the entity declaration above, the repository methods should produce queries such as:
select
    generatedAlias0
from
    Institucion as generatedAlias0
left join
    generatedAlias0.sector as generatedAlias1
where
    generatedAlias0.institucionNombre=:param0

and
select
    generatedAlias0
from
    Institucion as generatedAlias0
left join
    generatedAlias0.sector as generatedAlias1
where
    generatedAlias0.institucionEmail=:param0

This is because the entity model indicates sector to be optional so the ORM needs to load Institucions without worrying about their sectors.
Following this pattern, the following repository method:
  List<Institucion> findAllBySector(Sector sector);

translates to:
select
    generatedAlias0
from
    Institucion as generatedAlias0
left join
    generatedAlias0.sector as generatedAlias1
where
    generatedAlias1=:param0

Solution 1

If Institucion.sector is not optional, make it mandatory in the model too:
  @ManyToOne(fetch=FetchType.LAZY, optional = false)
  @JoinColumn(name="`sectorId`", nullable = false)
  private Sector sector;

Solution 2

If Institucion.sector is indeed optional, only a manual query such as the one shown in @MaciejKowalski's answer will work.

Simplified query

The following query will also work:
  List<Institucion> findAllBySectorSectorId(Long id);

This assumes that the model attribute names are exactly as shown in the post.


text:
Q: PHP - Search File for Contents I have a PHP script that reads the contents of a file and stores it into a variable. I want to split the text stored by the new line entries and then search the array[0] value for a specific value.
That is my idea. Here is my situation.
I have a directory file with specific entries.
Entry1_two_term3_stuff
Entry2_two_term3_stuff
Entry3_two_term3_stuff

This will be stored into a variable. How do I search this for Entry2 and then get the whole line to work with?

A: If you can, use the file() function to load the file into array, already split by newlines:
$lines = file('filename.txt');

If not, you can use
$lines = explode("\n", $contents);

You might want to use \r\n if you're on Windows and file contains CR characters.
To search the array, use foreach:
foreach ($lines as $ix => $line)
    if (strpos ($line, 'string') !== false)
        $lines[$ix] = ...new version of line...

In the end, write contents back to some file:
$fp = fopen('file.txt', 'w+');
foreach ($lines as $line)
    fputs($fp, $line);
fclose($fp);

A: You could search the directories with RecursiveDirectoryIterator, and search the files contents individually with preg_match_all


text:
Q: Button with image blue background I create a button with image in my app:
                <Button x:Name="favoriteButton" HorizontalAlignment="Left" VerticalAlignment="Top" Height="72" Width="99" Click="DidPressAddToFavorites" BorderBrush="{x:Null}" Foreground="{x:Null}">
                    <Button.Background>
                        <ImageBrush ImageSource="/Images/favouritesBWIcon@2x.png" Stretch="Uniform"/>
                    </Button.Background>
                </Button>

And i noticed that when the user press the button all the button became blue and when i release the button i see it again. any idea how to fix it?
Edit:
This is the handler method:
private void DidPressAddToFavorites(object sender, RoutedEventArgs e)
    {
        if (favoriteRep.ExistInFavorites(currentItem) == true)
        {
            this.SetButtonWithImage(favoriteButton, "/Images/favouritesBWIcon@2x.png");
            favoriteRep.RemoveFromFavorites(currentItem);
        }
        else
        {
            this.SetButtonWithImage(favoriteButton, "/Images/favouritesIcon@2x.png");
            favoriteRep.AddToFavorites(currentItem);
        }

    }

A: Because you didn't add the States, there are three states Normal, MouseOver, Pressed... You have to set the image for all three states, to make it work of your wish. Here the alternate to do so, didn't know about any better way available from c#, all you have to do is to add two more eventHndlers Mouse over event and press event, then set the image in both of them....
Well there's another good way to do so is try template editing from blend Software


text:
Q: Can't archive project with Swift Package that contains a binary target (xcframework) My project contains a Swift Package that contains a binary target. Generally, the project compiles and works properly, but the problem occurs when I try to archive the project, where I get a complier error saying No such module 'MyFramework'.
The Swift Package looks like this:
let package = Package(
    name: "MyPackage",
    platforms: [
        .iOS(.v13)
    ],
    products: [
        .library(name: "MyPackage", targets: ["MyPackage"]),
    ],
    dependencies: [
        // Product dependencies...
    ],
    targets: [
        .binaryTarget(name: "MyFramework", path: "MyFramework.xcframework"),
        .target(
             name: "MyPackage",
            dependencies: [
                "MyFramework"
                ...
            ],
            resources: [.process("Resources")]
         ),
        .testTarget(
            name: "MyPackageTests",
            dependencies: ["MyPackage"])
    ]
)

I've tried following many solutions, among them a proposal from the Apple Developer forums where I added the framework to the products as another library and then added the framework on the app (project / client) side, which made it archive successfully, but when I tried upload the archive to the App Store I got an error saying Found an unexpected Mach-O header code: 0x72613c21.
Right now, I am trying to follow other solutions mainly on the Swift Forums but none of them seem to work for me or be clear enough.
From what I've seen, this is a Swift Bug but I am wondering if there is any workaround that is sufficient for now.
Any help will be highly appreciated. Thanks in advance!

A: After too many hours we managed to find a (pretty ugly) workaround that archives properly.
Basically, we need to the framework as a library to the product, like so:
let package = Package(
    name: "MyPackage",
    platforms: [.iOS(.v13)],
    products: [
        .library(name: "MyPackage", targets: ["MyPackage"]),
        .library(name: "MyFramework", targets: ["MyFramework"]),
    ],
    ...
    targets: [
        ...
        .binaryTarget(name: "MyFramework", path: "MyFramework.xcframework")
    ]
)

Then link the frameworks on the project in Frameworks, Libraries and Embedded Content.
This in for itself though isn't enough, as the project will archive but will throw the error Found an unexpected Mach-O header code: 0x72613c21 like I mentioned in the original question. In order to resolve this issue, we needed to add the following script to the Archive's Post-actions in the project's scheme:
LOGFILE="${ARCHIVE_PATH}/static-frameworks.log"
echo "Removing static frameworks from ${WRAPPER_NAME} archive" > $LOGFILE
find "${ARCHIVE_PRODUCTS_PATH}/Applications/${WRAPPER_NAME}" -name '*.framework' -print0 | while IFS= read -r -d '' fm; do
    name=$(basename "${fm}" .framework)
    target="${fm}/${name}"
    echo "Checking: ${fm}" >> $LOGFILE
    if file "${target}" | grep -q "current ar archive"; then
        rm -rf "${fm}"
        echo "Removed static framework: ${fm}" >> $LOGFILE
    fi
done

Now the project archives successfully an can be uploaded to the App Store. Still obviously not an ideal solution, looking forward to hearing from Apple or for other possible solutions.

A: Update to Xcode 12.5 for a fix.
Much more detail and discussion here.


text:
Q: Valgrind configure build script "Syntax Error" OSX Monterey - how to fix? I'm trying to build Valgrind 3.19.0 on OSX monterey and when i run the configure script i get a syntax error at line 6594:
checking for diff -u... yes
./configure: line 6594: syntax error near unexpected token `newline'
./configure: line 6594: `    '''

This is the code sippet of the configure script where the error is occuring.
for as_dir in $PATH
do
  IFS=$as_save_IFS
  case $as_dir in #(((
    ''
 as_dir=./ ;;
    */) ;;
    *) as_dir=$as_dir/ ;;

Let me know if you need any more info.


text:
Q: hCard properties for advanced mark-up I have a database where various student musicians have their specialisms and departments listed (for example somebody could specialise in violin in the Historical Performance department). Also for example, consider Johann Sebastian Bach - he is a musician and composer in the Baroque style. Logically perhaps I'd want his specialism to fall under "Composition" and his department to be "Baroque".
I think that 'department' could be covered happily by the "category" property, but what to make of 'specialism'? That's a kind of category, too. The hCard spec says that it's cool to use 'category' twice, but it seems kind of dirty since department and specialism are so semantically unrelated.
What about the 'notes' property? Or 'role'? Thoughts?

A: I think I'd be inclined to use the category for 'Composition' and 'Baroque' either into role or as part of his faculty address. I'm not entirely clear on whether 'Baroque' would be an addressable part of your school, but if that would be the case then that'd work.  Maybe think about it in terms of how you would describe them - would Johann be a 'Composer of Baroque' (role) or a 'resident of Baroque department' (adr).
vCards aren't that super detailed, unfortunately.


text:
Q: Are any other systems' manpages available on Ubuntu? The manpage of man mentions a curious option:
-m system[,...], --systems=system[,...]
      If this system has access to  other  operating  system's  manual
      pages,  they can be accessed using this option.  To search for a
      manual page from NewOS's manual page collection, use the  option
      -m NewOS.

      The  system  specified  can  be a combination of comma delimited
      operating system names.  To  include  a  search  of  the  native
      operating  system's manual pages, include the system name man in
      the argument string.  This  option  will  override  the  $SYSTEM
      environment variable.

I guess it's referring to this NewOS. However, a search of the Package Index for newos came up empty. (Not that I am interested in NewOS - I don't care about it, but I am curious as to what I can do with this option.)
Are any other systems' manpages available in Ubuntu? If not, how is this option supposed to be used?

We have POSIX manpages available in a separate package, and those manpages have posix appended to the section number (1posix, etc.). However, posix doesn't seem to be a system:
$ man -wm posix ls
/usr/share/man/man1/ls.1.gz

A: I think Ubuntu placement of man pages with respect to that feature is broken:

*

*Entering man -wm es man shows /usr/share/man/es/man1/man.1.gz, that is, the spanish manual page for man(1) as installed by package man-db

*Similar to what you noticed about POSIX manpages, freebsd-manpages install into their own sections instead of under a distinct "operating system's manual pages" and can be viewed accordingly, for example man 3freebsd sysctl
FWIW, the same confusing behaviour of -m is present on ArchLinux and Debian. Implementation of -m on FreeBSD concerns the machine architecture, not operating system.
To answer your question's title, at least GNU/kFreeBSD manpages are available, but not using the documented method of viewing them.
(As an aside, initial commit to NewOS repository is from 2000, but initial commit to GNU man-db man(1) source shows a copyright from 1995 along with a reference to NewOS, as does the most recent version of man-db in Debian bo. This possibly indicates that NewOS was used as a placeholder name instead of referring to the actual software.)


text:
Q: Disabling 'go' button form submission in Android I have almost completed an ASP.NET webforms website using jQuery Mobile. I am stuck on one specific use case.
The site is scoped to support Android, iPhone, BlackBerry and Windows Mobile all of the functionality works great except for one specific use case.
The case is when a user is entering a value into one of the input boxes and then hits the native Go/Enter key. I am capturing this and throwing the appropriate event submit button click/tap with jquery.
function BindSubmit(textbox, button) {
    $(textbox).unbind().keypress(function (event) {
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) {
            $(button).trigger('tap');
        }
    });
}

This works great on all devices but one, Android. The phone ends up submitting the entire form instead of following the use case. Grabbing the onsubmit event and returning false doesn't work either. After some digging I found this Disabling 'go' button form submission in Android when using webview .
I am hoping for a solution to this for a standard webform. Thanks.

A: Thank you for the help. The way we solved this is binding to the form.submit event and calling the mobile.changePage() ourselves. Then after the changePage() we return false; This prevented the full form submit and still allowed jquery mobile to complete its actions.

A: Try running $(button).trigger('click'). This might be a better, more cross-platform way of sending the event.
You should definitely try to test it like this on an Android phone and find out when and where execution fails:
function BindSubmit(textbox, button) {
    console.log("BindSubmit()");
    $(textbox).unbind().keypress(function(event) {
        var keyCode = ...;
        console.log("Key pressed: " + keyCode + ", isEnter: " + keyCode == 13);
        if (keyCode == 13) {
            console.log("Enter key hit, triggering event.");
            ...;
        }
    });
}

If you have a link to it, I'd be happy to test it on my Nexus One for you :)


text:
Q: Can a field extension still have "non-separability" above its maximal purely inseparable subextension? Question 1
Let $E/F$ be an algebraic field extension. Let $K$ be the set of all elements of $E$ that are purely inseparable over $F$. Then, $E/K/F$ is a tower of fields, and $K/F$ is purely inseparable.
In this case, is $E/K$ always separable? If not, what is a counterexample?
Moreover, let $K^s$ and $F^s$ be the separable closures in $E$. Then, $E/K^s$ is purely inseparable. How different are $K^s$ and $F^s$ as fields? That is, how much nicer is the extension $K^s/K$ compared to $F^s/F$?
Question 2
Let $E/F$ be a normal field extension. Let $E^G$ denote the fixed field of $\operatorname{Aut}(E/F)$. Then, $E/E^G$ is separable and $E^G/F$ is purely inseperable.
Is $E^G$ the unique such subextension? That is, is there a subextension $K$ of $F$ such that $E/K$ is separable and $K/F$ is purely inseparable, but $K\neq E^G$?

A: The extension $E/K$ need not be separable. Here is the example I learned from a note by J. Lipman.
Consider the rational function field $F=\mathbb{F}_2(y,z)$ and the extension $E=F(x)$, where $x$ is a root of $$f(t)=t^4+yt^2+z\in F[t].$$ If $E/K$ was separable, we would have $f=g^2$, for $g\in K[t]$. We have $g=t^2+\sqrt{y}t+\sqrt{z}$, which means that $\sqrt{x},\sqrt{y}\in K$. The latter condition says that $K/F$ is a degree-four extension, and so it is not purely inseparable.

A: Answer to Question 1.
Here is another example of an extension $K/F$ such that $K/I$ is not separable, where $I$ is the purely inseparable closure of $F$ in $K$. This is Example 4.24 from Patrick Morandi's Field and Galois Theory (pages 48-49), and it is similar in spirit to the one mentioned in @user2097's answer.
Let $k$ be a field of characteristic $2$. Let $F = k(x,y)$ where $x$ and $y$ are indeterminates. Let $S = F(u)$, where $u$ is a root of the polynomial
$$
t^2 + t + x \in F[t].
$$
Let $K = S(\sqrt{uy})$. Then $K/S$ is purely inseparable and $S/F$ is separable, so $S$ is the separable closure of $F$ in $K$. But the purely inseparable closure of $F$ in $K$ equals $F$ itself, and so $K$ is not separable over $I$.
I cannot provide a strong answer for how much nicer $I^s/I$ is compared to $F^s/F$. Perhaps you would receive better answers if you asked it separately, either here or on MathOverflow.

Answer to Question 2.
Note that for any algebraic extension $E/F$, we have that $E/E^G$ is separable and that $E^G \supset I$, and if $E/F$ is normal, then $E^G = I$.
Now, let $E/F$ be a normal extension, and let $K$ be an intermediate extension such that $E/K$ is separable and $K/F$ is purely inseparable. Then, we have the chain of extensions
$$
F \subset K \subset I \subset E.
$$
Since $E/K$ is separable and $E/I = E/E^G$ is separable, $I/K$ is also separable. But $I/F$ is purely inseparable, so $I/K$ is also purely inseparable. Hence, $I = K$. Thus, if $E/F$ is normal, then there is a unique intermediate extension such that $E/F$ splits into a purely inseparable extension followed by a separable extension, namely $I = E^G$.
If $E/F$ is not necessarily normal, then there may not exist such an intermediate extension at all. If it does exist, then that intermediate extension is unique and equals $I$, but $E^G$ need not equal $I$ in this case! This follows from the results in the note of J. Lipman that @user2097 mentioned in their answer.


text:
Q: What if there were no surface tension in the upside-down water cup trick? There is a famous trick that goes as follows. Take a cup/glass that is partially filled with water. Place an index card over the top. Turn the entire thing upside-down (while keeping the index card at the cup opening), and then release the card. You should end up with the card "sticking" to the cup, keeping the water inside the cup, even though the cup is upside-down. Various posts about this have been made:

*

*About an upside down cup of water against atmosphere pressure

*Upside down water cup trick

*Why does the upside down water cup and card trick work?
I have a follow-up question to the questions above. I am trying to understand what role does the surface tension play in this trick (if any at all).
My question is, what would happen if we used a hypothetical liquid that had zero (or near zero) surface tension? There are two sub-questions I want to consider:

*

*Would the unbalanced pressure argument still hold? As far as I can tell, the answer is yes, so the card would still "stick" to the cup.

*On the other hand, wouldn't the liquid still leak out through the rim of the glass? It seems like it should since there is no surface tension keeping it in. But this seems to contradict the reasoning in #1 above. On top of all this, I have a hard time understanding what would happen to the air trapped at the top of the upside-down glass.

Can anyone help me think through this scenario more clearly. It seems paradoxical.
My tentative thought for now is that if a liquid had zero surface tension, it would be "infinitely porous" so the air molecules would simply penetrate through this substance. Basically, it seems like such a substance would just end up being a gas. I'm not sure if this is correct or if I am completely off, so I hope someone with better knowledge could chime in.


text:
Q: Moq System.NotSupportedException I get it again and again
System.NotSupportedException: 'Unsupported expression: c => c.ProductMaxLenght
Non-overridable members (here: ConfigurationService.get_ProductMaxLenght)
may not be used in setup / verification expressions.'

When I try call this
var configurationService = new Mock<ConfigurationService>();
configurationService.SetupGet(c => c.ProductMaxLenght).Returns(productMaxLength)

I call Initialize in Startup and take all data from Configuratiom
Configuration Service:
public class ConfigurationService
    {
        private IConfiguration _configuration;
        private int? _productMaxLength;
        public int? ProductMaxLenght
        {
            get
            {
                if (!_productMaxLength.HasValue)
                {
                    throw new ArgumentNullException(nameof(_productMaxLength));
                }
                return _productMaxLength;
            }
        }

        public void Initialize(IConfiguration configuration)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(_configuration));
            _productMaxLength = _configuration.GetValue<int>("ProductsMaxLength");
        }
    }

A: You have to make the property overridable, so make it virtual:
public virtual int? ProductMaxLenght  { get ...


text:
Q: Postgresql - moving data from loosely typed staging table to strongly typed final table - and catch errors I have a staging table that is loosely typed (all cols (except pk) of datatype text) and I want to move this data into a table that is correctly typed for the data e.g. numerics are numerics, dates are dates etc.
My initial approach is to create a cursor in pgsql and loop through the data inserting it into the final table with appropriate casts.
I will catch errors and use them to insert rows that fail into an errors table that I can look at and address later.
Is there a cleverer way of doing this?
Regards
Dave

A: Use a PL/PgSQL function with a BEGIN ... EXCEPTION WHEN ... END block wrapping the operation(s) that might fail.
See Postgres sql exception handling for batch insert for an example, and caveats.
It'd be nice if PostgreSQL's cast functions could be called in a test mode, where they return a boolean result indicating success and discard the product, or even better return a tuple of (result, successflag). That way you could do it all with plain SQL. Unfortunately they don't support that, so you've got to use an exception handling loop and subtransactions.


text:
Q: Header Manipulation Cookies in asp.net Fortify tool is showing the Header manipulation cookies issue on the below code.
HttpCookie cookieexit= new HttpCookie("CheckUserNameExists");
cookieexit.Value = userName;
cookieexit.Secure = true;
Response.Cookies.Add(cookieexit);
Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, false));

Any help ?

A: It is not directly related to original question.
If you use FormAuthentication, it is not a good practice to create custom cookie name to keep track of logged-in username.
Instead, you want to use same cookie name FormsAuthentication.FormsCookieName that FormsAuthentication uses.
So, you replace 5 lines of codes with the following single line -
FormsAuthentication.RedirectFromLoginPage(userName, false);

Global.asax.cs
You then retrieve the username from cookie, and save it in both Principal Object and Current Thread.
public class Global : HttpApplication
{
    private void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie decryptedCookie =
            Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        FormsAuthenticationTicket ticket =
            FormsAuthentication.Decrypt(decryptedCookie.Value);

        var identity = new GenericIdentity(ticket.Name);
        var principal = new GenericPrincipal(identity, null);

        HttpContext.Current.User = principal;
        Thread.CurrentPrincipal = HttpContext.Current.User;
    }
}

You can then retrieve username literally anywhere in your code as long as HttpContext.Current is available. For example,
string userName = User.Identity.Name;

A: Fortify is complaining because it thinks that userName could have dangerous characters, such as newlines, which could (maybe) allow header manipulation attacks in the scenario of social engineering/phishing attacks.
I'm not too sure of the practicality of such attacks, but I am pretty sure that if you validate that userName only contains a whitelisted set of characters that exclude any whitespace, then such an attack is prevented.


text:
Q: Page get hangs and gives 'Aw, snap' error when clicking button using ('click' selenium-java and sendKeys(Keys.ENTER)) in Chrome browser After clicking save button, page hangs and gives Aw! snap error after 2-3 minutes.
I tried below methods, but nothing worked.
Elements.findElement("responsive_shipping_options.gift_options_save_signed_in").sendKeys(Keys.ENTER);

Clicks.click("responsive_shipping_options.gift_options_save_signed_in");
logger.info("Successfully clicked on change button");

Thread.sleep(5000);


text:
Q: Android GCM registration ID change I know this is a silly question but important for me. I am developing an application which uses GCM. I searched and read regarding the GCM and having some question related to this as:

*

*Is the registration_id of GCM change after App update? If yes then how to handle it?

*Is the registration_id of GCM change after Android update? If yes then how to handle it?

*Is the registration id changes with every time registration to GCM from the same device and same app?

*Do the app need to call registration to GCM method every time when app runs?

*Can the app wait till the token or registration process complete in background?

I refereed the This Link to implement GCM in my app.

A: check GCM
The periodical refresh never happened. The registration refresh is not included in the new GCM library.
However you can also  unregister device and set expiry on it.

Do the app need to call registration to GCM method every time when app
  run?

No until you unregister you dont need to call it.

A: I'll try to answer some of your questions.

*

*Is the registration_id of GCM change after App update? If yes then how to handle it?

Ans. : Yes, registration_id of GCM change after App update here you can find explanation.

*Is the registration_id of GCM change after Android update update? If yes then how to handle it?

Ans. : Yes, registration_id of GCM change after App update here you can find explanation.

*Is the registration id changes with every time registration to GCM from the same device and same app?

Ans. : No, It'll be same as long as the app is not updated or android version of device is not changed.

*Do the app need to call registration to GCM method every time when app run?

Ans. : If you have an app where user has to do login then at login success step you can but registration. And it doesn't take much time to register the device. If the id is changed, it'll give new id or else will return old one so no worries about duplication or such problems.

*Can the app wait till the token or registration process complete in background?

Ans. : You can do this in background thread as well. But it doesn't take much time so you can do it normally as well.
I hope, am able to answer you questions. Let me know if I am wrong anywhere.
Accept my answer if you agree with me.
Thanks.


text:
Q: Send data between silbing components in Angular I've 2 components and app-component.ts is the father. I want to send a number from one component to other component, but I don't know how. I've tried with service.
Component A ("transmitter")
 export class ShowCompnents implements OnInit{

    numberAttendee:number;

    constructor(public eventService: EventService){}

    ngOnInit(): void {
      this.numberAttendee = 8;
      this.eventService.changeNumber(this.numberAttendee);
    }
  }

I need to send numberAttendee.
Component B ("receiver")
  export class ShareComponents implements OnInit{

    num: number;

    constructor(public eventService: EventService){}

    ngOnInit(): void {
    this.eventService.updatedEditNumber.subscribe((data: any) => {
      this.selectedNum = this.eventService.getCurrentNumber();
      console.log(this.selectedNum);
    });
    }
  }

This component receives the number.
And the service is:
@Injectable({
  providedIn: 'root',
})
export class EventService {
  constructor() {}

  public editNumber: number = 0;
  updatedEditNumber: any = new EventEmitter();

  changeNumber(num: number) {
    this.editNumber = num;
    this.updatedEditNumber.emit(this.getCurrentNumber);
  }

  getCurrentNumber() {
    return this.editNumber;
  }
}

This always return 0 in component B, the number in eventService, not the number in component A (8).
Thanks !!

A: I think this will work.
Component B: remains just the way it is.
Component A: this needs to receive the updated data from a service method getCurrentNumber after changing the value of editNumber in our service by triggering an event updateEditNumber which hence changing num accordingly.
 export class ShareComponents implements OnInit{
   num: number;

   constructor(public eventService: EventService){}

   ngOnInit(): void {
     this.eventService.updateEditNumber.subscribe((data: any) => {
       this.num = this.eventService.getCurrentNumber();
     });
   }
 }

Service: the service needs to implement an event to update the data through all the necessary components.
 @Injectable({
    providedIn: 'root',
 })
 export class EventService {
    constructor() {}
    public editNumber: number = 0;

    updatedEditNumber: any = new EventEmitter()

    changeNumber(num: number) {
      this.editNumber = num;
      this.updatedEditNumber.emit(this.getCurrentNumber);
    }

    getCurrentNumber() {
      return this.editNumber;
    }

 }


text:
Q: Creating figures of polytopes (in 3D): Is it worth switching from PSTricks to TikZ? I used PSTricks a lot to create figures of polytopes. More recently, I have become aware of discussions going on about whether PSTricks or TikZ is the better choice for creating figures of all kinds. From the general discussion on this issue, I have come to the conclusion that I want to use TikZ rather than PSTricks in the future.
However, before I switch to TikZ, I want to find out whether TikZ is good for the particular purpose I want to use it for. I mainly used the pst-solides3d package of PSTricks, and I wonder whether TikZ provides substitutes for the features of PSTricks I used. To make my question more conrete, let me just give a very simple example of a polytope that I created with PSTricks and give you a list of features that I like in this example, and you tell me whether the particular features are easily implemented in TikZ.
\documentclass{minimal}
\usepackage{pst-solides3d}
\begin{document}

\begin{pspicture}(-2.5,-1)(6,4)
\psset{viewpoint=40 16 12,Decran=130,solidmemory}
\psSolid[object=new,linewidth=0.7\pslinewidth,
 action=draw*,
 name=A,
 fcol=1 (0.8 setgray),
 sommets=
  %n=4
  0 0 0 %0
  0.420448  0.420448 0.5 %e1
 -0.420448  0.420448 0.5 %e2
 -0.420448 -0.420448 0.5 %e3
  0.420448 -0.420448 0.5 %e4
  0 0 1.2, %u
 faces={
  [1 2 3 4]
  [1 2 5]
  [2 3 5]
  [3 4 5]
  [4 1 5]}]%
\psSolid[object=plan,definition=solidface,action=none,args=A 0,name=S0]
\psset{fontsize=8}
\psProjection[object=texte,text={G},plan=S0]%
\psSolid[object=plan,definition=solidface,action=none,args=A 1,name=S1]
\psProjection[object=texte,text={H},phi=90,plan=S1]%
\psPoint(0, 0, 1.2){a}
\uput[u](a){$a_G$}
\psdot[dotsize=0.1](a)
\end{pspicture}

\end{document}

What I like about it:

*

*I can create the polytope from a given set of three-dimensional coordinates.

*If I want to change the viewpoint, I don't have to type in the code of a whole new polytope but I simply change \psset{viewpoint=40 16 12,Decran=130}.

*The hidden lines are dashed. Important: I don't have to specify which lines are hidden; determining the hidden lines should be automatic.

*I can write text on the faces of the polytope (like G, H in this example).

*I can easily color a face (like giving the H-face a gray color).

*The corners are easily marked (with a dot) and labeled (a_G in the example).

Is this easily done using TikZ? An example creating this polytope with the mentioned features using TikZ would be nice (this would also help me to start using TikZ if I should decide to switch). I think if these basic things work with TikZ, then I can cope with other details that may or may not be possible with TikZ.
EDIT: Answering the question of what would be "the most complicated" polytope I might want to draw: I don't know. Although I don't know TikZ, I would gess that increasing complexity in terms of an increasing number of coordinates / corners should not be problematic (is it?). Of course it's more labor-intensive to type the code (needless to say that this is also true for pstricks), but I think the general feasibility should not be affected by that (right?). That's why I focused on features instead of on the complexity of the polytope. One thing I can say is that I will probably only draw convex polytopes. I might want to draw more complicated polytopes in the future, but the most complicated one I have drawn so far is probably this one (yes, the additional septagon on top is intended):
    \documentclass{minimal}

\usepackage{pst-solides3d}

\begin{document}

\begin{pspicture}[showgrid=false](-2,-0.5)(2,2.7)
\psset{viewpoint=26 7 5,Decran=50}
\psSolid[object=new, linewidth=0.7\pslinewidth,
action=draw*,
name=A,
sommets=
%n=7
0 0 0 %0 0
0.656862 0.82368 1 %w1 1
-0.234432 1.02711 1 %w2 2
-0.949194 0.457108 1 %w3 3
-0.949194 -0.457108 1 %w4 4
-0.234432 -1.02711 1 %w5 5
0.656862 -0.82368 1 %w6 6
1.05353 0 1 %w7 7
0.311322 0.390385 0.473952 %e1 8
-0.111109 0.486802 0.473952 %e2 9
-0.449873 0.216647 0.473952 %e3 10
-0.449873 -0.216647 0.473952 %e4 11
-0.111109 -0.486802 0.473952 %e5 12
0.311322 -0.390385 0.473952 %e6 13
0.499321 0 0.473952 %e7 14
-0.311322 -0.390385 0.526048 %u-e1 15
0.111109 -0.486802 0.526048 %u-e2 16
0.449873 -0.216647 0.526048 %u-e3 17
0.449873 0.216647 0.526048 %u-e4 18
0.111109 0.486802 0.526048 %u-e5 19
-0.311322 0.390385 0.526048 %u-e6 20
-0.499321 0 0.526048 %u-e7 21
0 0 1, %u 22
faces={
[0 13 16 12]
[0 12 15 11]
[0 11 21 10]
[0 10 20 9]
[0 9 19 8]
[0 8 18 14]
[0 14 17 13]
[16 13 17 22]
[17 14 18 22]
[18 8 19 22]
[19 9 20 22]
[20 10 21 22]
[21 11 15 22]
[15 12 16 22]
[1 2 3 4 5 6 7]
}]
\end{pspicture}

\end{document}

At this example, one can see why it is useful that hidden lines are dashed: If they were solid, the picture would not be as readable as this one.

A: it may make sense in the future when TikZ will use the Lua extensions for calculations of hidden lines and surfaces. Then it may be possible to do with Lua the same as you can do with the programming language PostScript.


text:
Q: Use package.json version in MD files for Vue Press I'm trying to utilise the package.json version tag inside of my *.md files which get later compiled into HTML, however I can't seem to figure out how to do this. My plugin.js files contains the following which I thought I could utilise:
const { version } = require('../../package.json')

module.exports = (/*options, ctx*/) => ({
  async enhanceAppFiles () {
    const code = `export default ({ Vue }) => {
  Vue.mixin({
    computed: {
      $version () {
        return '${version}'
      }
    }
  })
}`
    return [{
      name: 'vuepress-plugin-vue-cli-plugin-p11n',
      content: code
    }]
  }
})

I tried using version and $version inside of my *.md files with little luck, has anyone else got this issue?

A: The easiest way to achieve this, it's simply put the version into themeConfig and let VuePress do its thing
// .vuepress/config.js
const { version } = require('../../package')

module.exports = {
  themeConfig: {
    version: version
  }
}

and use it in markdown like
{{ $themeConfig.version }}

However, it seems like that themeConfig isn't meant for this, so you can also create your own computed properties
// .vuepress/enhanceApp.js
const { version } = require('../../package')

export default ({ Vue }) => {
  Vue.mixin({
    computed: {
      $version: function() {
        return version
      }
    }
  })
}

and use it like
{{ $version }}


text:
Q: create android TCP client for rtl-tcp-android I am trying to get the I/Q signals from an RTL-SDR dongle (RTL2832U R820T2) connected to an android phone (samsung galaxy 7, android 8.0) using an OTG cable. I am using the rtl-tcp-android driver. I have installed the driver by compiling and downloading from it's source code, and I can receive FM signals using the SDR Touch app (created by the driver's author) so as far as I understand the driver installation itself should be fine.
The github page for the driver explains how to get I/Q samples. It says once the driver has been properly invoked using an Android intent I should be able to just read interleaving I/Q data in uint_8 format if I can read the driver's output using a tcp client.  I am trying to use this answer to make a tcp client. In the TcpClinet class, inside the while (mRun) loop, I have changed the line
mServerMessage = mBufferIn.readLine();

to
mServerMessage = Integer.toString( mBufferIn.read() );

Apparently that answer expects the tcp data to come in as lines of text, while the data I should be getting is continuous streams of uint_8 data. (in fact, if I don't make this change the program eventually crashes with an outofmemory exception at the readLine() function). I have also changed the values of SERVER_IP and SERVER_PORT member variables in TcpClient class with appropriate values for my device. Everything else related to the tcp client is same as in that answer.
In onProgressUpdate() I am getting random sequences of 0x7f and 0xfffd.
This is the onProgressUpdate() function I am using now in MainActivity:
@Override
protected void onProgressUpdate(String...values){
   super.onProgressUpdate(values);
   Log.d("MYLOG", "response " + values[0] + String.format( "(0x%x)", Integer.parseInt( values[0] ) );
}

Here is a section of my logcat:
2019-10-31 14:37:21.629 7232-7232/? D/MYLOG: response 65533(0xfffd)
2019-10-31 14:37:21.633 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.635 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.643 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.645 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.651 7232-7232/? D/MYLOG: response 65533(0xfffd)
2019-10-31 14:37:21.654 7232-7232/? D/MYLOG: response 65533(0xfffd)
2019-10-31 14:37:21.655 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.657 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.658 7232-7232/? D/MYLOG: response 65533(0xfffd)
2019-10-31 14:37:21.663 7232-7232/? D/MYLOG: response 65533(0xfffd)
2019-10-31 14:37:21.666 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.669 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.671 7232-7232/? D/MYLOG: response 65533(0xfffd)
2019-10-31 14:37:21.673 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.687 7232-7232/? D/MYLOG: response 127(0x7f)
2019-10-31 14:37:21.689 7232-7232/? D/MYLOG: response 65533(0xfffd)

I am pretty sure this is not correct, and I suspect there is something wrong with the tcp client code. How can I modify this code to properly talk with the rtl-tcp-android driver?
EDIT 1---
This is an edit to the code that I tried but didn't work (based on this answer to the same linked question):
mRun = true;
try {
    InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
    Log.e("TCP Client", "C: Connecting...");
    Socket socket = new Socket(serverAddr, SERVER_PORT);
    try {
        mBufferOut = new PrintWriter(socket.getOutputStream());
        Log.e("MYLOG", "TCP Client; C: Sent.");
        mBufferIn = new DataInputStream(socket.getInputStream());
        int charsRead = 0; short[] buffer = new short[1024]; //choose your buffer size if you need other than 1024

        while (mRun) {
            // charsRead = mBufferIn.read(buffer);
            // int length = mBufferIn.readInt();
            int length = 5;
            // Log.d("MYLOG", String.format("length = %d", length ) );
            if(length > 0){
                byte[] message = new byte[length];
                // mBufferIn.readFully(message, 0, message.length);
                mBufferIn.read(message, 0, message.length);
                // just display here instead of sending as a String to onProgressUpdate()
                for(int i=0; i<length; i++){
                    Log.d("MYLOG", String.format("message[%d] = %d (0x%x)", i, message[i], message[i]) );
                }
            }
            // mServerMessage = new String(buffer).substring(0, charsRead);
            if (mServerMessage != null && mMessageListener != null) {
                mMessageListener.messageReceived(mServerMessage);}
            mServerMessage = null;
        }
        Log.e("MYLOG", "RESPONSE FROM SERVER; S: Received Message: '" + mServerMessage + "'");

mBufferIn declaration has been changed to
private DataInputStream mBufferIn;

I would like to first make sure the correct data is coming in the TcpClient class's run() function itself, before the program does anything else. With this update I am getting 0x7f and 0x80 in the logcat.


text:
Q: WPF: How to resize bars using mouse or touch I have grid / canvas that has some bars which looks like your ordinary bar chart. I'd like that the user can (using touch and mouse) resize these bars by  dragging at selected points - see image below:

So the 5 points drawn here would be where the user can resize.
New to WPF, I'm not sure how to approach this, or even search for the right solutions. Can anyone point me in the right direction?

A: When you perform mouse hover it will resize your grid control refer below code
 <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="barresize.MainWindow"
        x:Name="Window"
        Title="MainWindow"
        Width="640" Height="480">
        <Window.Resources>
            <Storyboard x:Key="OnMouseEnter1">
                <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="tbTB">
                    <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="2">
                        <EasingDoubleKeyFrame.EasingFunction>
                            <BackEase EasingMode="EaseOut"/>
                        </EasingDoubleKeyFrame.EasingFunction>
                    </EasingDoubleKeyFrame>
                </DoubleAnimationUsingKeyFrames>
                <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" Storyboard.TargetName="tbTB">
                    <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="2">
                        <EasingDoubleKeyFrame.EasingFunction>
                            <BackEase EasingMode="EaseOut"/>
                        </EasingDoubleKeyFrame.EasingFunction>
                    </EasingDoubleKeyFrame>
                </DoubleAnimationUsingKeyFrames>
            </Storyboard>
        </Window.Resources>
        <Window.Triggers>
            <EventTrigger RoutedEvent="Mouse.MouseEnter" SourceName="tbTB">
                <BeginStoryboard x:Name="OnMouseEnter1_BeginStoryboard" Storyboard="{StaticResource OnMouseEnter1}"/>
            </EventTrigger>
            <EventTrigger RoutedEvent="Mouse.MouseLeave" SourceName="tbTB">
                <StopStoryboard BeginStoryboardName="OnMouseEnter1_BeginStoryboard"/>
            </EventTrigger>
        </Window.Triggers>

        <Grid >

            <Grid x:Name="grid1" Background="#00000000">

                <Grid Name="tbTB" VerticalAlignment="Center" HorizontalAlignment="Center" Height="100" Width="30" Background="Blue">

                    <Grid.RenderTransform>
                        <TransformGroup>
                            <ScaleTransform/>
                            <SkewTransform/>
                            <RotateTransform/>
                            <TranslateTransform/>
                        </TransformGroup>
                    </Grid.RenderTransform>

                </Grid>

            </Grid>
        </Grid>

    </Window>


text:
Q: VBA Convert Time from weird format I am new to VBA and am working on a subroutine that will help me transform call records into something useful for analysis.
Column B contains values that refer to the duration of the phone call, however the formatting is quite strange. Here are some values:
47s 472ms
53s 844ms
55s 164ms
2mn 17s
1mn 5s
1mn 25s
As you can tell, if the call is less than 1 minute, the format is seconds then milliseconds. If the call is greater than 1 minute, the format is minutes then seconds.
I need to convert those values to seconds (so ignore the milliseconds when they appear).
Would you mind helping me write the VBA code? Thanks!

A: Public Function ConvertTime(ByVal sTime As String) As Date

    Dim vaSplit As Variant
    Dim lSeconds As Long
    Dim lMinutes As Long

    Const sSEC As String = "s"
    Const sMIN As String = "mn"

    vaSplit = Split(sTime, Space(1))

    If Right$(vaSplit(0), 1) = "s" Then
        lSeconds = Val(Replace(vaSplit(0), sSEC, vbNullString))
    Else
        lSeconds = Val(Replace(vaSplit(1), sSEC, vbNullString))
        lMinutes = Val(Replace(vaSplit(0), sMIN, vbNullString))
    End If

    ConvertTime = TimeSerial(0, lMinutes, lSeconds)

End Function


text:
Q: auto-complete installation emacs I am a complete newbie to emacs and I am trying to use Vincent Goulet's  modified emacs (https://vigou3.github.io/emacs-modified-windows/) for my work (mostly R programming and LaTeX). The modified emacs comes with ess installed and I am trying to get auto-complete to work.
I don't see company-mode or auto-complete in the when I type M-x package-list-packages (although I see auto-complete-[other things] and company-[other things], and I am not able to install auto-complete.
My .emacs file is as follows:
;; Added by Package.el.  This must come before configurations of
;; installed packages.  Don't delete this line.  If you don't want it,
;; just comment it out by adding a semicolon to the start of the line.
;; You may delete these explanatory comments.
(package-initialize)

(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(ansi-color-faces-vector
   [default default default italic underline success warning error])
 '(custom-enabled-themes (quote (tango-dark)))
 '(package-selected-packages (quote (auto-auto-indent auto-complete company))))
(custom-set-faces
 ;; custom-set-faces was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 )

(require 'package)
(let* ((no-ssl (and (memq system-type '(windows-nt ms-dos))
                    (not (gnutls-available-p))))
       (proto (if no-ssl "http" "https")))
  ;; Comment/uncomment these two lines to enable/disable MELPA and MELPA Stable as desired
  (add-to-list 'package-archives (cons "melpa" (concat proto "://melpa.org/packages/")) t)
  ;;(add-to-list 'package-archives (cons "melpa-stable" (concat proto "://stable.melpa.org/packages/")) t)
  (when (< emacs-major-version 24)
    ;; For important compatibility libraries like cl-lib
    (add-to-list 'package-archives '("gnu" . (concat proto "://elpa.gnu.org/packages/")))))
(package-initialize)

(setq ess-use-company t)

Any help in getting auto completion of code to work in R would be really helpful. Thank you.

A: This doesn't appear to be an issue with ESS but with R options. The R option help_type should be set to "text" instead of "html" (which may be default on Windows?). This can be changed by setting the option in your .Rprofile configuration file (the user file should be located at Sys.getenv("HOME")) by adding options(help_type="text").
Note that your configuration ess-use-company is telling ESS to use the company backend that comes bundled with ESS and not the auto-complete library (two different packages that provide completion in emacs).
You may want to add (global-company-mode) to your init file to have completion running all your buffers (or enable it in your ess hook). I would also recommend looking into company-quickhelp for info in your completion menu.


text:
Q: boost b2 --layout=system causing LNK1104 error on Visual Studio using CMake I've compiled boost using:
b2.exe link=shared runtime-link=shared address-model=32 variant=release --layout=system --stagedir=./stage/win32

I'm loading boost components to CMake myself, specifically:
find_path(Boost_INCLUDE_DIR NAMES boost/config.hpp PATHS ${CMAKE_CURRENT_SOURCE_DIR}/../external/boost_1_69_0)
message("${Boost_INCLUDE_DIR}")

add_library(Boost INTERFACE IMPORTED GLOBAL)
set_target_properties(Boost PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${Boost_INCLUDE_DIR})

find_library(Boost_filesystem_LIBRARY NAMES boost_filesystem PATHS ${CMAKE_CURRENT_SOURCE_DIR}/../external/boost_1_69_0/stage/win32/lib)
message("${Boost_filesystem_LIBRARY}")

add_library(Boost_filesystem UNKNOWN IMPORTED GLOBAL)
set_target_properties(Boost_filesystem PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${Boost_INCLUDE_DIR})
set_target_properties(Boost_filesystem PROPERTIES IMPORTED_LOCATION ${Boost_filesystem_LIBRARY})
target_link_libraries(Boost INTERFACE Boost_filesystem)

When invoking CMake:
C:/bla/SW/cmake-template/external/boost_1_69_0
C:/bla/SW/cmake-
template/external/boost_1_69_0/stage/win32/lib/boost_filesystem.lib
-- Configuring done
-- Generating done
-- Build files have been written to: C:/bla/SW/cmake-template/build-windows

And last,
Link:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\
bin\HostX86\x86\link.exe /ERRORREPORT:QUEUE /OUT:"C:\bla\SW\cmake-template\build-windows
\mylib\Debug\mylib.dll" /INCREMENTAL /NOLOGO ..\myotherlib\Debug\myotherlib.lib "C:\bla\
SW\cmake-template\external\boost_1_69_0\stage\win32\lib\boost_filesystem.lib" kernel32.lib
user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib
advapi32.lib /DEF:"C:/bla/SW/cmake-template/build-windows/mylib/mylib.dir/Debug/exports.
def" /MANIFEST /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /manifest:embed /DEBUG /PD
B:"C:/bla/SW/cmake-template/build-windows/mylib/Debug/mylib.pdb" /SUBSYSTEM:CONSOLE /TLB
ID:1 /DYNAMICBASE /NXCOMPAT /IMPLIB:"C:/bla/SW/cmake-template/build-windows/mylib/Debug/
mylib.lib" /MACHINE:X86 /SAFESEH  /machine:X86 /DLL mylib.dir\Debug\mylib.obj
LINK : fatal error LNK1104: cannot open file 'libboost_filesystem-vc141-mt-gd-x32-1_69.lib' [
C:\bla\SW\cmake-template\build-windows\mylib\mylib.vcxproj]

I don't get it, how come it's trying to link to libboost_filesystem-vc141-mt-gd-x32-1_69.lib and not to boost_filesystem.lib?

A: That link comes from the auto-ink feature of some of the Boost libraries. You can either adjust the auto-link to use the appropriate naming see macros for controlling this in Boost Config library. Or you can turn off the auto-linking with the BOOST_ALL_NO_LIB macro mentioned also in the Boost Config docs.


text:
Q: Match words (regex) and create internal links from values stored in Array What I am trying to achieve is the following:
When I create news items, I want php to check these items for keywords. These keywords are stored in a mysql table (2 fields: search = varchar(255), link = varchar(255)).
I use a query to get the results and store them in an array.
I want to find words in a string and add an anchor to the word. The important bit is (where I have difficulty with) is that the search has to be case insensitive.
For example:
$searchFor = array("sun","sunny","wind","crap");
$linkArray = array("/solar","/solar","/wind-energy","/toilet");

The string:

What do you know about the sun? Sun, what kind of word is that? Is it
  something just like wind? Wind, another weird word. This text is
  complete crap by the way.

What I want as a result is:

What do you know about the sun? Sun what kind of word is that? Is it something just like wind? Wind another weird word. This text is complete crap by the way.

The code I have is:
$string = 'What do you know about the sun? Sun, what kind of word is that? Is it something just like wind? Wind, another weird word. This text is complete crap by the way.';
$pattern = "/(\w+)/i";
preg_match_all($pattern, $string, $matches);

foreach($matches[0] as $i => $word)
{
    $search = strtolower($word);
    if(in_array($search,$searchFor))
    {
        $pos = array_search($search,$searchFor);
        $link = $linkArray[$pos];
        echo "{$word} ";
    }
    else
    {
        echo $word." ";
    }
}

But I get stuck using regex (I think this is the right way).
$replacement = '${1}';

Is this possible??
Thank you.

A: Testet!
<?php
$searchFor = array("sun","sunny","wind","crap");
foreach($searchFor as $iKey => $sVal) {
    $searchFor[$iKey] = "/(" . $sVal . ")/i";
}
$linkArray = array("/solar","/solar","/wind-energy","/toilet");
foreach($linkArray as $iKey => $sVal) {
    $linkArray[$iKey] = '$1';
}
$string = 'What do you know about the sun? Sun, what kind of word is that? Is it something just like wind? Wind, another weird word. This text is complete crap by the way.';
echo preg_replace($searchFor, $linkArray, $string);


text:
Q: create a vector from a long table for each variable I have a following table
Name Subject
Alex Math
Alex Physics
Ann  History
Ann  Literature
Ann  Social Sciences

I want to transform this table into to a table with two rows so it would look like:
Name Subject
Alex c(Math, Physics)
Ann  c(History, Literature, Social Sciences)

The purpose of this transformation is to create generate all combinations of elements in the vector:
Math Physics
History Literature
History Social Sciences
Literature Social Sciences

A: You can use aggregate()function
  dat=read.table(text="Name Subject
            Alex Math
            Alex Physics
            Ann  History
            Ann  Literature
            Ann  'Social Sciences'",h=T,stringsAsFactors=F)

  aggregate(Subject~Name,dat,I)
   Name                              Subject
 1 Alex                        Math, Physics
 2  Ann History, Literature, Social Sciences


text:
Q: Django: ImportError: No module named doc here is the traceback
System check identified 1 issue (0 silenced).
September 10, 2018 - 13:01:31
Django version 1.8, using settings 'settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/home/basha/UpgradeMloss/venv1.8/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__
    self.load_middleware()
  File "/home/basha/UpgradeMloss/venv1.8/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 50, in load_middleware
    mw_class = import_string(middleware_path)
  File "/home/basha/UpgradeMloss/venv1.8/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 26, in import_string
    module = import_module(module_path)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named doc

and here is the installed libraries pip freeze:
certifi==2018.8.24
chardet==3.0.4
Django==1.8
django-contrib-comments==1.5
django-markup-deprecated==0.0.3
django-recaptcha2==1.3.0
idna==2.7
Markdown==2.6.11
Pillow==5.2.0
pytz==2018.5
recaptcha-client==1.0.6
requests==2.19.1
urllib3==1.23

and here is also the INSTALLED_APPS:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'django_comments',
    'django.contrib.syndication',
    'django.contrib.flatpages',
    'django.contrib.humanize',
    'software',
    'revision',
    'registration',
    'community',
    'forshow',
    'user',
    'subscriptions2',
    'aggregator',
    'blog',
    'captcha',
    'snowpenguin.django.recaptcha2',
    'markup_deprecated',
)

I don't know exactly where is the problem or how can I resolve it.
I've been searching about this ImportError but there is nothing talking about such an error.!

A: In django-1.8 some deprecated elements have been removed [Django-doc]:

*

*django.middleware.doc.XViewMiddleware will be removed. Use django.contrib.admindocs.middleware.XViewMiddleware instead.

So in your MIDDLEWARE_CLASSES, you should replace it with:
# settings.py

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.admindocs.middleware.XViewMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
In later versions MIDDLEWARE_CLASSES is renamed to MIDDLEWARE. If you upgrade the Django version, I advise you to check the deprecation page and make changes accordingly. Usually an item is marked deprecated two versions before it is removed. So it was marked deprecated in django-1.6.


text:
Q: save table structure to variable after 2nd row? if in html table have 5 row, 1 and 2 are safe, 3,4,5 must be saved as html structure to a variable. like this
var after2ndContent= '
3

4

5
'

A: Since this is a continuation of your previous post, you can use this
var elemRemoved = $("#tbl1 tr:gt(1)").detach();
var removedContents = $("
").append(elemRem).remove().html();
alert ( removedContents );

A: As jQuery does not have an outerHTML function, it's a bit tricky:
$('
').append($('tr:gt(1)').clone()).remove().html();

That is:

*

*Create a dummy table element

*Append the rows after the second row (gt() is zero-indexed)

*Get the contents of this table (including the
 tags) and remove the element

If you simply used $('tr:gr(1)').html(), you'd probably just get the contents of the first
.


text:
Q: Get all index from boolean list I have a problem with a pice of my code. I have a boolean list and need to know which index is true.
lst = [True, True, False]

for element in lst:
 print(lst.index(element))

why the output is 0,0,2?
I just need output 0,1,2

A: Do this.
lst = [True, True, False]

for idx, val in enumerate(lst):
    if val == True:
        print(idx)

The output
0
1

A: This will print only the true, so I'm not sure if its exactly what you need. If you provide more context we could probably help get a better answer for your specific problem.
lst = [True, True, False]

for element in lst:
    if element == True:
        print(element)


text:
Q: Flutter SliverAppBar -- Allow scrolling until SliverAppBar is no longer visible I am trying to create a CustomScrollView with a SliverAppBar. Since the SliverGrid that contains the main content may frequently have insufficient content to allow scrolling past the 'SliverAppBar', the UI now feels 'stuck'; the user can only scroll until a part of the SliverAppBar but never until it is hidden.
Therefore, I'm looking for away to allow scrolling only until the SliverAppBar is hidden.
Below is my current code,
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            backgroundColor: Colors.green,
            expandedHeight: 500.0,
            flexibleSpace: FlexibleSpaceBar(
              background: Image.asset(
                'tree_logo.jpg',
                fit: BoxFit.cover,
              ),
            ),
          ),

          SliverGrid.count(
            crossAxisCount: 4,
            crossAxisSpacing: 20.0,
            mainAxisSpacing: 20.0,
            childAspectRatio: 4 / 3,
            children: [
              PermissibleModuleCard(
                moduleTitle: 'Master Data',
                moduleDescription:
                    'Edit berbagai master-master data (client, supplier, tenaga kerja & material) serta konstanta-kosntanta lainnya (PPN, Alamat, etc.)',
              ),
            ],
          ),
        ],
      ),
    );
  }
}

A: After looking through the docs, I found the center property for CustomScrollView. This allowed me to set my SliverList as the center widget.
Final code:
class HomePage extends StatelessWidget {
  final GlobalKey _sliverKey = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: CustomScrollView(
        center: _sliverKey,
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: Image.asset(
              'tree_logo.jpg',
              fit: BoxFit.cover,
            ),
          ),
          SliverGrid.count(
            key: _sliverKey,
            crossAxisCount: 4,
            crossAxisSpacing: 20.0,
            mainAxisSpacing: 20.0,
            childAspectRatio: 4 / 3,
            children: [
              PermissibleModuleCard(
                moduleTitle: 'Master Data',
                moduleDescription:
                    'Edit berbagai master-master data (client, supplier, tenaga kerja & material) serta konstanta-kosntanta lainnya (PPN, Alamat, etc.)',
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return MasterDataModulesHomePage();
                  }));
                },
              ),
            ],
          ),
        ],
      ),
    );
  }
}