text:
Q: How to add a row dynamically in a tableLayout in Android I have a function who gets a list of products from a webpage, and I want to add a row in a tableLayout for each element of the list.
public void getProductsOfCategory() throws IOException{
        new Thread(){
            public void run(){
                //background code...
                try {
                    Bundle extras = getIntent().getExtras();
                    String categoryName = extras.getString("categoryName");

                    HttpGet httpget = new HttpGet("http://romal.hopto.org/foodadvisor/users/getProductsOfCategory.json?category="+categoryName);
                    HttpResponse httpresp = httpClient.execute(httpget);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    httpresp.getEntity().writeTo(baos);
                    final String content = new String(baos.toByteArray());
                    CategoryActivity.this.runOnUiThread(new Runnable(){
                        public void run(){
                            //foreground code (UI)
                            //update user interface, for example, showing messages
                            try {
                                JSONObject jObject = new JSONObject(content);
                                JSONArray productsList = jObject.getJSONArray("response");
                                for(int i=0; i<productsList.length();i++){
                                    JSONObject product = productsList.getJSONObject(i);
                                    JSONObject productData = product.getJSONObject("Product");
                                    String productDescription = productData.getString("description");
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }

In my layout xml file I have defined the table layout like this:
<TableLayout
            android:id="@+id/tableOfProducts"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/productDescription"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView"
                android:paddingBottom="7dp"
                android:paddingLeft="14dp"
                android:paddingRight="14dp"
                android:paddingTop="7dp"
                android:textSize="20dp" />

        </TableLayout>

I imagine I have to add some extra code in the for loop, adding a new row and a new textview for each element, and setting the content of the text view with the string that has the description of the product.
How can I do this?

A: Check this out, this is the general way of creating table rows dynamically. Modify it accordingly
XML file
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/main_table"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</TableLayout>

JAVA PART
TableLayout t1;

TableLayout tl = (TableLayout) findViewById(R.id.main_table);

Create table row header to hold the column headings
TableRow tr_head = new TableRow(this);
tr_head.setId(10);
tr_head.setBackgroundColor(Color.GRAY);        // part1
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));

I'm adding two data sections to the table row
TextView label_hello = new TextView(this);
         label_hello.setId(20);
         label_hello.setText("HELLO");
         label_hello.setTextColor(Color.WHITE);          // part2
         label_hello.setPadding(5, 5, 5, 5);
         tr_head.addView(label_hello);// add the column to the table row here

         TextView label_android = new TextView(this);    // part3
         label_android.setId(21);// define id that must be unique
         label_android.setText("ANDROID..!!"); // set the text for the header
         label_android.setTextColor(Color.WHITE); // set the color
         label_android.setPadding(5, 5, 5, 5); // set the padding (if required)
         tr_head.addView(label_android); // add the column to the table row here

After adding the columns to the table row its time to add the table row the the main table layout that we fetched at the start
tl.addView(tr_head, new TableLayout.LayoutParams(
                 LayoutParams.FILL_PARENT,                    //part4
                 LayoutParams.MATCH_CONTENT));

EDIT : YOU CAN DO THE FOLLOWING IN YOUR CODE
 TextView[] textArray = new TextView[productsList.length()];
 TableRow[] tr_head = new TableRow[productsList.length()];

 for(int i=0; i<productsList.length();i++){
 JSONObject product = productsList.getJSONObject(i);
 JSONObject productData = product.getJSONObject("Product");
 String productDescription = productData.getString("description");

//Create the tablerows
tr_head[i] = new TableRow(this);
tr_head[i].setId(i+1);
tr_head[i].setBackgroundColor(Color.GRAY);
tr_head[i].setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));

 // Here create the TextView dynamically

 textArray[i] = new TextView(this);
         textArray[i].setId(i+111);
         textArray[i].setText(productDescription);
         textArray[i].setTextColor(Color.WHITE);
         textArray[i].setPadding(5, 5, 5, 5);
         tr_head[i].addView(textArray[i]);

// Add each table row to table layout
tl.addView(tr_head[i], new TableLayout.LayoutParams(
                     LayoutParams.MATCH_PARENT,
                     LayoutParams.WRAP_CONTENT));

} // end of for loop

Creating the TextView and TableRow array are not necessary. You can just include part1, part2, part3 (if you need more than 1 field) and part4 inside your for loop.

A: Look, i think you have to modify your xml to adding rows to your tableview:
First, the inflater:
 LayoutInflater inflater = mContext.getLayoutInflater();

or in this way:
 LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

 //Here you can set up the layoutparameters from your tableview and the rowview.
 //Maybe you don't have to modify nothing from the parameters of your tableview so
 //you can dismiss it.

 TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
 TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);

 //Here were we take the tablelayout from your xml
 TableLayout tableLayout = (TableLayout)inflater.inflate(R.layout.tableOfProducts, null);

 //Like a told you before, maybe you don't need set the parameters of the tablelayout
 //so you can comment next line.
 tableLayout.setLayoutParams(this.tableParams);

 TableRow tableRow = new TableRow(context);
 tableRow.setLayoutParams(this.tableParams);

 //Here you have to create and modify the new textview.
 TextView textView = new TextView(context);
 textView.setLayoutParams(this.rowParams);

 tableRow.addView(textView);

 tableLayout.addView(tableRow);

If you need more help, tell me, if it is helpful, rating me!!! ;) Un saludo Gallega! O como se dice en gallego: una aperta!

A: for this, you have to create one xml file for row, then you have to modify your layout.xml file like
<ScrollView>
  <LinearLayout orientation=vertical id="+id/rowHolder">
  </LinearLayout
</scrollview>

Then in for loop, inflate the row layout and add it runtime to rowHolder object.

A: I'm new myself to Android, and after years with Python/Gtk, I'm lost if I can't think in terms of Model/View/Presenter.
one useful approach I managed to apply, it puts me back into that optics, and even if it's not relative to a Table, I'm quite sure it can be extended to that (I guess this page would be a good start, for me too).
start by declaring the two objects in your fragment (or activity):
List<String> stringList;  // think of it as the model.
ArrayAdapter<String> listAdapter;  // and this would be the presenter

define the model in the fragment constructor:
stringList = new ArrayList<>();

next, when the onCreateView of my fragment is invoked, I do this (edit correspondingly if you're using Activity, not Fragment):
View rootView = inflater.inflate(R.layout.fragment_taxonomy, container, false);
ListView mainListView = rootView.findViewById(R.id.taxonomy_results);

// Create ArrayAdapter using the string list.  think of it as the presenter.
// see how it's being handled a model and a view.
listAdapter = new ArrayAdapter<>(
        rootView.getContext(), R.layout.textrow, stringList);

// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );

textrow.xml is an extra layout which is being reused every time I add an element to the stringList model.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

in the rest of the code, I only "talk" to listAdapter, and I only need its two add and clear methods, to add elements, or for clearing the list.

A: There are many ways to do this. First, for minimizing your code, create an XML file that initializes the TableRow and its attribute (TextView should be also included). Then, in your target XML file that is linked to the activity, you have to create only the TableLayout.
In the main, create LayoutInflater that will link the items to gather. Then, create as much as you can of the number of TableRow. In the end, each TableRow that has a unique variable should be linked using addView() to the TableLayout that you have created in the XML.
For more, see here. https://github.com/AreejTurky/Dynamic-TableRow-Generation


text:
Q: WinRT | C++ - HTTP Post File - The certificate authority is invalid or incorrect Basically I have two concerns, however the focus is on how to get around the certification.
I am having a hard time understanding how to make an HTTP post request in WinRT|C++. I have an ASP.Net-6-Web-Api-Project, which I have already been able to communicate with via a Python project and a C++ project (via Curl). I also tested the api via Postman. Every time doing so I had to ignore the validation of certification and it worked fine.
But now I have a WinRT/C++ project and have thrown together the following code. I want to be able to upload a file. In my case it is a point cloud in a .ply syntax as a string.
My Concerns:

*

*In WinRT I got the expected error for invalid/untrusted certification, so I looked up what to do and ended up using IgnorableServerCertificateErrors from HttpBaseProtocolFilter, like you can see at the end of my code. But that did not fix my error. What am I missing? I still get the errors:

WinRT originate error - 0x80072F0D : 'The certificate authority is invalid or incorrect'.
WinRT originate error - 0x80190190 : 'The response status code does not indicate success: 400 ().'.

*From the point of view of a developer familiar with WinRT, is the implementation correct in terms of an HTTP post request? Especially the lines
binaryContent.Headers().Append(L"Content-Type", L"image/jpeg"); andHttpContentDispositionHeaderValue disposition{ L"form-data" }; And what are the follow lines for? Is this just about assigning arbitrary names?

disposition.Name(L"fileForUpload");
disposition.FileName(L"test.ply");

Code:
    void HL2ResearchMode::SendPLY(std::wstring const& pointCloud)
    {
        OutputDebugString(L"--- SendPLY()\n");

        if (pointCloud.size() == 0)
            return;

        init_apartment();

        auto buffer{
            winrt::Windows::Security::Cryptography::CryptographicBuffer::ConvertStringToBinary(
                pointCloud,
                winrt::Windows::Security::Cryptography::BinaryStringEncoding::Utf8
            )
        };

        winrt::Windows::Web::Http::HttpBufferContent binaryContent{ buffer };
        // binaryContent.Headers().Append(L"Content-Type", L"text/plain;charset=utf8");
        binaryContent.Headers().Append(L"Content-Type", L"image/jpeg");

        winrt::Windows::Web::Http::Headers::HttpContentDispositionHeaderValue disposition{ L"form-data" };
        //winrt::Windows::Web::Http::Headers::HttpContentDispositionHeaderValue disposition{ L"multipart/form-data" };
        binaryContent.Headers().ContentDisposition(disposition);
        disposition.Name(L"fileForUpload");
        disposition.FileName(L"test.ply");

        winrt::Windows::Web::Http::HttpMultipartFormDataContent postContent;
        postContent.Add(binaryContent);

        winrt::Windows::Web::Http::HttpResponseMessage httpResponseMessage;
        std::wstring httpResponseBody;

        try
        {
            // Send the POST request.
            winrt::Windows::Foundation::Uri requestUri{ L"https://192.168.178.41:5001/api/meshes/uploadPointCloud" };
            winrt::Windows::Web::Http::Filters::HttpBaseProtocolFilter myFilter;

            auto fu = myFilter.IgnorableServerCertificateErrors();
            fu.Append(ChainValidationResult::Expired);
            fu.Append(ChainValidationResult::Untrusted);
            fu.Append(ChainValidationResult::InvalidName);
            fu.Append(ChainValidationResult::InvalidSignature);
            fu.Append(ChainValidationResult::InvalidCertificateAuthorityPolicy);

            winrt::Windows::Web::Http::HttpClient httpClient(myFilter);
            httpResponseMessage = httpClient.PostAsync(requestUri, postContent).get();
            httpResponseMessage.EnsureSuccessStatusCode();
            httpResponseBody = httpResponseMessage.Content().ReadAsStringAsync().get();
        }
        catch (winrt::hresult_error const& ex)
        {
            httpResponseBody = ex.message();
        }
        std::wcout << httpResponseBody;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to detect that there is no activity from user in last 20 seconds(php)
Possible Duplicate:
Detecting idle time in JavaScript elegantly

I am working on a website and I want the cursor to be placed in a particular textbox if there is no activity from the user since last 20 seconds. Please help.


text:
Q: Removing the box on mouse click in as3 I am trying to remove a box that i have created on the screen.I have a box exported as
Box and a ship exported as player, they are both movie clips. this is the code:
package {
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class Main extends MovieClip {

        //playermovevar
        private var _player:MovieClip;
        private var _playerSpeed:Number=5;
        private var _destinationX:int;
        private var _destinationY:int;

        //boxaddvar
        private var boxAmount:Number=0;
        private var boxLimit:Number=20;
        private var _root:Object;

        public function Main() {
            createPlayer();

            //playermovlisten
            stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
            stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseHandlerdown);

            //boxaddlisten
            addEventListener(Event.ENTER_FRAME, eFrame);

            _box.addEventListener(MouseEvent.CLICK, boxclick);

        }

        //playermoving
        private function createPlayer():void {
            _destinationX=stage.stageWidth/2;
            _destinationY=stage.stageHeight/2;

            _player = new Player();
            _player.x=stage.stageWidth/2;
            _player.y=stage.stageHeight/2;
            stage.addChild(_player);
        }

        private function enterFrameHandler(event:Event):void {
            _player.x += (_destinationX - _player.x) / _playerSpeed;
            _player.y += (_destinationY - _player.y) / _playerSpeed;
        }

        private function mouseHandlerdown(event:MouseEvent):void {
            _destinationX=event.stageX;
            _destinationY=event.stageY;
            addEventListener(MouseEvent.MOUSE_UP, mouseHandlerup);

            rotatePlayer();
        }
        private function mouseHandlerup(event:MouseEvent):void {

        }

        private function rotatePlayer():void {
            var radians:Number=Math.atan2(_destinationY-_player.y,_destinationX-_player.x);
            var degrees:Number = radians / (Math.PI / 180) + 90;
            _player.rotation=degrees;
        }
        //boxadding
        private function eFrame(event:Event):void {
            if (boxAmount<=boxLimit) {
                boxAmount++;

                var _box:Box=new Box  ;

                _box.y=Math.random()*stage.stageHeight;

                _box.x=Math.random()*stage.stageWidth;

                addChild(_box);

            } else if (boxAmount >= boxLimit) {
                removeEventListener(Event.ENTER_FRAME, eFrame);
            } else {
                addEventListener(Event.ENTER_FRAME, eFrame);
            }
        }
        function boxclick(event:MouseEvent):void {
            removeChild(_box);
        }
    }

It gives me this error:
1120: Access of undefined property _box. _box.addEventListener(MouseEvent.CLICK, boxclick);
1120: Access of undefined property _box. removeChild(_box);
anyone know whats wrong?
thanks

A: *

*You forgot to close the } for the package.

*Your _box variable does not exists as global attribute, but you are trying to access it globally.
:)
[edit]
Just remove this line from the top
_box.addEventListener(MouseEvent.CLICK, boxclick);

and put it after
var _box:Box=new Box  ;

Then change boxclick function to:
function boxclick(event:MouseEvent):void {
    var _box:Box = event.currentTarget as Box; // here is your box again

    // make with _box what you want here. Like,

    removeChild(_box);
}

A: Not sure what results you're wanting but try this and feel free to ask any questions.
package {
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class Main extends MovieClip {

        //playermovevar
        private var _player:Player;
        private var _playerSpeed:Number=5;
        private var _destinationX:int;
        private var _destinationY:int;

        //boxaddvar
        private var boxAmount:Number=0;
        private var boxLimit:Number=20;
        private var _root:Object;

        private var _box:Box;
        private var arrayOfBoxes:Array = new Array(boxLimit);

        public function Main() {
            createPlayer();

            //playermovlisten
            stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler, false, 0, true);
            stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseHandlerdown, false, 0, true);

            //boxaddlisten
            addEventListener(Event.ENTER_FRAME, eFrame, false, 0, true);

        }

        //playermoving
        private function createPlayer():void {
            _destinationX=stage.stageWidth/2;
            _destinationY=stage.stageHeight/2;

            _player = new Player();
            _player.x=stage.stageWidth/2;
            _player.y=stage.stageHeight/2;
            stage.addChild(_player);
        }

        private function enterFrameHandler(event:Event):void {
            _player.x += (_destinationX - _player.x) / _playerSpeed;
            _player.y += (_destinationY - _player.y) / _playerSpeed;
        }

        private function mouseHandlerdown(event:MouseEvent):void {
            _destinationX=event.stageX;
            _destinationY=event.stageY;
            addEventListener(MouseEvent.MOUSE_UP, mouseHandlerup, false, 0, true);

            rotatePlayer();
        }
        private function mouseHandlerup(event:MouseEvent):void {

        }

        private function rotatePlayer():void {
            var radians:Number=Math.atan2(_destinationY-_player.y,_destinationX-_player.x);
            var degrees:Number = radians / (Math.PI / 180) + 90;
            _player.rotation=degrees;
        }
        //boxadding
        private function eFrame(event:Event):void {
            if (boxAmount<=boxLimit) {
                boxAmount++;

                _box =new Box();

                _box.y=Math.random()*stage.stageHeight;

                _box.x=Math.random()*stage.stageWidth;

                _box.addEventListener(MouseEvent.CLICK, boxclick, false, 0, true);

                arrayOfBoxes.push(_box);

                addChild(_box);

            } else if (boxAmount >= boxLimit) {
                removeEventListener(Event.ENTER_FRAME, eFrame);
            } else {
                addEventListener(Event.ENTER_FRAME, eFrame, false, 0, true);
            }
        }
        function boxclick(evt:MouseEvent):void {
            removeChild(evt.currentTarget as Box);
        }
    }
}


text:
Q: Evaluating a function after simplifying to avoid infinite expressions
My Poly[j_, s_] function simplifies to a polynomial for all j. So I defined a PolySim[j_, s_] = Simplify[Poly[j,s]] function.
However, if I try to evaluate PolySim[j,0], since this is PolySim[j,0] = Simplify[Poly[j,0]] and it plugs in s = 0 before simplifying it to a polynomial, leading to infinite expression and messes up my calculation.
Is there any way I can simplify first and then evaluate with my desired values?
Thanks!

A: In general to avoid divergences you can use the Limit function.
Example, let be
num[x_, n_, j_] := (1/(x - j))Product[x - i, {i, 1, n}]

Then
num[x, 6, 3]

produces $(-6 + x) (-5 + x) (-4 + x) (-2 + x) (-1 + x)$. If I want to evaluate this function when $x=3$, it's "obvious" that it will be $(-6 + 3) (-5 + 3) (-4 + 3) (-2 + 3) (-1 + 3)=-12$, but if I write it like this
num[3, 6, 3]

Mathematica gives me
"Infinite expression 1/0 encountered."

To avoid this divergence I can use the Limit function as follows:
Limit[num[x, 6, 3], x -> 3]

which returns $-12$, as expected.


text:
Q: Guava retryer that calls a function until an exception occurs Say I have some code like this:
public void deleteResource(UUID resourceId) {
    deleteFromDb();
    deleteFromALotOfOtherPlaces();    // Takes a long time!
}

public DescribeResourceResult describeResource(UUID resourceId) throws ResourceNotFoundException {
    return getResourceDescription(resourceId);
}

Unfortunately, the delete doesn't signal that it's completed. The only way to verify that the deletion has completed is to call describeResource which will throw an exception if the resource has been deleted.
I want to write a retryer that will repeatedly call describeResrouce until a ResourceNotFoundException occurs. How can I do that?
Here's what I have so far:
final Retryer<ResourceNotFoundException> deleteResourceRetryer = RetryerBuilder.<ResourceNotFoundException>newBuilder()
                .withWaitStrategy(WaitStrategies.fixedWait(500, TimeUnit.MILLISECONDS))
                .withStopStrategy(StopStrategies.stopAfterDelay(10, TimeUnit.SECONDS))
                .build();

// Error: Bad return type in lambda expression: DescribeResourceResult cannot be converted to ResourceNotFoundException
deleteResourceRetryer.call(() -> describeResource(resourceId));

Thank you!

A: I not so familar with Guava's Retryer, thus after short investigation I was not able to find ready-to-use StopStrategy, so my advice is to implement it yourself
static class OnResourceNotFoundExceptionStopStrategy implements StopStrategy {

    @Override
    public boolean shouldStop(Attempt attempt) {
        if (attempt.hasException()
                     && attempt.getExceptionCause() instanceof ResourceNotFoundException) {
            return true;
        }
        return false;
    }

}

With that strategy retries will stop when you'll catch ResourceNotFoundException. After that fix types and correctly define Retryer
final Retryer<DescribeResourceResult> deleteResourceRetryer = RetryerBuilder
            .<DescribeResourceResult>newBuilder()
            .retryIfResult(Predicates.notNull())
            .withWaitStrategy(WaitStrategies.fixedWait(500, TimeUnit.MILLISECONDS))
            .withStopStrategy(new OnResourceNotFoundExceptionStopStrategy())
            .build();

And finally, start retrying
try {
    deleteResourceRetryer.call(() -> describeResource(resourceId));
} catch (ExecutionException e) {
    // should not happens, because you will retry if any exception rather
    // than ResourceNotFoundException raised in your describeResource method
} catch (RetryException e) {
    // should not happens, because my implementation of StopStrategy
    // (as it looks in this example) is effectively infinite, until target exception.
    // For sure you're free to override it to anything you want
}

Hope it helps!


text:
Q: How long until a random word with letters "A", "B", "C" ends in the pattern "ABC"? Let's say I have word constructed from random letters, A Band C with $\mathbf{P}(A) = \mathbf{P}(B) = \mathbf{P}(C) = \frac{1}{3}$.  I am going to do a random trial and record the letters I got.  The experiment stops the first time I spell out the word ABC.  Let $N$ be the number of trials until I make the word ABC out of letters.
Here are some trial words:
BBBBACCCCBABAABBBBCBCCBBBCACBCAACBABC
BBACCCCACABABC
CBBCCCABBABC
BABBBCAAAABC
CBBBCCBCCABABC
CCBCBBABC
ACCACCCCBCBBBCBACCBBAABBABBACCCBCBAABC
ABAAABBBABC
ABABC
BBCACAACCACCAABAAABBCABBBBACABACBACBAABACCCBCBCCCBCCCBAAAABC

I am asking for the expected length of this word.  And the variance.

*

*$\mathbb{E}[N]$ expectation

*$\mathbb{E}[N^2] - \mathbb{E}[N]^2$ variance

Sounding more like a textbook:
Our random variable is $X \in \{ A,B,C\}$ where each letter appears with equal probability.  Let's examine the sequence $(X_1, X_2, X_3, \dots , X_n)$ where $X_i$ are iid random variables with probability the same as $X$.  Our process stops at time $t = N$ when $(X_{N-2}, X_{N-1}, X_N) = (A,B,C)$.  What is the expected value of $N$ ?

A: Expectation is easy enough (Variance seems like more work).
We have four states, according to how much of $ABC$ is complete.  Thus the states are $\emptyset, A, AB, ABC$.  Of course, Start is $\emptyset$ and End is $ABC$.  For a state $\mathscr S$ we denote by $E[\mathscr S]$ the expected number of steps, given that you are starting from $\mathscr S$.  The answer you want is $E[\emptyset]$.
We note that $$E[AB]=1\times \frac 13+(E[A]+1)\times \frac 13+(E[\emptyset]+1)\times \frac 13$$
$$E[A]=(E[AB]+1)\times \frac 13+ (E[A]+1)\times \frac 13+(E[\emptyset]+1)\times \frac 13$$
$$E[\emptyset]=(E[A]+1)\times \frac 13+(E[\emptyset]+1)\times \frac 23$$
Solving this linear system (and trusting that no arithmetic errors have been made) yields:  $$E[AB]=18\quad E[A]=24\quad \boxed {E[\emptyset]=27}$$

A: Once you spot that this is a Markov chain (as correctly tagged) the problem is easy to solve with first step analysis.
States: $0, A, AB, ABC$, meaning that the ending of the word you already have is not helpful (equivalent to the empty word), ends with $A$, ends with $AB$ and ends with $ABC$, respectively. The state $ABC$ is the only absorbing state.
Transitions:
$0\rightarrow 0$ if you get $B$ or $C$, so the transition probability is $2/3$.
$0\rightarrow A$ if you get $A$, so the transition probability is $1/3$.
$A\rightarrow 0$ if you get $C$, so the transition probability is $1/3$.
$A\rightarrow A$ if you get $A$, so the transition probability is $1/3$.
$A\rightarrow AB$ if you get $B$, so the transition probability is $1/3$.
$AB\rightarrow 0$ if you get $B$, so the transition probability is $1/3$.
$AB\rightarrow A$ if you get $A$, so the transition probability is $1/3$.
$AB\rightarrow ABC$ if you get $C$, so the transition probability is $1/3$.
So the transition matrix is
$\begin{pmatrix}
2/3 & 1/3 & 0 & 0\\
1/3 & 1/3 & 1/3 & 0\\
1/3 & 1/3 & 0 & 1/3\\
0 & 0 & 0 & 1\\
\end{pmatrix}$
Can you finish from here? There is a formula that computes the expected number of steps from each transient state given the transition matrix.

A: For the variance, one step analysis is not enough. Basically, you need to know the probability $p_n$ that you make exactly $n$ steps starting from the empty word. It is easiest to do by finding the vector $v_n$ with length 4 whose $i$-th entry represents the probability that after $n$ steps you are in state $i$. If you had an $ABC$ somewhere, you stay in the fourth state (ABC) forever.
Then $v_0= (1, 0, 0, 0)$, and $v_{n+1}=v_n\cdot P$, where $P$ is tmatrix in my first answer:
$P= \begin{pmatrix}
2/3 & 1/3 & 0 & 0\\
1/3 & 1/3 & 1/3 & 0\\
1/3 & 1/3 & 0 & 1/3\\
0 & 0 & 0 & 1\\
\end{pmatrix}$
So $v_n=v_0\cdot P^n$. You can compute this by standard linear algebraic techniques: compute the Jordan normal $J=S^{-1}AS$ form of $P$ (together with $S$), then exponentiation is easy, and $P^n= SJ^nS^{-1}$.
Once you have a closed form for $v_n$, add the first three coordinates: that is the probability that the length of the word is at least $n$. Denoting this by $q_n$ (it will be a linear combination of geometric series, well, almost...), we have $p_n= q_n-q_{n+1}$ (still a linear combination of geometric series, if you are lucky). Then you can compute the variance from definition, but I suggest you use the moment generating function, instead. Or just use the formulas here:
https://en.wikipedia.org/wiki/Absorbing_Markov_chain#Variance_on_number_of_visits

A: Here is a quick simulation in R resulting in the mean of the distribution of lengths of about 27.1 (variance 591) and so confirming the result of @lulu.
mc = function( state ){

  if( state == '0' ){
      if( runif(1,0,1) < 1/3 ) { return('A') } else{ return('0')}
  }

  if( state == 'A' ){
      u = runif(1,0,1)
      if( u < 1/3 ) { return('A') }
      if( u < 2/3 ) { return( 'AB') } else { return('0') }
  }

  if( state == 'AB' ){
      u = runif(1,0,1)
      if( u < 1/3 ) { return('A') }
      if( u < 2/3 ) { return('0') } else { return('ABC') }
  }
}

state = '0'; nsim = 1000000;
n.abc = 0; d.abc = NULL

for( i in 1:nsim){

   state = mc( state )
   n.abc = n.abc + 1

   if( state == 'ABC' ){
      d.abc = append( d.abc, n.abc )
      n.abc = 0
      state = '0'
   }
}

d.abc = unlist( d.abc )
print( mean( d.abc ))
hist( d.abc)

A: Instead of using the apparatus of Markov chains, the result for the mean can be immediately obtained using Kac's theorem about return times (an important result that is often used, eg, for proving asympotic optimality of Lempel-Ziv compression algorithms - see eg Cover & Thomas, 13.5).
In this case, the probability of success of the ergodic $0$-$1$ process is $p=(1/3)^3=1/27$, hence the mean return time is $\langle T \rangle = 1/p=27$
The computation of the variance seems to be much more difficult. Some work in "Variations on a Theme by Mark Kac" (P. W. Kasteleyn , Journal of Statistical Physics, Vol. 46, Nos. 5/6, 1987).


text:
Q: get current options in a fancybox after having selected them I have created a fancybox dialog which contains a multiple select (#select-a). Now I have another multiple select within a form outside the fancybox dialog, that has the same options (#select-b).
I want to sync the selected options from #select-a with #select-b and therefore I'm trying to find out which are the options the user has selected within #select-a, but if I try to get them they all return 'false', but I can get their values.
Initially, all of the options of #select-a are deselected, so I'm thinking the selections cannot be retrieved. Can it be because the #select-a is in a fancybox?

A: If you have items using the same ID (e.g. #select-a) than only one of them will be submitted. You can use "onCleanup" callback to access content of fancybox and update your form.


text:
Q: Save attachment then move email in outlook 2010 I'm new to VB and have been struggling to try and create a VBA macro that will automatically perform the following tasks upon email receival:
1) Checks to see if the email originated internally, or externally. (If external ignore)
2) Checks to see if the email has an attachment. (If no attachment, then ignore)
3) Checks the attachment name, should be like "report" (full name is generally "Report 12198 blah blah.pdf"). (If attachment name is not like "report" then ignore)
4) Save the attachment in G:\Test
5) Move the email to an Outlook folder named "Completed"
I've seen many sites that have code for saving attachments, moving emails to folders but no one else seems to have had the same issue as me; combining these two.
I initially thought I could use Outlook Rules to help do some of this, but the code I have so far (for saving attachments) doesn't show up as a script.
In addition I've read on a site (can't remember which one) that you can't use a 'For Each' loop when trying to do things such as 'Move' or 'Delete', so I'm not too sure if the code below should be useable.
Any help would be greatly appreciated. This is the code I have at the moment:
Sub GetAttachments()

On Error GoTo GetAttachments_err

Dim ns As NameSpace
Dim Inbox As MAPIFolder
Dim Item As Object
Dim Atmt As Attachment
Dim StringLength As Long
Dim FileName As String
Dim i As Integer

Set ns = GetNamespace("MAPI")
Set Inbox = ns.GetDefaultFolder(olFolderInbox)
i = 0

If Inbox.Items.Count = 0 Then
   MsgBox "There are no messages in the Inbox.", vbInformation, _
          "Nothing Found"
    Exit Sub
End If

For Each Item In Inbox.Items
   For Each Atmt In Item.Attachments
        If Left(Atmt.FileName, 6) Like "*REPORT*" Then
            StringLength = Len(Atmt.FileName)
            FileName = "G:\Test\" & Left(Atmt.FileName, (StringLength - 13)) & Format(Item.CreationTime, "ddmmmyyyy") & ".pdf"
      Atmt.SaveAsFile FileName
      i = i + 1
      End If
   Next Atmt
Next Item

If i > 0 Then
   MsgBox "I found " & i & " attached files." _
      & vbCrLf & "I have saved them into the Test Folder." _
      & vbCrLf & vbCrLf & "Have a nice day.", vbInformation, "Finished!"
Else
   MsgBox "I didn't find any attached files in your mail.", vbInformation, _
   "Finished!"
End If

GetAttachments_exit:
    Set Atmt = Nothing
    Set Item = Nothing
    Set ns = Nothing
    Exit Sub

GetAttachments_err:
   MsgBox "An unexpected error has occurred." _
      & vbCrLf & "Please note and report the following information." _
      & vbCrLf & "Macro Name: GetAttachments" _
      & vbCrLf & "Error Number: " & Err.Number _
      & vbCrLf & "Error Description: " & Err.Description _
      , vbCritical, "Error!"
   Resume GetAttachments_exit

Exit Sub

End Sub

A: I think the problem is in the declaration part.
Try to change this:
Dim ns As NameSpace
Dim Inbox As MAPIFolder
Dim Atmt As Attachment
Dim Item as Object

with this:
Dim ns As outlook.NameSpace
Dim Inbox As outlook.MAPIFolder
Dim Atmt As outlook.Attachment
Dim Item as outlook.MailItem

Then in your code, you only check for the attachments?
I can't seem to find the checking for internal or external?

A: to check every incoming mail when received you have to do the following:
First put in "ThisOutlookSession"
Option Explicit
Private WithEvents objInspectors As Outlook.Inspectors
Public WithEvents myreceivedItems As Outlook.Items

Private Sub Application_Startup()
    Set objInspectors = Outlook.Inspectors

Dim folder As Outlook.MAPIFolder
Set folder = oNamespace.GetDefaultFolder(olFolderInbox)
Set myreceivedItems = folder.Items
End Sub

Private Sub myreceivedItems_ItemAdd(ByVal ItemMail As Object)
If ItemMail.Class = olMail Then Call whatdotowithyourincomingmails(ItemMail, true)
End Sub

whatdotowithyourincomingmails would be the Sub that is called with every mail you receive. This can be in any module, I would not put it into thisoutlooksession.
the code there could be like below. I did copy my own code and changed it to your Needs, I think it should work. The Folder completed has to be a subfolder of your inbox.
The subject of the mail will be changed, as you can see in the code - this is just to make sure you know why the mail is in completed.
If the attachment as file already exists in G:\test, the attachment is ignored. Of course that could be changed in any way (adding timestamp, ideleting existing files,...)
Only mails will be moved, that have exactly one attachment with "Report" at the beginning of the Name. Other attachments will be ignored.
Sub whatdotowithyourincomingmails (olitem As Outlook.MailItem, verschieben As Boolean)
'On Error GoTo exit_sub
Dim lngAttCount As Long, i As Long
Dim Datei As String
Dim anzahl_pdf As Integer
Dim anzahl As Integer

    lngAttCount = olitem.Attachments.Count
    anzahl_pdf = 0
'Zählen pdfs:
    If lngAttCount = 0 Then GoTo Ende_nix
        For i = lngAttCount To 1 Step -1
        With olitem.Attachments.Item(i)
        If LCase(Mid(.FileName, 1, 6)) = "report" Then anzahl_pdf = anzahl_pdf + 1
        End With
        Next i
'verarbeiten wenn 1 pdf
    If Not anzahl_pdf = 1 Then GoTo Ende_nix
        For i = lngAttCount To 1 Step -1
        With olitem.Attachments.Item(i)
         If not LCase(Mid(.FileName, 1, 6)) = "report" Then GoTo naechste
            Datei = "g:\test\" & .FileName
            If CreateObject("Scripting.FileSystemObject").FileExists(Datei) = True Then
                GoTo Ende_nix
                Else
                .SaveAsFile Datei
                anzahl = anzahl + 1
            End If
        End With
naechste:
        Next i
    olitem.Subject = olitem.Subject & " || autosaveandmove"
    If verschieben = True Then
        Call movesomewhereelse(olitem, "completed")
    End If
Ende_nix:
exit_sub:
End Sub

Sub movesomewhereelse(olitem As MailItem, move_to_as string)
Dim olfolder As MAPIFolder
Dim folderPath As String
    'the next line is looking in which Folder the item is; if you are always working with inbox it can be replaced by the path
    folderPath = GetPath_auto(olitem)
    Set olfolder = GetFolder(folderPath)

On Error GoTo exit_sub
    Dim Subfolder As Outlook.MAPIFolder
    Set Subfolder = olfolder.Folders(move_to_as)
    olitem.UnRead = False
    olitem.Move Subfolder
exit_sub: Exit Sub
End Sub

Public Function GetFolder(strFolderPath As String) As MAPIFolder
  ' strFolderPath needs to be something like
  '   "Public Folders\All Public Folders\Company\Sales" or
  '   "Personal Folders\Inbox\My Folder"
On Error GoTo schas
  Dim objApp As Outlook.Application
  Dim objNS As Outlook.NameSpace
  Dim colFolders As Outlook.Folders
  Dim objFolder As Outlook.MAPIFolder
  Dim arrFolders() As String
  Dim i As Long
 ' On Error Resume Next

  strFolderPath = Replace(strFolderPath, "\\", "")
  strFolderPath = Replace(strFolderPath, "/", "\")
  arrFolders() = Split(strFolderPath, "\")
  Set objApp = Application
  Set objNS = objApp.GetNamespace("MAPI")
  Set objFolder = objNS.Folders.Item(arrFolders(0))
  If Not objFolder Is Nothing Then
    For i = 1 To UBound(arrFolders)
      Set colFolders = objFolder.Folders
      Set objFolder = Nothing
      Set objFolder = colFolders.Item(arrFolders(i))
      If objFolder Is Nothing Then
        Exit For
      End If
    Next
  End If

  Set GetFolder = objFolder
GoTo ende
schas:
'MsgBox ("Ordner für verschieben nicht gefunden")
ende:
  Set colFolders = Nothing
  Set objNS = Nothing
  Set objApp = Nothing
End Function

Function GetPath_auto(Item As MailItem) As String
'gibt des gesamten Pfad des items zurück
  Dim folder As Outlook.MAPIFolder
  Dim folderPath As String
  Set folder = Item.Parent
  folderPath = folder.Name
  Do Until folder.Parent = "Mapi" Or folder.Parent = "Freigegebene Daten" 'Or folder.Parent = "Stamm - Postfach"
    Set folder = folder.Parent
    folderPath = folder.Name & "\" & folderPath
  Loop
  GetPath_auto = folderPath
End Function

A: By the way, if you want to use your script as a rule, define function as
Sub GetAttachments(mItem As MailItem)

It will then appear in the list of functions when editing a rule


text:
Q: Организовать простой веб-сервис Есть голая VPS-ка на линуксе. Задача - организовать простенькую страничку, с помощью которой можно будет аплоадить большие (300 мегабайт) файлы на сервер. Тупо html-ка с парой формочек, доступная из веба.Поднимать апач + php для такой ерунды не хочется, тем более, грамотно конфигурировать я их не умею. Может есть более простые варианты? С помощью чего такое наиболее легко и быстро реализовать?
A: Цитата Тупо html-ка с парой формочек,доступная из веба.Поднимать апач + php для такой ерундыне хочется,Цитатаа ктож тогда будет обслуживать те самые html-ки? к тому же 300 Мб - объем, который превышает "дефолтные" лимиты. Так что веб-сервер прийдется и ставить и настраивать...======================================================с "собственным веб-сервером" есть еще такая штука как webmin, или же usermin. Если задача чисто загружать и скачивать файлы, то возможно, usermin подойдет. У него есть подобные функции в меню, НО есть одно "но" войти в него смогут лишь пользователи, созданные в системе (в самом линуксе). Хотя, может быть этот факт защиты информации наоборот, будет совсем не лишним?..http://www.webmin.com/usermin.html
A: Nginx upload module вам должен подойти.
A: То же Mojolicious-приложение может работать как веб-сервис. Из требования более-менее свежая версия Perl.
A: Ну блин, так сервак же на голом железе всё одно подымать! Вот тут есть, хоть и с Апачем, но "искаропки": http://www.denwer.ru/ Он, хоть и для тестинга в основном, но при надлежащей прикрутке и в боевом режиме неплохо работает. Там всё написано! А дальше - вот: http://www.joomla-docs.ru/%D3%F1%F2%E0%ED%EE%E2%EA%E0_Joomla_%ED%E0_%C4%E5%ED%E2%E5%F0А потом - сюда: http://www.joomla-docs.ru/FAQ_по_шаблонам_Joomla


text:
Q: Sqlite, sort second column without messing the order in the first I have the following table:
15|flex        |2|low   |Not started
16|flex        |1|medium|Not started
17|flex        |2|medium|Not started
18|gridonly-med|1|low   |Not started
19|gridonly-med|2|low   |Not started
20|gridonly-med|4|low   |Not started
21|gridonly-med|1|medium|Not started
22|gridonly-med|2|medium|Not started
23|gridonly-med|4|medium|Not started

and what I need is to sort it(desc) by 3-rd column without messing column 2 and column 4.
Basically, I need to get this table:
15|flex        |2|low   |Not started
17|flex        |2|medium|Not started
16|flex        |1|medium|Not started
20|gridonly-med|4|low   |Not started
19|gridonly-med|2|low   |Not started
18|gridonly-med|1|low   |Not started
23|gridonly-med|4|medium|Not started
22|gridonly-med|2|medium|Not started
21|gridonly-med|1|medium|Not started

I have tried:
ORDER BY column4 DESC, column1 ASC

but it didn't work.
I get:
23|gridonly-med|4|medium|Not started
20|gridonly-med|4|low   |Not started
22|gridonly-med|2|medium|Not started
19|gridonly-med|2|low   |Not started
17|flex        |2|medium|Not started
21|gridonly-med|1|medium|Not started
18|gridonly-med|1|low   |Not started
16|flex        |1|medium|Not started

If someone points out any clause or any other thing which I could use to solve my issue I would really appreciate any help, thank you.

A: You must sort first by col2, then by col4 and finally by col3 descending:
ORDER BY col2, col4, col3 DESC

Note that I use the fact that 'flex' is sorted alphabetically before 'gridonly-med' and 'low' is sorted alphabetically before medium, so if there were different values the code would not work.
For certain results you should use conditional sorting:
ORDER BY col2 = 'flex' DESC,
         col4 = 'low' DESC,
         col3 DESC

or:
ORDER BY CASE col2 WHEN 'flex' THEN 1 ELSE 2 END,
         CASE col4 WHEN 'low' THEN 1 ELSE 2 END,
         col3 DESC

and you can extend the branches of the CASE expressions to include more values.
See the demo.


text:
Q: ubuntu 14.10: ibus only working in the search applicatoin Just installed Ubunut 14.10 (clean install with old $HOME directory). Things are working fine except for one thing: the Chinese input in ibus. It actually works fine in all the search applications triggered by Windows key or ALT key. But nowhere else. Anyone seen this before?

A: I had the same problem. After I tried the following things, it worked for me (I'm not sure the exactly reason that made it work):

*

*Run a system update: sudo apt-get update; sudo apt-get upgrade.

*Remove ibus-pinyin and install ibus-libpinyin: sudo apt-get remove ibus-pinyin; sudo apt-get install ibus-libpinyin.

*Open a terminal and run im-config, then click "OK" and "YES", then select "ibus" and click "OK" twice.

*Reinstall ibus and ibus-gtk: sudo apt-get --reinstall install ibus; sudo apt-get --reinstall install ibus-gtk

*Reboot the system


text:
Q: I have written the following code for a neural network, but I am getting a ValueError: Failed to convert a NumPy array to a Tensor I have written the following code for a neural network to perform regression on a dataset, but I am getting a ValueError
import tensorflow as tf
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
from numpy import loadtxt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

data1_train = pd.read_csv('../input/car-security/DoS_dataset.csv',
names=["Timestamp", "CAN ID", "DLC", "DATA[0]", "DATA[1]", "DATA[2]", "DATA[3]",
"DATA[4]", "DATA[5]", "DATA[6]", "DATA[7]", "Flag"])

data1_train.head()

#Splitting dataset to know if the data is injected or normal
data1_features = data1_train.copy()
data1_labels = data1_features.pop('Flag')

data1_features = np.array(data1_features)
data1_features

array([[1478198376.389427, '0316', 8, ..., '21', '00', '6f'],
[1478198376.389636, '018f', 8, ..., '3c', '00', '00'],
[1478198376.389864, '0260', 8, ..., '8e', '6d', '3a'],
...,
[1478201209.058471, '02a0', 8, ..., '02', 'bd', '00'],
[1478201209.058703, '0329', 8, ..., '20', '00', '14'],
[1478201209.058944, '0545', 8, ..., '00', '00', '00']],
dtype=object)

#regression model to predict data
data1_model = tf.keras.Sequential([
layers.Dense(11),
layers.Dense(2)
])

 data1_model.compile(loss = tf.keras.losses.MeanSquaredError(),
              optimizer = tf.keras.optimizers.Adam())

 data1_model.fit(data1_features, data1_labels, epochs=10)

I get:
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float).

A: As requested by uka here's an example using tf datasets
import tensorflow as tf
import numpy as np

def map_data(input_data):
    # input_data is a dictionary
    # do something with input_data, make sure you return as dictionary
    input_data['input']
    return input_data

# Here you can add many key, val as you want, mapping is up for you to decide
sample_data = {'inputs': np.random.randn(100, 1, 100)}
dataset = tf.data.Dataset.from_tensor_slices(sample_data)
dataset = dataset.map(map_data, num_parallel_calls=tf.data.AUTOTUNE)

# Grab an example from dataset
sample = next(iter(dataset))

# Use for model prediction
model.predict(dataset)


text:
Q: Redirect command to input of another in Python I would like to replicate this in python:
gvimdiff <(hg cat file.txt) file.txt

(hg cat file.txt outputs the most recently committed version of file.txt)
I know how to pipe the file to gvimdiff, but it won't accept another file:
$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"

Getting to the python part...
# hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])

When subprocess is called it merely passes <(hg cat file) onto gvimdiff as a filename.
So, is there any way to redirect a command as bash does?
For simplicity's sake just cat a file and redirect it to diff:
diff <(cat file.txt) file.txt

A: There is also the commands module:
import commands

status, output = commands.getstatusoutput("gvimdiff <(hg cat file.txt) file.txt")

There is also the popen set of functions, if you want to actually grok the data from a command as it is running.

A: This is actually an example in the docs:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

which means for you:
import subprocess
import sys

file = sys.argv[1]
p1 = Popen(["hg", "cat", file], stdout=PIPE)
p2 = Popen(["gvimdiff", "file.txt"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

This removes the use of the linux-specific /proc/self/fd bits, making it probably work on other unices like Solaris and the BSDs (including MacOS) and maybe even work on Windows.

A: It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable:
import subprocess
import sys

file = sys.argv[1]
p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)
p2 = subprocess.Popen([
    'gvimdiff',
    '/proc/self/fd/%s' % p1.stdout.fileno(),
    file])
p2.wait()

That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question:
file = sys.argv[1]
p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout)
diff_text = p2.communicate()[0]

A: It just dawned on me that you are probably looking for one of the popen functions.
from: http://docs.python.org/lib/module-popen2.html
popen3(cmd[, bufsize[, mode]])
    Executes cmd as a sub-process. Returns the file objects (child_stdout, child_stdin, child_stderr).
namaste,
Mark


text:
Q: google-api-php-client download zip from Git has only one directory src/Google Git : google-api-php-client
I only see
src/Google

how do I download the other directory ?
/example

/style

/tests

Thank you.

A: Install Git on your computer
Run
git clone https://github.com/google/google-api-php-client

You will have the whole directory structure.


text:
Q: Compiler C2491 error: solution requires loss of data? Using VS2017, I made a project from the auto-generated .cpp/.h files generated by this line (I am adding this to illustrate how I reached this point):
protoc -I=$SRC_DIR --cpp_out=dllexport_decl=MY_EXPORT_MACRO:$DST_DIR $SRC_DIR\gameinformation.proto

This line generated the files correctly and with no errors or warnings, my question does not refer to the generation of the files, rather their compilation to a .dll. I am specifically looking for a way to fix the error I encountered afterwards.
I have defined the macro as so in the .h file (I am adding this in case it is linked to the error I am dealing with):
#if BUILD_GAMEINFORMATION
#define MY_EXPORT_MACRO __declspec( dllexport )
#else
#pragma comment( 'lib', "gameinformation.lib" )
#define MY_EXPORT_MACRO __declspec( dllimport )
#endif

Now, a portion of the generated code (.cpp) is as follows:
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_gameinformation_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( protodesc_cold ) = {
    PROTOBUF_FIELD_OFFSET(::GameInfo::GameInformation, _has_bits_ ),
    PROTOBUF_FIELD_OFFSET(::GameInfo::GameInformation, _internal_metadata_ ),
    ~0u, // no _extensions_
    ~0u, // no _oneof_case_
    ~0u, // no _weak_field_map_
    PROTOBUF_FIELD_OFFSET(::GameInfo::GameInformation, gamemessage_ ),
    PROTOBUF_FIELD_OFFSET(::GameInfo::GameInformation, eacmessagebuffer_ ),
    PROTOBUF_FIELD_OFFSET(::GameInfo::GameInformation, eacmessagelength_ ),
    0,
    1,
    2,
};

This is the only definition/assignment of a value to this variable in the whole project.
When I try to compile my project, this portion of code throws this error:
Error   C2491   'TableStruct_gameinformation_2eproto::offsets': definition of dllimport static data member not allowed

This is the error I am trying to resolve, specifically.
I googled this, and according to the Microsoft docs, I need to get rid of the value assignment, ie, only retain this much:
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_gameinformation_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( protodesc_cold )

This does not seem like a robust solution to me. This file was automatically generated and I am quite sure those values are important.
If I have to take the Microsoft solution, does it matter if these values are lost? Is there somewhere else I can put them?
Or is there an alternative?


text:
Q: How do I use breakpoints in F# interactive? I've started researching some ideas in algorithms using VS2010 and F# interactive.
So, I've created a DebugScript.fsx, I write some code there and eventually send it to F#Int to test it.
At some some moment I need to catch a bug. But I can't place a breakpoint even in a simple for loop:
for i in stringarray do
    printfn "%s" i

When I press F9 to set a breakpoint, the VS show a red circle with a warning sign. The hint for it is "The breakpoint will not currently be hit".
Surely, I did open Debug menu -> Attach to process ... -> Fsi.exe previously
I tried placing Debugger.Break() inside the loop, but that's the only line where debugger stops, giving me no option to proceed with debugging lines inside the loop. I also don't have any local variables available :(
Maybe I'm missing something obvious?

A: As far as I know, there's no way to do this.  Instead, you'll want to use a .fs file and start debugging it in Visual Studio instead.

A: in VS2015 is now much more easy: in Tools->Option->F# tools -> F# interactive-> Debugging -> Enable script debugging = True
then reset your interactive session and when you want to debug press CTRL+ALT+D
and send command as usual
(or right click on the source file and choose "debug in interactive")

A: You cannot debug the code that is part of your scripts, but you can debug external code referenced in your scripts by attaching the debugger to the Fsi.exe process as you describe.
So if you really want to debug from the interactive window without wanting to write a console  program, you can create an fs file with the function to debug and:

*

*Attach the debugger

*Either

*

*reference the fs file with #load (*)

*compile the code as a library and reference the resulting DLL with #r

*Set a breakpoint

*Call the function from a script

(*) worked on my VS Ultimate installation, but I haven't been able to reproduce on another machine with VS Shell install

A: In addition to kvb's answer: One could say that F# Interactive is already a type of debugger. You can feed code line by line (or region by region) and see intermediate results. You can also inspect the value of bindings just by evaluating them in the F# Interactive console.

A: the interactive is for feeding it small pieces of code and evaluating intermediate results, think of it as micro-unit testing. i've had some success with using nunit with f#, it's no different than with c#, you decorate your testfixture and test cases in the same way and it will load up. i did have some issues with mixed-mode assemblies where nunit would barf, but overall, it's a better way imho to test a piece of code. also, i did not see a way to send a namespace to interactive, only modules.


text:
Q: Clicking a button doesn't work before unfocusing textarea I have a html textarea set to expand on focus, and right below that i have button for submitting whatever the users put into the textarea. When the textarea is expanded clicking the button does not fire the onclick event but instead it just puts the textarea out of focus causing it to get smaller Again. How can i make the onclick event fire on the first click?
The html looks  like this:

    <textarea placeholder="add a comment" id="txtTitle"></textarea>

    <button onclick="return addListItem()">Post</button>

The button doesn't have any styles attached but the textarea has the following:
#txtTitle {
width: 878px;
margin-bottom: 5px;
height: 30px;
transition: height 0.2s;
}

#txtTitle:focus {
height: 100px;
}

A: The issue is that when your textarea height moves so does the button. With a transitions of 0.2s by the time you've clicked where the button was originally the textarea has resized and moved the button away from where you originally clicked.
One way around this would to add some javascript to check if the input has a value, if it has a value then keep it the same height - if it's empty then resize it ( this is purely based on the idea that the text area requires a value to be submitted)

A: Here is a hack using required property to determine when the input has some value inside it.

function addListItem(){
  console.log('inside addListItem');
}
#txtTitle {
    width: 878px;
    margin-bottom: 5px;
    height: 30px;
    transition: height 0.2s;
}

#txtTitle:valid {
    height: 100px;
}
#txtTitle:focus {
    height: 100px;
}

    <textarea placeholder="add a comment" id="txtTitle" required></textarea>

    <button onclick="return addListItem()">Post</button>


text:
Q: Access to different directories I have recently moved to Ubuntu 12.04 and noticed that in some directories I can't even create a  directory or file (e.g:/var/lib). I know about the command chmod, but is it appropriate to use it in order to modify the access to these sort of directories?
For example I wanted to install something from the command line but gave me an error because it didn't have access and I thought that for security reasons I shouldn't change it.

A: No, you shouldn't mess with those directories: there's a good reason why you cannot modify them by default.
You use the Ubuntu Software Center or the command apt-get (in a terminal) to install new software on Ubuntu. While you have not learned the basics of Linux, it's not recommended you modify these directories by hand.
For example, to install the Chromium browser via the terminal you run:
sudo apt-get install chromium-browser

Or graphically,

*

*Open the Dash (tapping the Windows/Super key)

*Type software center and select Ubuntu Software Center

*Search for chromium web browser on the software center

*Install the search result (you can read a description of the app, too).


text:
Q: To Find the OverLapping dateTime I need to find the Overlapping dates and time using linq
example:
Scenario 1
i will define the date 1/4/2015 and 9/4/2015 and time span of 05:12 to 10:56
and i will define one more date range like 1/4/2015 to 2/4/2015 and time span of 11:45 to 15:67
and this should get added to DB as it is not lies in the 1st defined date.
if i add 1/4/2015 and 5/4/2015 and time span of 09:12 to 10:00 this should not allow to save in db.
Scenario 2:
And in the UI page i need to fetch these content which in between the date and time span with respect to server time.
Consider Current time is 12:00 now it has to pic 1/4/2015 to 2/4/2015 and time span of 11:45 to 15:67 date range record.
can any one help me out how to write the logic in linq.


text:
Q: django-filer raises django.db.utils.OperationalError: no such table: filer_file I am trying to implement django-filer into my models in Django Admin for extended file upload functionality. No matter how many times I have dropped my database and re-run migrations, I am getting a django.db.utils.OperationalError: no such table: filer_file error when I migrate the database.
I've read every post related to this on StackOverflow and none of them have helped me. I've tried faking migrations too and it starts to delete stale files, but then I get this error anyway.
When I try to access the model via Django Admin, I get
OperationalError: no such column: attorneydoc.attachment_id

Here is my models.py:
class AttorneyDoc(models.Model):
    attachment = FilerFileField(null=True, blank=True)

And here is admin.py:
@admin.register(AttorneyDoc)
class AttorneyDocAdmin(admin.ModelAdmin):
     ...

What do I need to do in order to resolve this?


text:
Q: Can anyone tell me why on one of my pages, the footer appears twice? http://adamshort.site50.net/#cv
On my portolio site I have used ajax to animate content load, but am wondering how I can make the transitions smoother as each page differes in length, and also why does the footer appear twice on the linked page above? This is the tutorial I followed:
http://net.tutsplus.com/tutorials/javascript-ajax/how-to-load-in-and-animate-content-with-jquery/

A: Looks like you're using a master page and have called the footer from both the master and child.


text:
Q: SAML authentication with Azure AD returns expired token I have a java spring security app that authenticates against Azure AD with SAML. With default settings, when the token is returned from MS back to my apps, the "notOnOrAfter" date is in the past, regardless when the user actually logged into their Microsoft account.
I have added forceAuthN=true parameter - this solved the issue of expired tokens, however at the expense of having to re-enter the username/password on every login request. Now the users are asking why they have to re-login in for my app when this works seamlessly for other apps they use that authenticate to Azure AD.
I tried playing around with different values for forceAuthN and passive - but still no luck.
Is there anything I can do (either in my application or in the setup of then enterprise application in Azure AD) to get seamless login working?

A: Normally this type of error occurs when your server time is different than AAD time. Please check the time set in your server and see if because of some recent patching or some activity it has changed.


text:
Q: Distance metric between two sample distributions (histograms) Context: I want to compare the sample probability distributions (PDFs) of two datasets (generated from a dynamical system). These datasets depend on a set of parameters, and I want a concise way to evaluate the distance between the two PDFs over several different parameter regimes, ideally by a single number. For a fixed parameter regiume, my two sample PDFs are given by the vectors $x$ and $y$, where $x_i$ is the relative frequency of samples which lie in the $i$th bin.
One method I've seen is the Kolmogorov-Smirnov statistic, which is the maximum vertical distance between the cumulative distribution functions of the two datasets. This would work for my purposes, but I'm starting to think that the chi-squared distance will be better (at the very least I had heard of it). It is given by: $d(x,y) = \frac{1}{2}\sum_i \frac{(x_i-y_i)^2}{x_i+y_i}$. But this doesn't seem to make sense in the case where $x_i=y_i=0$, which seems like a fairly reasonable occurrence.
Any recommendations?
Edit: My first instinct was just to take the $L^2$ ($l^2$) norm of the difference of the two PDFs (sample PDFs). But then I thought the $L^1$ norm might be more suitable for a probability distribution. After looking a little further, I stumbled on the K-S and Chi-Squared distances.

A: For particle distributions, you can, e.g., use the Wasserstein distance or OSPA (its counterpart for densities with different numbers of particles), see [1]. These two are based on the linear assignment problem (one-to-one assignment of the particles, if the numbers are equal) and therefore do not have a continuous gradient. If you don't want a a hard assignment of the particles, you can use the LCD distance from [2].
[1] J. R. Hoffman and R. P. S. Mahler. Multitarget Miss Distance and its Applications. In Proceedings of the Fifth International Conference on Information Fusion (Fusion 2002), July 2002.
[2] U. D. Hanebeck. Optimal Reduction of Multivariate Dirac Mixture Densities. at -Automatisierungstechnik, 63(4), 2015.

A: Total variation and Hellinger distance are two standard ways to measure this.
Kullback-Leibler divergence is another standard way, as would be general $f$-divergences.
The Earth-Mover's distance (also called the Wasserstein metric) is another option.
Bear in mind that your data gives an empirical cdf, so you can use any of the standard metrics for probability distributions notwithstanding the fact that you have a data sample in hand rather than a formula.
(Wiki has decent entries for all of these, which I may link to later.)

A: In the first place the answer depends on the nature of your data (e.g., numerical continuous, numerical discrete, nominal etc.). In each of these cases the empirical measures on the range of your data have to be compared by using the corresponding specific methods. I presume that your values are reals (since you evoke the KS distance). In this case the most natural for your problem topology on the space of measures is weak, and by no means the norm (total variation) one, as empirical measures you deal with will typically be pairwise singular.
The weak topolgy, indeed, can be metrized by the "ad hoc" Levy-Prohorov metric, however, the transportation metric (which also metrizes the weak topology) is by far more canonical and appropriate in this situation (it was evoked in R Hahn's answer under the names of Earth-Mover's distance and Wasserstein metric). For instance, the KS distance between two distinct $\delta$-measures is always 1, their total variation distance is 2, whereas the transportation distance between them is equal to the distance between the corresponding points, so that it correctly reflects their similarity. Another advantage is that, unlike the LP metric, the transportation metric on the line can be easily computed explicitly (by using its dual description in terms of Lipschitz functions).
The metrics used in statistics, generally speaking, serve a purpose which is different from yours, and do not make much sense in your situation, when comparing two mutually singular empirical distributions. Most of the statistical distances only make sense for equivalent measures (like the Kullback-Leibler deviation). Of course, you can always discretize your data by using bins, however you will lose information about the data by making it "coarser" (which is OK for typical statistical purposes, but is not necessarily so for you). I do not see any reason to do that if one can efficiently work with the original data by metrizing the weak topology.


text:
Q: what is meant by binary RBM? I understand what is RBM. I also accept that in binary RBM, states of RBM are binary. Is that also means the input datasets should be binary?

A: Typically the hidden units in an RBM are binary (though not always), so when people talk about things like binary RBMs or Gaussian RBMs without further qualification, I normally assume they are referring to the visible units only and the hidden units are binary.
That being said, even if the visible units are binary this doesn't people always use binary input data. For example, in all the MNIST examples out there, people will typically treat the greyscale value (between 0 and 1) as a probability and use that as input rather than thresholding or sampling to get actual binary data.


text:
Q: How can I query for documents where date is greater than a provided date? I have a collection of events that contain the date of the event stored in this format: YYYY-MM-DD. I want to query for all events that are greater than a provided date. This is what I have so far:
var eventSchema = mongoose.Schema({
    title : String,
    details : String,
    start_date : String,
    company: {
        type: String,
        ref: 'Company'
    }
});

eventSchema.methods.getUpcomingEvents = function(company_id, cb) {
var date = utils.dateToday(); // returns e.g., '2015-02-26'

return this.model('Event')
    .find({ company: company_id, start_date : {$gte: date} })
    .sort({start_date: 'asc'})
    .exec(function (err, data) {
        if (err) {
            console.log('ERROR = ' + err);
            cb(false, err);
        } else {
            cb(null, data);
        }
    })
};

The problem is that this query is return events that occur before the provided 'date'. What am I doing wrong?

A: start_date is String, make it Date if you want to perform date comparisons.
change the schema to something like this;
var eventSchema = mongoose.Schema({
    title : String,
    details : String,
    start_date : Date,
    company: {
        type: String,
        ref: 'Company'
    }
});


text:
Q: Appengine Query Offset - Not For Paging - EDIT With Memcache? I have an application where there are a list of items that my users will page through. I have handled paging through an index field (I needed it for other things eitherway so I figured why not).
My issue is that I want to implement a "goto" feature; where the user can skip directly to an item instead of paging through them using the provided navigation buttons (next and previous). For instance, they can enter 1000 in the "goto" box and have the 1000th item displayed. There is a disconnect between the nth item and its index - the index is guaranteed to be in order but is not guaranteed to be sequential so I can't just filter by the index. I thought about using the offset parameter of fetch, but I remember when I first started programming using appengine I was told not to use that due to performance issues.
Would offset be the best way to go here, or is there a better way? Also, are the costs associated with it simply that it would take longer to get the results, or will it count towards my datastore reads/small operations?
EDIT: I don't mean this in a bad way but in order to stave off the people who will tell me to use cursors... :-) I handle paging in a way that is more useful to me than if I would use cursors. Thank you in advance for your concern.  Additionally, I thought I'd spell out what I'm trying to do a bit in code:
q = Item.all()
#orders it by highest index first which is how client handles items
q = q.order('-index')
#count is determined automatically but is at least 25 and not greater than 300
q = q.fetch(limit=count, offset=i)

EDIT 2:  Based on the comments I decided to try storing my items in memcache, and do all of my filtering, ordering, offsets, etc... in memory. Item are grouped by Category which could hold up to 1500 items, and I store each Category in the memcache under its own key. The only issue I could think of is that each Item can worst-case scenario be 2kb in size. It's not so likely that a Category will have anywhere near 1500 Items in it, or that the Item will reach the worst-case scenario size, but if it does, it will exceed the 1mb memcache limit. Any suggestions on how to handle that? Also, there could be around 10 Categories; will this much storage in memcache cause it to flush more often? And finally, would it be worth it to use offset when I fetch the Entities or is memcache a better solution (Items will be accessed quite frequently, usually in small groups (25-30))?
EDIT 3:  I now have a sequential way of referencing items. Each item has an id which uniquely identifies it across categories, an index which is a way of ordering items within a category non-sequentially, and num which is sequential, but isn't implicit to the item (everytime I pull the items out of memcache I order it by index, and then iterate through the list of items, assigning each item a num given the current number of iterations) I guess that's a convoluted way of saying:
for i in range(0, len(items)):
    items[i]['num'] = i

EDIT 4:  Item Model:
class Item(db.Model):
   item_id = db.IntegerProperty()
   index = db.IntegerProperty()
   #I used StringProperty instead of ReferenceProperty because I'm a cheapo with memory
   category = db.StringProperty()

I kept num separate from the Model because of the cost associated with updating it to be sequential on adds and removes. Therefore, I use index to maintain the (nonsequential) order of the items, and everytime the list of dicts representing the items for a specific category is kicked out of the datastore, I run through them and add a sequential "num" to each item. num is really only for the client (read: browser) since my UI is entirely dynamic (all AJAX; no page reloads whatsoever) and I cache every item that is sent to the browser in javascript. Server-Side I don't necessarily need a sequential order for the items; there are certain functions on the client side that need it, and the server would do just fine with a non-sequential index.
The main crux of my question seems to have turned into whether I should keep this model, ie storing all items for a category in memcache, or going back to retrieving the items directly from the datastore. Items will be requested a lot (I don't have an exact amount or even an estimate of how many times per second, but it should be many items requested per second). I know that there's no way to precisely determine how long the items will be in memcache before getting kicked out, but can I assume it won't be happening every few minutes? Because if otherise, I feel like the best way to go is with memcache, but I could be missing something. Oh, and hopefully this will be the last edit before I steal all of SO's disk space ;)
EDIT 5 So much for no more edits... This is a chart of my calculations for time complexity when using memcache and the datastore or just the datastore (left out time complexity for the datastore because I'm not sure exactly what it is. It's too late to go read the BigTable paper again to try and figure it out so I'll just assume it's the same for operations on a hashtable). These are all best cases. For the memcache solution, the worst case you would need to add N datastore reads (since all the items in the category must be read into the memcache). This chart is leaving anything extra not having to do with storing or retrieving the data (ie sorts, filters) out of the equation for both memcache and datastore solutions. For the memcache only solution, num is not stored in the datastore. For the datastore only solution it is, which is why there is the extra cost associated with an Add or Remove (updating the num for each item).
n DS = number of DataStore operations
w = write
r = read
N = number of items in category (for Add and Remove this is the number before
    the operation is performed)
c = count of items to read
o = offset

+------------------------------------------------------------------------------+
|                  Memcache             |               Datastore              |
|------------------------------------------------------------------------------|
|       |                               |       |                              |
| Reads |           O(o + c)            | Reads |           c DS r             |
|-------+-------------------------------|-------+------------------------------|
|       |                               |       |                              |
|Reads w|           O(o + c)            |Reads w|          o + c DS r          |
|Offset |                               |Offset |                              |
|-------+-------------------------------|-------+------------------------------|
|       |                               |       |                              |
| Adds  |         1 DS w + O(N)         | Adds  |   1 + N DS w & N - 1 DS r    |
|-------+-------------------------------|-------+------------------------------|
|       |                               |       |                              |
|Removes|       1 DS rw + O(o + N)      |Removes|        N - o DS wr           |
|-------+-------------------------------|-------+------------------------------|
|       |                               |       |                              |
| Edits |         1 DS rw + O(o)        | Edits |          1 DS rw             |
|-------+-------------------------------|-------+------------------------------|

So the question is, does the worse time complexity for the memcache solution outweigh the potential more DS operations that come with the datastore solution, unless memcache eviction could cause more DS operations in the memcache solution than the datastore solution (because each time the items are evicted from mecache we have to do N DS r to repopulate the memcache). This is all assuming reads will happen much more frequently than writes which in this application will be the case once initial data loading is done.

A: Updated for Edit 4.
Your Item model looks reasonable, the biggest issue is how how to manage the sequential index. I'm still hesitent to rely on memcache in the way you describe, because cache eviction dramatically slows your read operations (which are common and user-facing) unless you have the datastore properly backing up the state of your data.
So, feel free to continue storing items in memcache. However, on inserts or deletes, make sure to update num in the datastore as well. (If you already have the entire set of Items in memcache, no read ops are required. Just update all the items in memcache and write them to the datastore simultaneously.)
The worst case scenario is still as I described it before your 4th edit. Inserting an element is 1 read + 1 write. Removing an element is N reads + N writes where N is the number of items in the category. Looking up an item is just 1 read. Each of these scenarios assume memcache is empty.
If you were using an offset, each insert would be 1 write. Removing an element would be 1 write. But, reading an element is N reads, where N is the sequential index of the item you are retrieving. If you're using memcache, but aren't backing up the value of num in the datastore, you'll also fall into this scenario.
In most cases, reads are far more common than writes, so maintaining num in the datastore is far more efficient.
An addendum:
Cloud SQL is another option if your data size isn't too large. SQL in general is much better at sequential queries like the one you are trying to do, at the cost of scaling poorly with large data sets.
The per use pricing is relatively cheap if you suspect you'll have minimal usage.

A: offset is the best way to do this in GAE, do not worry about quota, it will only count reads after offset. In another words: reading first N items consumes the same amount of quota as reading N items starting with some offset.


text:
Q: How can I send POST request with zip body using WebClient reactive web client How to POST a request with ZIP (compressed data) body using WebClient reactive web Client.
I created a zip in memory (bytearrayoutputstream) and want to send the zip data in a POST request body using WebClient reactive web Client. The REST API is a PdfReactor REST WebService. The Response is a binary data (pdf).
When I debug my Code I get the following error:
Pooled connection observed an error
org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/octet-stream' not supported for bodyType=java.io.ByteArrayInputStream
    at org.springframework.web.reactive.function.BodyInserters.unsupportedError(BodyInserters.java:297) ~[spring-webflux-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.reactive.function.BodyInserters.lambda$writeWithMessageWriters$9(BodyInserters.java:287) ~[spring-webflux-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at java.base/java.util.Optional.orElseGet(Optional.java:358) ~[na:na]
    at org.springframework.web.reactive.function.BodyInserters.writeWithMessageWriters(BodyInserters.java:287) ~[spring-webflux-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.reactive.function.BodyInserters.lambda$fromObject$1(BodyInserters.java:85) ~[spring-webflux-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.reactive.function.client.DefaultClientRequestBuilder$BodyInserterRequest.writeTo(DefaultClientRequestBuilder.java:257) ~[spring-webflux-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$exchange$1(ExchangeFunctions.java:103) ~[spring-webflux-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.http.client.reactive.ReactorClientHttpConnector.lambda$connect$2(ReactorClientHttpConnector.java:110) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at reactor.netty.http.client.HttpClientConnect$HttpClientHandler.requestWithBody(HttpClientConnect.java:528) ~[reactor-netty-0.8.2.RELEASE.jar:0.8.2.RELEASE]
    at reactor.netty.http.client.HttpClientConnect$HttpObserver.lambda$onStateChange$0(HttpClientConnect.java:396) [reactor-netty-0.8.2.RELEASE.jar:0.8.2.RELEASE]
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44) ~[reactor-core-3.2.2.RELEASE.jar:3.2.2.RELEASE]
    at reactor.core.publisher.MonoOnAssembly.subscribe(MonoOnAssembly.java:76) [reactor-core-3.2.2.RELEASE.jar:3.2.2.RELEASE]
    at reactor.netty.http.client.HttpClientConnect$HttpObserver.onStateChange(HttpClientConnect.java:397) [reactor-netty-0.8.2.RELEASE.jar:0.8.2.RELEASE]
    at reactor.netty.resources.PooledConnectionProvider$DisposableAcquire.onStateChange(PooledConnectionProvider.java:501) [reactor-netty-0.8.2.RELEASE.jar:0.8.2.RELEASE]
    at reactor.netty.resources.PooledConnectionProvider$DisposableAcquire.run(PooledConnectionProvider.java:531) [reactor-netty-0.8.2.RELEASE.jar:0.8.2.RELEASE]
    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) [netty-common-4.1.29.Final.jar:4.1.29.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404) [netty-common-4.1.29.Final.jar:4.1.29.Final]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:446) [netty-transport-4.1.29.Final.jar:4.1.29.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884) [netty-common-4.1.29.Final.jar:4.1.29.Final]
    at java.base/java.lang.Thread.run(Thread.java:844) [na:na]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
    |_  Mono.error ⇢ org.springframework.web.reactive.function.BodyInserters.lambda$writeWithMessageWriters$9(BodyInserters.java:287)
    |_  Mono.defer ⇢ reactor.netty.http.client.HttpClientConnect$HttpObserver.onStateChange(HttpClientConnect.java:396)

 configuration.json:
    {
    "document": "test.html",
    "addBookmarks": true,
    "addLinks": true
    }

 test.html:

    Hallo, hier ist ein Testdokument von .

map.put(template, tempBytesArray);
map.put(configuration, configByteArray);

        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            try (ZipOutputStream zos_ = new ZipOutputStream(bos)) {
                map.forEach((k, v) -> {
                    var zipentry = new ZipEntry(k);
                    try {
                        zos_.putNextEntry(zipentry);
                        zos_.write(v);
                        zos_.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
               byte[] b = bos.toByteArray();
               BodyInserter<Object, ReactiveHttpOutputMessage>     bodyInserter = BodyInserters.fromObject(bos);
               byteArray = pdfReactorClient
                        .post()
                        .uri(pdfReactorUrl + PDF_REACTOR_URL_SUFFIX)
                        .accept(MediaType.APPLICATION_OCTET_STREAM)
                        .body(BodyInserters.fromObject(bos)
                        .exchange()
                        .flatMap(response -> response.bodyToMono (ByteArrayResource.class))
                        .map(ByteArrayResource::getByteArray)
                        .block();
                zos_.close();
            } catch (Exception e) {
                // TODO: handle exception
            }

If I execute the following CURL on command line, I get the result pdf:
curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/zip" --data-binary @test.gzip "http://localhost:8080/service/rest/convert.pdf" > result.pdf.
Same should be translated in Java reactive Code. The request body (Zip/asset package) to the PDFReactor is the problem. Kindly help please...
PDFReactor

A:
Content-Type for PDF is MediaType.APPLICATION_PDF

change the content type as shown below
                    pdfReactorClient
                        .post()
                        .uri(pdfReactorUrl + PDF_REACTOR_URL_SUFFIX)
                        .accept(MediaType.APPLICATION_PDF)


text:
Q: $\lim_{n\rightarrow\infty}X1_{\{X>n\}}=0 \space\space\space\text{a.s.}$ $$\lim_{n\rightarrow\infty}X1_{\{X>n\}}=0 \space\space\space\text{a.s.}$$
This is a claim I need to use in part of a proof that involves the dominated convergence theorem.
Since it holds almost surely, I need to show that $P(\lim_{n\rightarrow\infty}X1_{X>n}=0)=1$
$$\forall\varepsilon > 0,\exists N \text{ s.t. }\forall n\ge N,P(|X1_{X>n}|\ge\varepsilon)=0$$
Rewriting,
$$P(|X1_{X>n}|\ge 2^{-n})=0$$
Do I have to use the Borel-Cantelli lemma to show this?

A: Recall that if $X$ is a random variable, then $X:\Omega\to\mathbb{R}$ . In particular, $X(\omega)$ is finite for every $\omega$. Now, fix an $\omega\in\Omega$ and pick a natural number $N(\omega)\in\mathbb{N}$ such that $N(\omega)\geq X(\omega)$, e.g. $N(\omega)=\lceil X(\omega)\rceil$ where $\lceil\cdot\rceil$ denotes the ceiling function. Then
$$
\mathbf{1}_{\{X>n\}}(\omega)=\mathbf{1}_{\{X(\omega)>n\}}=0,\quad \text{for all }n\geq N(\omega).
$$
In particular,
$$
X(\omega)\mathbf{1}_{\{X>n\}}(\omega)\to 0\quad\text{for }n\to\infty.
$$
Since $\omega$ was arbitrary, we conclude that
$$
\left\{\omega\;\Big|\;\lim_{n\to\infty} X(\omega)\mathbf{1}_{\{X>n\}}(\omega)=0\right\}=\Omega.
$$


text:
Q: Suppose $g(x) \in M$, the maximal ideal, then I want to show $\varphi(g) \in M^p$ Consider the finite field $k$ of characteristic $p$.
Consider the ring of Witt vectors $W(k)$ and its associated ring of power series $W(k)[[x]]$.
Define the Frobenius map $\varphi: W(k)[[x]] \to W(k)[[x]]$ by $\varphi(x)=x^p$.
That is, for $f(x)=\sum_{n \geq 0}a_nx^n \in W(k)[[x]]$, we have $$\varphi(f)=\sum_{n\geq 0}\varphi(a_n)x^{np}.$$
Note that $W(k)[[x]]$ is local ring and so it has unique maximal ideal $M=(p,x)$.

Suppose $g(x) \in M$, then I want to show $\varphi(g) \in M^p$.

If $g(x)=\sum_{n \geq 1}x^n$, then $\varphi(g)=x^p+x^{2p}+\cdots+x^{np}+\cdots \in M^p$. Here I have taken coefficients $a_n =1$ for all $n \geq 1$.
but if the coefficients $a_n$ are arbitrary, does $\varphi(g) \in M^p$ ?
If $r \in W(k)[[x]]$ and $s^p \in M^p$, then $rs^p \in M^p$, since $M^p$ is an ideal. So I think, $\varphi (g) \in M^p$, for any $g$.


text:
Q: Redirect all domains requests to 1 domain without `www.` on Divshot Kicking the tires on divshot.com with my middleman blog. I moved it over from Heroku, which uses rack to handle URL redirects/rewriting. I'm trying to duplicate some of that behavior on divshot, which uses HTML5 pushState (superstatic) instead.
I have multiple domains that I want to redirect to 1 domain, and I want to redirect all www. requests directly to http://example.com (rather than http://www.example.com).
Is there anyway to do this?

A: In order to redirect a user to another page, you can use:
if(window.location.host === 'www.example.com') {
    window.location = "http://example.com";
}

or for IE only:
window.navigate("http://www.example.com");

A: there are a few ways to tackle this:

*

*Your DNS provider may offer the ability to make these kinds of redirects without having to use Divshot to do it.

*If you have a high-performance app (i.e. a paid plan) we can manually configure our CDN to do those redirects for you.

*You can detect host in JS and redirect that way (less ideal, I'd go with 1 or w).


text:
Q: When is an event too rare for predictive modelling to be worthwhile? Background
I built a complaints management system for my company. It works fine. I'm interested in using the data it contains to do predictive modelling on complaints. We have ~40,000 customers of whom ~400 have complained.
Problem
I want to use our complaints data to model the probability that any given customer will complain. My concern is that a model giving each customer a probability of 0.000 for complaining would already be 99% accurate and thus hard to improve upon. Is it even possible to build a useful predictive model of the kind I describe trying to predict such a rare event with so little data?

A: That is why there are alternative measures than just accuracy.
Here, recall is probably what you are interested in. An in order to balance precision and recall, F1 is a popular mixture that takes both into account.
But in general, avoid trying to break down things into a single number.
It's a 1 dimensional result, and too much of a simplification. In practise, you will want to study errors in detail, to avoid a systematic error from happening.


text:
Q: How to filter data of object according to keys and make new array in react? I am working with the object like this:-
{
 0:
  buyAmount: 16.664328043964396
  buyAmountInUsd: 16.685266204095775
  date: {date: '2021-12-07'}
  sellAmount: {USD: 500, INR: 35000}
 1:
  buyAmount: 1004.7015442959262
  buyAmountInUsd: 1005.9639175379324
  date: {date: '2021-12-07'}
  sellAmount: {USD: 1000, INR: 79000}
......

and I am trying to make a new array using useState hook with this data but the problem I am facing is how to filter data and make an almost similar array with the same data.
e.g.:-
 0: [amount: 500, date: '2021-12-07'],
 1: [amount: 1000, date: '2021-12-07']

The problem I am facing is I don't know the approach how to get the data like amount = sellAmount.USD and date = date.date
I thought of trying the for...of But I don't think it will be a good hit.

A: You can do this with Array.map

const arr = [{
  buyAmount: 16.664328043964396,
  buyAmountInUsd: 16.685266204095775,
  date: {date: '2021-12-07'},
  sellAmount: {USD: 500, INR: 35000}
},{
  buyAmount: 1004.7015442959262,
  buyAmountInUsd: 1005.9639175379324,
  date: {date: '2021-12-07'},
  sellAmount: {USD: 1000, INR: 79000}
}]

console.log(
  arr.map(initialValue => {
    return {
      amount: initialValue.sellAmount.USD,
      date: initialValue.date.date
    }
  })
)

A: The better idea would be the having an array of objects rather than array of array elements
let result = yourArray.map(each => ({ amount: each.sellAmount.USD, date: each.date.date }))

A: This is not related to ReactJS - just native Javascript object handling.
If your original data has the shape of an Object you can convert it into an Array like so:
const objData = { 0: {...}, 1: {...} };
const arrData = Object.entries(objData); // [[0, {...}], [1, {...}]];

From there, you can filter/map/sort your array with native array methods:
const reshapedArray = arrData.map(([key, value]) => {
  return {
    amount: value.sellAmount.USD,
    date: value.date.date,
  };
});

Then sort:
const sortedArray = reshapedArray.sort((prev, next) => {
  return prev.amount - next.amount; // sort by amount ascending
});

You can of could chain these array functions and shorten the syntax a bit:
Object.entries(objData)
  .map(([_, { sellAmount, date: { date } }]) => ({ amount: sellAmount.USD, date }))
  .sort((a, b) => a.amount - b.amount);


text:
Q: Javascript replace() function not working in jQuery UI Dialog I've been using javascript replace() with to limit input to digits and a single decimal like this:
<input id="dialog-input" type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" \>

This works perfectly fine and if I can get dialog content from the existing input like this:
<input id="dialog-input" type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" \>
dialog = $( '#dialog-input' ).dialog({ });

However, if rendered the input directly as a jQuery object for the dialog like this, the second regex replace seems to fail getting the capturing group and something happens where it will only allow a single character in the input:
dialog = $( '<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, \'\').replace(/(\..*)\./g, \'$1\');" \>' ).dialog({ });

Why does this work in one case but fail in the other?  I have a hunch that some part of my regex needs to be escaped but I've tried a multitude of variations and nothing seems to work.

A: Double escape your period in the second regex:
'...replace(/(\\..*)\\./g, \'$1\');" \>'

I would just avoid working with strings:
$('<input type="text">').on('input', function() {
    this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
}).appendTo('body').dialog();


text:
Q: How to find average of variable (x value) aggregated by subset (certain days) of another variable (year) in R? I would like to see if it is possible to use the aggregate function to find the mean for values from Sep. to Oct. of multiple years. I would like to compare the average rainfall in the 2021-9-1 to 2021-10-31 range to the same range of previous years without having to write out a mean calculation for each one.
DANHP has 12 variables, of which I am using:

*

*value (rainfall in inches)

*DATE (YYYY-MM-DD in date format)

*JULIAN (the Julian day 1-365)

*Month (1-12, extracted from DATE)

*Year (2012-2021, extracted from DATE)
Here is the code I am working with:

aggregate(DANHP$value, list(DANHP$Year), subset(filter(DANHP$JULIAN >= 244 & DANHP$JULIAN <= 304)),
          FUN=mean)

Error in UseMethod("filter") :
  no applicable method for 'filter' applied to an object of class "logical"

It doesn't look like I can define a subset for the command by filtering, so I would like to know if there is another method.
Ideally, the output would be similar to the below output, but this output calculates the means for all days in each year. I would like to see the means for the same subset of each year: Sep. 1 - Oct. 31 (Julian days 244-304).
aggregate(DANHP$value, list(DANHP$Year), FUN=mean)
   Group.1         x
1     2012 0.1455956
2     2013 0.1586712
3     2014 0.1376849
4     2015 0.1338904
5     2016 0.1476230
6     2017 0.2518082
7     2018 0.1467507
8     2019 0.1400603
9     2020 0.1759290
10    2021 0.1520301
11    2022 0.0000000

A: There is a syntax error in the subset code, where a dplyr::filter (may be used).  Instead, the subset itself can use subset argument inside
aggregate(value ~ Year, subset(DANHP, JULIAN >= 244 & JULIAN <=304), mean)


text:
Q: ASP.NET MVC Generic Html and Url helpers Where has the generic html controls and url helpers gone ?
You know the ones that looked something like this:
this.TextBox<MyInputModel>(model=>model.Name)

this.ActionLink<MyController>(controller=>controller.Index)

A: These are (and have always been, I think) in the MvcFutures assembly.  You need to update to the newest MvcFutures when you upgrade to the released version.

A: They are extensions located in the assembly Micosoft.Web.MVC.
You have to add this assembly to your project and add a reference to it in the web.config file.
You should consult the following answer for more details: Where to get Microsoft.Web.Mvc.dll

A: They should appear on a generic view. i.e.
ViewPage<MyInputModel>

or generic user control
ViewUserControl<MyInputModel>

but that should read
html.TextBox(model=>model.Name)

Beware that is untested code.


text:
Q: Why does uniq drop korean string? I have a CSV file containing 220k names that I want to batch import into a graph database. The batch importer imposes the restriction that each node must occur only once so I want to remove duplicates using sort and uniq like this:
sort all-authors.csv | uniq > unique-authors.csv

Upon investigating missing nodes I observed this odd behavior:
$ grep 이선동 unique-authors.csv
$ grep 이선동 all-authors.csv
"이선동"
$

The name is passed on by sort but then lost by uniq:
$ sort all-authors.csv | grep 이선동
"이선동"
$ sort all-authors.csv | uniq | grep 이선동
$

It works with other non-English names, e.g.:
$ grep '잔쎈 우베' *csv
all-authors.csv:"잔쎈 우베"
unique-authors.csv:"잔쎈 우베"
$

What is happening here?
edit: added output of locale
 $ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8
$

edit: added output of attempt with single-line file and sort -u
answering pLumo's comment regarding a file only containing the affected string:
$ grep 이선동 all-authors.csv > single-author.csv
$ sort single-author.csv | uniq
"이선동"
$

answering rush's comment regarding sort -u:
$ sort -u all-authors.csv | grep 이선동

I do not have any aliases set for uniq, I verified using alias | grep uniq, which returns nothing.

A: Based on the answer from:
https://stackoverflow.com/questions/5982531/behaviour-of-gnu-sort-command-with-non-letter-ascii-characters-such-as-dot-or
This did the trick for me:
Without LC_COLLATE=C
sort test | uniq
이선동

With LC_COLLATE=C
LC_COLLATE=C sort test | LC_COLLATE=C uniq
동선이
동이선
선동이
선이동
이동선
이선동


text:
Q: Detect 32 or 64 bits machine (Understanding `32 << (^uint(0) >> 63)` ) It is said that the 32 << (^uint(0) >> 63) expression can be used to detect whether the machine is 32 or 64 bits.
How so?
UPDATE:
The question was closed because of
How can I determine the size of words in bits (32 or 64) on the architecture?
however, that answer has two problems,

*

*on a 32-bit architecture, the result of the first step yields 0, and no matter how you shift it, the result of the second step will always be 0 (the given answer is wrong).

*Moreover, as per The Go Programming Language, the constant are compiled at the compile time, so that const BitsPerWord will be a fixed value, the same as runtime.GOARCH which gives the arch of the compiled program, and cannot be used to detect the OS architecture no matter which one it runs on.

UPDATE:
Found that the most reliable and portable way is to check with this under Linux:
$ getconf LONG_BIT
64

It won't depend on the language implementation of any programming language, and it can be used in shell scripts too.