text:
Q: AngularJS, Angular-Material - HTML Not rendering despite object present on $scope I have searched extensively for a solution to this problem and can't seem to find one. Any help here would be greatly appreciated.
The Basics:

*

*Utilizing angular-material tabs

*Upon selection of an item from a dropdown, a call is made to a firebase database and returns a response, which is put into an array on the $scope.

*HTML is utilizing ng-repeat on this response object.

The Problem:

*

*Despite the response object being present on the scope, the html does not render anything until the user "clicks" another button on the view - any button at all. In fact, the user has to simply touch/click something on the screen and then the results render.

*If user makes a call to the database to get artists in a certain medium (i.e. painting), but does not click anything on the screen, no results will show at all, despite response object being present in $scope.
I am stumped.
HTML:
<md-tabs md-dynamic-height md-border-bottom md-center-tabs><md-tab label="Artists">
    <md-content id="tab_background" class="md-padding">

                <md-card>

                    <md-card-header>

                            <md-card-header-text>
                                {{artist.name}}{{artist.name_last}}
                                {{artist.selectedSubmedium[0]}}
                                {{artist.neighborhood}}
                            </md-card-header-text>

                    </md-card-header>
                    <md-card-actions layout="row" layout-align="end center">
                    </md-card-actions>
                </md-card>

    </md-content>
    </md-tab>
        <md-tab label="Events">
    </md-tab>
</md-tabs>

Javascript:
  $scope.getArtists = function(medium){
    //resetting results array
    $scope.firstArray = [];
    $scope.results = [];
    var Medium = medium.name;
    firebase.database().ref('/Artists/' + Medium).once('value').then(function(snapshot){
      console.log(snapshot.val());
      var obj = snapshot.val();
      for (var key in obj) {
        var innerObj = obj[key]
        innerObj.uid = key;
        console.log(innerObj);
        $scope.firstArray.push(innerObj);
      }
      $scope.results = $scope.firstArray;
      $scope.runSpinner();
    })
  }

A: I used $scope.apply() and it solved it.


text:
Q: cut rows between 2 values and pasting it on a new sheet I am new and I've been trying to work on this macro for a few days now. What I am trying to do is to search thru column A for the word "REPORT"; then cut and paste all rows in between "report" (including blanks rows) to a new sheet. It kinda works but it would not stop because it would continue to look for the "REPORT". Here's how my data looks like. Thanks.
Table:
         A
  ---------------
 1| REPORT
 2| SOLICITOR_ID
 3| ISSUER:
 4| CUSIP:
 5| RECORD_DATE:
 6| TOTAL
 7|
 8|
 9|
10|
11|
12| REPORT
13| SOLICITOR_ID
14| ISSUER:
15| CUSIP:
16| RECORD_DATE:
17|
18|
19|
20|
21|
22| REPORT
23| SOLICITOR_ID
24| ISSUER:
25| CUSIP:
26| RECORD_DATE:
27|
28|

Code:
Sub BRGFileCleanup()

Dim rownum As Long
Dim colnum As Long
Dim startrow As Long
Dim endrow As Long
Dim lastrow As Long

Do
    rownum = 1
    colnum = 1
    lastrow = Worksheets("BRG_FILE").Range("A65536").End(xlUp).Row

    With ActiveWorkbook.Worksheets("BRG_FILE").Range("A1:A" & lastrow)

    For rownum = 1 To lastrow

Do
    If .Cells(rownum, 1).Value = "REPORT" Then
       startrow = rownum

    End If

    rownum = rownum + 1

 If (rownum > lastrow) Then Exit For

 Loop Until .Cells(rownum, 1).Value = "REPORT"
    endrow = rownum - 1
    rownum = rownum + 1

    Worksheets("BRG_FILE").Range(startrow & ":" & endrow).Cut

    Sheets.Add After:=Sheets(Sheets.Count)

    Range("A1").Select
    ActiveSheet.Paste
    Worksheets("BRG_FILE").Range(startrow & ":" & endrow).Delete

 Next rownum
 End With

Loop Until ActiveSheet.Range("A1").Value = ""

End Sub

A: just be sure you have row 1 as a header row and then you can exploit AutoFilter() and SpecialCells() methods and Areas() property of Range object like follows:
Option Explicit

Sub main()
    Dim iArea As Long
    Dim filteredRng As Range

    With Worksheets("BRG_FILE")
        With .Range("A1", .Cells(.Rows.count, 1).End(xlUp).Offset(1))
            .Cells(.Rows.count) = "REPORT"
            .AutoFilter field:=1, Criteria1:="REPORT"
            If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then
                Set filteredRng = Intersect(.Parent.UsedRange, .Resize(.Rows.count - 1).Offset(1).SpecialCells(xlCellTypeVisible).EntireRow)
            End If
            .Cells(.Rows.count).ClearContents
        End With
        .AutoFilterMode = False
    End With

    If Not filteredRng Is Nothing Then
        With filteredRng
            For iArea = 1 To .Areas.count - 1
                Sheets.Add After:=Sheets(Sheets.count)
                .Parent.Range(.Areas(iArea), .Areas(iArea + 1).Offset(-1)).Cut
                ActiveSheet.Paste
            Next
        End With
    End If
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: UNNEST in bigquery isn't working, getting "Cannot access field on a value of type ARRAY" Noob to bigquery, but I need to query a simply project I have from crashlytics that dumps into bigquery.
In a perfect world... this query would work as it makes sense to me, but exceptions is a more complex type which requires unnesting?
SELECT exceptions.exception_message
FROM `rollertoaster-235.firebase_crashlytics.com_rollertoaster_app_ANDROID`
WHERE STARTS_WITH(issue_title, 'MyCrashFile.java') LIMIT 1000

The exceptions are defined in the table schema as such:

All I want to do is get a resulting list of exception_messages, but it does not like the UNNEST. Reading some docs and other SO questions... it looks like I need to "UNNEST". But I get a similar error.
SELECT asdf
FROM `rollertoaster-235.firebase_crashlytics.com_rollertoaster_app_ANDROID`,
UNNEST(exceptions.exception_message) AS asdf
WHERE STARTS_WITH(issue_title, 'MyCrashFile.java') LIMIT 1000

Error:
Cannot access field exception_message on a value with type ARRAY<STRUCT<type STRING, exception_message STRING, nested BOOL, ...>> at

A: Looks like you're trying to unnest a field within the struct array, not the array itself.  Try something like this, which unnests the array and projects the field of the unnested record/struct:
SELECT ex.exception_message
FROM `your.table`,
UNNEST(exceptions) as ex
WHERE STARTS_WITH(issue_title, 'MyCrashFile.java') LIMIT 1000


text:
Q: Serial port read result contains response but also the command I give, how to solve this? I am writing a GUI for Modem communication tool, able to receive AT command and also return the result from modem after execution in modem. I use serial port datareceived event to handle the received data but it contains not only the response from the modem but also the AT command I give. Now I think it is because:
1) send at command from my GUI
2) Modem receive it, then trigger datareceived events
3) Modem runs the command, the reply also trigger datareceived events.
4) the received data then contains both my given command and also the reply
For example:

Input: AT+COPS=0
Output:AT+COPS=0OK (OK is modem response)
Input: AT
Output:ATOK (OK is modem response)

I could not find a solution in MSDN. Are there two different buffers in Modem?
How to solve this?
Here is my code:
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{

    if (e.EventType != SerialData.Chars)
    {
        return;
    }
    try
    {
        System.Threading.Thread.Sleep(1000);
        string indata = atPort.ReadExisting();
        string status = timeStamp.ToShortDateString() + " " + timeStamp.ToUniversalTime() + "   " + "Read from Modem: " + indata;
        this.Invoke(new MethodInvoker(delegate () { this.listBox_CommandOutput.Items.Add(status); }));
    }
    catch (Exception ex)
    {

    }
}

private void executeCommandLine()
{
    if (this.textBox_CommandLine.Text != "")
    {
        try
        {
            atPort.DiscardInBuffer();
            atPort.DiscardOutBuffer();
            this.atPort.Write(this.textBox_CommandLine.Text.ToString()+"\\r");
            this.listBox_CommandOutput.Items.Add(timeStamp.ToShortDateString() + " " + timeStamp.ToUniversalTime() + "   " + "Write to Modem: " + this.textBox_CommandLine.Text.ToString());

        }
        catch (Exception exc)
        {
            this.listBox_CommandOutput.Items.Add(exc.ToString());
        }
    }
    else MessageBox.Show("Command can't be void.", "COM talk", MessageBoxButtons.OK);

}

A: The problem is not in your code. Some modem by default use the echo mode by default: they echo every character sent to them to the sender (so you can use them like a terminal).
You can disable the echo mode using the AT command:
ATE0


text:
Q: custom order of products in woocommerce category page I have a woocommerce store and want to make a custom order of my products.
Users access directly category pages, no shop archive page.
Do you have any good solutions for making a custom order here ?
I Tried using plugins and also giving those products a number... but all did not work.
kind regards

A: You can assign a number to each woocommerce product in wp-admin.When you edit or add product than you will see a menu order option just input a numeric number.


text:
Q: Issues while building apk using android platforn in ubuntu 14.0.4 Good morning. I'm newer in ionic and face this issues since 3 day.
node -v: v5.8.0
npm -v: 3.7.3
cordova -v: 6.4.0
ionic -v: 2.2.1
java -version:  openjdk version "1.8.0_45-internal"
                     OpenJDK Runtime Environment (build 1.8.0_45-internal-b14)
                     OpenJDK Server VM (build 25.45-b02, mixed mode)
when I try : >ionic build android
I have this issues
:CordovaLib:processDebugResources
~/android-sdk/build-tools/25.0.0/aapt: 3: /home/donvex/android-sdk/build-tools/25.0.0/aapt: Syntax error: Unterminated quoted string
FAILED
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':CordovaLib:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 12.544 secs
Error: /opt/lampp/htdocs/www/pneupur_app//platforms/android/gradlew: Command failed with exit code 1 Error output:
~/android-sdk/build-tools/25.0.0/aapt: 3: ~/android-sdk/build-tools/25.0.0/aapt: Syntax error: Unterminated quoted string
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':CordovaLib:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Some body help me :worried:

A: Try installing 32bit dependencies
sudo apt-get install -y lib32gcc1 libc6-i386 lib32z1 lib32stdc++6


text:
Q: what's wrong in my sql with a simple self-join query? I have a table comment,table column as the follow:
  `comment_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `nick_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  `comment_content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT 'content',
  `parent_id` bigint(20) NULL DEFAULT NULL COMMENT 'parentCommentId',
  `active_flag` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'activeFlag',

I have an index on parent_id column, but when I select data using left join on parent_id, the index does not work in. Is there anything wrong?
The Sql as the follow:
select * from comment p left join comment sub on p.comment_id = sub.parent_id

The explain result:
mysql> EXPLAIN select  * from comment p left join comment sub on p.comment_id = sub.parent_id;
+----+-------------+-------+------------+------+------------------+------+---------+------+--------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys    | key  | key_len | ref  | rows   | filtered | Extra                                              |
+----+-------------+-------+------------+------+------------------+------+---------+------+--------+----------+----------------------------------------------------+
|  1 | SIMPLE      | p     | NULL       | ALL  | NULL             | NULL | NULL    | NULL | 126717 |   100.00 | NULL                                               |
|  1 | SIMPLE      | sub   | NULL       | ALL  | comment_n2 | NULL | NULL    | NULL | 126717 |   100.00 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+------------+------+------------------+------+---------+------+--------+----------+----------------------------------------------------+
2 rows in set (0.03 sec)

UPDATE:
CREATE TABLE `comment`  (
  `comment_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `catalog_version_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '',
  `nick_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  `login_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  `user_id` bigint(20) NOT NULL COMMENT '',
  `operated_id` bigint(20) NULL DEFAULT NULL COMMENT '',
  `comment_type_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '',
  `level_path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '',
  `comment_content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '本',
  `average_comment_score` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '',
  `describe_score` int(11) NULL DEFAULT NULL COMMENT '',
  `logistics_score` int(11) NULL DEFAULT NULL COMMENT '',
  `service_score` int(11) NULL DEFAULT NULL COMMENT '',
  `comment_status_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '',
  `platform_order_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '',
  `platform_order_entry_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '',
  `parent_id` bigint(20) NULL DEFAULT NULL COMMENT '',
  `tenant_id` bigint(20) NOT NULL DEFAULT 0,
  `object_version_number` bigint(20) NOT NULL DEFAULT 1,
  `creation_date` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created_by` bigint(20) NOT NULL DEFAULT -1,
  `last_updated_by` bigint(20) NOT NULL DEFAULT 1,
  `last_update_date` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `reply_flag` tinyint(4) NULL DEFAULT NULL COMMENT '',
  `active_flag` tinyint(4) NOT NULL DEFAULT 0 COMMENT '',
  `display_status` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  `operated_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  `platform_product_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '',
  `platform_sku_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '',
  `sku_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '',
  PRIMARY KEY (`comment_id`) USING BTREE,
  UNIQUE INDEX `comment_u1`(`comment_id`, `tenant_id`) USING BTREE,
  INDEX `comment_n1`(`platform_product_code`, `platform_sku_code`, `tenant_id`) USING BTREE,
  INDEX `comment_n2`(`parent_id`, `tenant_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 128596 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin COMMENT = '' ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

And there are 126717 records.

A: There are several possible reasons what an index on parent_id would not be getting used in your query.  One reason is that your comment table is fairly small, in which case MySQL might eschew the use of any index and decide to just scan the table.
Another reason for the index on parent_id not being used is that your query is doing a SELECT *.  That is, it is selecting all columns from both tables in the query (which happens to be the same table).  Your index covers the join, but not the select.  You could consider an index which covers all columns:
CREATE INDEX idx_new ON comment (parent_id, comment_id, comment_content,
                                 nick_name, active_flag);

This index would cover the entire self join to the same table.


text:
Q: Relation between independent increments and Markov property Independent  increments  and Markov property.do not imply each other. I was wondering

*

*if being one makes a process
closer to being the other?

*if there are cases where one implies
the other?

Thanks and regards!

A: Independent increments do imply Markov property.
To see this, assume that $(X_n)_{n\ge0}$ has independent increments, that is, $X_0=0$ and $X_n=Y_1+\cdots+Y_n$ for every $n\ge1$, where $(Y_n)_{n\ge1}$ is a sequence of independent random variables. The filtration of $(X_n)_{n\ge0}$ is $(\mathcal{F}^X_n)_{n\ge0}$ with $\mathcal{F}^X_n=\sigma(X_k;0\le k\le n)$. Note that
$$
\mathcal{F}^X_n=\sigma(Y_k;1\le k\le n),
$$
hence $X_{n+1}=X_n+Y_{n+1}$ where $X_n$ is $\mathcal{F}^X_n$ measurable and $Y_{n+1}$ is independent on $\mathcal{F}^X_n$. This shows that the conditional distribution of $X_{n+1}$ conditionally on $\mathcal{F}^X_n$ is
$$
\mathbb{P}(X_{n+1}\in\mathrm{d}y|\mathcal{F}^X_n)=Q_n(X_n,\mathrm{d}y),
\quad
\mbox{where}\quad
Q_n(x,\mathrm{d}y)=\mathbb{P}(x+Y_{n+1}\in\mathrm{d}y).
$$
Hence $(X_n)_{n\ge0}$ is a Markov chain with transition kernels $(Q_n)_{n\ge0}$.
On the other hand, Markov property does not imply independent increments.


text:
Q: Fixed points of map $h$ in compact riemann surface I have the following problem:
Let $h : Σ → Σ$ be a conformal self-map, different from the identity, of a
compact Riemann surface $Σ$ of genus $p$. Show that $h$ has at most $2p+2$
fixed points.
The problem has a suggestion. Hint: Consider a meromorphic function $f : Σ → S^2$ with
a single pole of order $≤ p + 1$ at some $z_0$ which is not a fixed point of
$h$, and study $f(z) − f(h(z))$.
So let's go to what I thought ...
By theorem (see for example Jost p. 239), exists a non-constant meromorphic function $f : Σ → S^2$ with only one pole, of order $≤ p + 1$. Then for $z_0 \in Σ $ such that $h(z_0) \neq z_0$, we consider $f$ like mentioned with only one pole of order $≤ p + 1$ at $z_0$. Let $g(z):= f(z)-f(h(z))$.
Now i need study the set zeros of $g$ and conclude that $≤ 2p + 2$.
My difficults is exactly here!
After that i conclude that $h$ has at most $2p+2$
fixed points.
So that's it ... any help to solve my difficulty is welcome!Thanks!


text:
Q: How do you make a Function in Pseudocode So I have given myself a task to make a Pseudocode BubbleSort Algorithm (In accending order) Function to use in a bigger program, I am quite new to Pseudocode so I would love the support. I have the Python Code:
    # Python: BubbleSort
def bubblesort(myList):
    for i in range(0, len(myList) - 1):
        for j in range(0, len(myList) - 1 - i):
            if myList[j] < myList[j+1]:
                myList[j], myList[j+1] = myList[j+1], myList[j]
                return myList

But how would I go about making this into Pseudocode?

A: Pseudocode has no defined standard, as it is simply a method of writing a human-readable representation of program code. Functions can be defined however you wish. A few examples are:

*

*def FunctionName(), as is the Python syntax for defining functions;

*C-style <type> function name();

*etc.

However you define functions in the end is up to you, and whether you choose to follow the syntax of the original source's language or not is only your decision to make.
More examples of pseudocode function declarations can be found here (en.wikipedia.org, "Pseudocode", section "Syntax").


text:
Q: How to show builtin Zoom Controlls in webview in Android may be duplicate to this [Always show zoom controls in WebView1 but I just want to display the zoom controls not necessary always.
Basically i have a list View and i fill this with the multiple webview in getVIew Method.
Here is the code
    public View getView(final int position, View convertView,
            ViewGroup parent) {

        View vi = convertView;
        if (convertView == null) {
            vi = inflater.inflate(R.layout.book_reader_list_style, parent,
                    false);
            holder = new ViewHolder();

            holder.webView = (WebView) vi.findViewById(R.id.webView1);
            WebSettings webSettings = holder.webView.getSettings();
            holder.webView.setVerticalScrollBarEnabled(false);
            holder.webView.setHorizontalScrollBarEnabled(false);
            holder.webView.setVisibility(View.VISIBLE);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setUseWideViewPort(false);

            webSettings.setBuiltInZoomControls(true);
            webSettings.setSupportZoom(true);
            webSettings.setLoadWithOverviewMode(true);

            holder.webView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i("Webview", "Clicked");

                }
            });

            vi.setTag(holder);
        } else {

            holder = (ViewHolder) vi.getTag();
        }

        holder.webView
                .loadDataWithBaseURL(
                        null,
                        "<!DOCTYPE html>",
                        "text/html", "UTF-8", null);

        return vi;

    }
}

class ViewHolder {
    WebView webView;

}

and here is my XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<WebView
    android:id="@+id/webView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:scrollbars="none" />

listview is filled with webviews nicely but problem is that i want the Zoom button controls.

*

*Please have a look on my XML and Java Code. What i m doing wrong?

I have tried the
webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);

but still not working

A: in oncreate() method
webView.getSettings().setBuiltInZoomControls(true);

and always search before asking.it reduces redundancy & saves your time.
once check this mate.
zoom controls for webview

A: Make  android:clickable="false" to  android:clickable="true". In your webView XML. You can remove focusable or make them true also


text:
Q: Relationship $v_A^2-v_B^2=2a_t\Delta s $ for motion with constant tangential acceleration I can not understand a relationship in the general motion in the plane. I am considering a point, which follows a curved trajectory. Indicate A and B two different position of the trajectory and $v_A$ and $v_B$ the modulus of the speed in those positions. Knowing that $a_t$ (the tangential acceleration which  is constant) and calling $\Delta s$ the distance between A e B.
Why
$$v_A^2-v_B^2=2a_t\Delta s $$

A: This equation holds whenever there is constant acceleration. Here are 2 ways of deriving that equation, which I hope help you understand it.
Energy conservation
The change in kinetic energy must be equal to the work done on the particle.
$$
\frac{1}{2}m v_A^2 - \frac{1}{2}mv_B^2 = \int F\cdot dx
$$
For a constant force and mass $\int F\cdot dx = F (x_A - x_A) \cos(\theta) = ma \cos(\theta) \Delta s$. Further let $a_t = a \cos(\theta)$ and we get
$$
\frac{1}{2}m v_A^2 - \frac{1}{2}mv_B^2 = ma_t\Delta s
$$
Multiply both sides by $2$ and divide by $m$
$$
v_A^2 - v_B^2 = 2a_t\Delta s
$$
Constant acceleration
We can derive the same equation a different way by assuming the acceleration is constant.
$$
a = constant \\
v = \int a dt = a \int dt = at + c
$$
Consider $t = 0$ and see that $v(t=0) = c$, so $c$ is the initial velocity $u$.
$$
x = \int v dt = \int(u + at)dt = u \int dt + a\int t dt = ut + \frac{1}{2}at^2 + c_2
$$
Again consider $t = 0$ and see that $x(t=0) = c_2$, so $c_2$ is the initial position $x_0$. Let's rewrite $x - x_0$ as $\Delta s$
$$
\Delta s = ut + \frac{1}{2}at^2
$$
Now we'll eliminate the $t$ dependence by plugging in $t = \frac{v-u}{a}$
$$
\Delta s = u\frac{v-u}{a} + \frac{1}{2}a(\frac{v-u}{a})^2 = (\frac{v-u}{2a}) (2u + v- u )  = (\frac{v-u}{2a}) (v + u) = \frac{1}{2a} (v^2 - u^2)     \\
v^2 = u^2 + 2a\Delta s
$$


text:
Q: Design approach for Multiple choice quiz app with Multiple right answers Hi I'm trying to implement a django quiz app. But can't figure out the approach i should use when trying to create a question with multiple right answers. ie, users should be able to mark multiple choices as the right answers.
This is what I've come up with so far.
class Question(models.Model):
    question = models.CharField(...)

class Choice(models.Model):
    question = models.ForeignKey("Question")
    choice = modelsCharField("Choice", max_length=50)

class Answer(models.Model):
    question = models.ForeignKey("Question")
    answers = models.ForeignKey("Choice")

Please guide me how to implement it the right way.

A: You don't need another model for answer. Just modify Choice model like this.
class Choice(models.Model):
    question = models.ForeignKey('Question')
    choice = models.CharField(...)
    is_answer = models.BooleanField(default=False) # or True.

And then, you can make some useful methods in Question.
class Question(models.Model):
    question = models.CharField(...)

    def check_answer(self, choice):
        return self.choice_set.filter(id=choice.id, is_answer=True).exists()

    def get_answers(self):
        return self.choice_set.filter(is_answer=True)

I recommend change your field name such as question in Question, choice in Choice. This can cause confusion.


text:
Q: C++ program need lines words and characters count I have an assignment where i need to count lines, words and characters from a file. I'm having a problem counting the right amount of characters and words since if it gets doubled space it counts like a character and a word.
the output should be
Example
lines  words  characters  filename

 3     5        29        testfile

Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;

int main(int argc, const char * argv[]) {
string lines, words, chars, file1, file2;

ifstream infile;
ofstream outfile;
char c;

int countLines = 0;
int countChars = 0;
int countWords = 0;
cout<< "Enter the file name" << endl;
cin >> file1;
infile.open(file1.c_str());

while(!infile.eof())
{
    if(infile.peek() == 1)
        break;
    c = infile.get();
    if(c != '\n')
       countChars++;
    else
        countLines++;

    if(c == ' '|| c =='\n')
        countWords++;

}

  //  countChars = countChars - countWords;

cout << setw(12) << countLines << setw(12) << countWords << setw(12) << countChars  << endl;

infile.close();

return 0;
}

A: I believe OP's purpose to ask this question is to find out why his/her code is not working, therefore I will answer in this perspective.

counting the right amount of  words

*

*C++ define EOF(end of file) as -1, so include a check for EOF too, or you will miss a word count.

if it gets doubled space it counts like a character and a word.

*You can use a boolean test to solve this, if you encountered a space, turn on the boolean, and skip if next char is a space, too.

*I suppose your character count doesn't count in punctuation? so check for c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'. If your assignment count punctuation as character count too, ignore this point.
Below is a correct version code that is modified based on your code.
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;

int main(int argc, const char * argv[]) {
    string lines, words, chars, file1, file2;

    ifstream infile;
    ofstream outfile;
    char c;
    bool findNextString = false;

    int countLines = 0;
    int countChars = 0;
    int countWords = 0;
    cout << "Enter the file name" << endl;
    cin >> file1;
    infile.open(file1.c_str());

    while (!infile.eof())
    {
        if (infile.peek() == 1)
            break;
        c = infile.get();

        // use the boolean to find next valid string
        if (findNextString && c == ' ')
            continue;
        else
            findNextString = false;

        // there is a structure issue with your code.
        // you should think of the priority of checking

        // do not check by rejection, because you will count in punctuation too.
        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
        {
            countChars++;
        }
        else if (c == '\n')
        {
            countLines++;
            countWords++; // <- add word too
        }
        else if (c == ' ' || c == EOF)
        {
            countWords++;
            findNextString = true;
        }
    }

    cout << setw(12) << countLines << setw(12) << countWords << setw(12) << countChars << endl;

    infile.close();

    return 0;
}

A: Use getline for reading file line by line
while(getline(file,str))
{
    countLines++;
    countChars += str.length();
    countWords += CountWords(str);
 }

Which file is an iofstream object and str is a string. And for counting number of words(CountWords), you have several ways. One of them is:
#include <vector>
#include <string>
#include <boost/algorithm/string/split.hpp>

int countWords(std::string str) {
  vector< std::string > result;
  boost::algorithm::split_regex(result, str, regex( "\\s+" ));
  return result.size();
}


text:
Q: How to change duration of "remember me" cookie in laravel 9? I'm using laravel 9 and implementing login authentication manually without the laravel starter kit, I've read a lot of questions like this but most of the answers only apply to those using the starter kit, I've also read some of the other answers without the starter kit but most of them don't work.
This is my login method in the controller:
public function auth()
{
    // validation
    request()->validate([
        'emailOrUsername' => ['required'],
        'password' => ['required']
    ]);

    // Check if the user clicks "remember me" in the login form
    $remember = (request()->remember) ? true : false;

    // If login using email
    if (Auth::attempt(['email' => request()->emailOrUsername, 'password' => request()->password], $remember)) {
        request()->session()->regenerate();
        return redirect()->intended('/dashboard');
    }
    // If login using username
    else if (Auth::attempt(['username' => request()->emailOrUsername, 'password' => request()->password], $remember)) {
        request()->session()->regenerate();
        return redirect()->intended('/dashboard');
    }
    // If incorrect credentials
    else {
        return back()->with('errorAlert', 'Maaf, email/username atau password yang anda masukkan salah');
    }
}

I also noticed that it seems the default cookie duration for "remember me" is set in the Illuminate\Auth\SessionGuard namespace (but I didn't find the explanation in the official laravel documentation), I see that class has a setRememberDuration() method to change the duration of the "remember me" cookie, but I don't know how to properly call it, I've used Auth::setRememberDuration(1000) but it doesn't work. Is there any other way to set the "remember me" cookie duration using that method? Or is there another way to change the duration without using that method?

A: You can set it in config/auth.php :
'guards' => [
    'web'     => [
        'driver'   => 'session',
        'provider' => 'users',
        'remember' => now()->addDays(7)->diffInMinutes(),
    ]
],

it's then used by the AuthManager :
if (isset($config['remember'])) {
    $guard->setRememberDuration($config['remember']);
}

edit:
For future readers, this answers only work from Laravel 8.65.0


text:
Q: AngularJS set cookies from $resource request and resend them in other requests I'm consuming services from an API coded using Phalcon micro framework, eg api.mydomain.com
I'm consuming the API using AngularJS and I'm performing the requests using the next code:
Services.factory('theRequester', ['$resource',
  function($resource){
    return $resource('http://api.mydomain.com/myrequest', {}, {
      query: {method:'GET', params:{}, isArray:false}
    });
  }]);

I'm receiving the first response correctly, (which sets sessions data in the server side) and it returns this in the headers:
Access-Control-Allow-Origin:*
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Type:application/json
Date:Thu, 22 May 2014 23:05:02 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=100
Pragma:no-cache
Server:Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.0-fips mod_bwlimited/1.4
Set-Cookie:PHPSESSID=105c5ec5df299f758c1ea124d93b109c; path=/; domain=mydomain.com
Transfer-Encoding:chunked
X-Powered-By:PHP/5.4.27

Now, for each new request I perform to the API I need to send the PHPSESSID cookie, but the problem is that the cookie is not being set after performing the request, and if I set the cookie manually in the browser the cookie is also not send in the other requests I do.
I already did a research and I always read the browser automatically sends the cookies in each request, but is not doing so.
How can I solve both problems?
Thanks


text:
Q: Streaming Standard Output of a console application to an ASP.NET MVC View What I am looking to do is:
1) From an MVC View, Start a long running Process. In my case, this process is a seperate Console Application being executed. The Console Application runs for potentially 30 minutes and regurlarily Console.Write's its current actions.
2) Back on the MVC View, periodically poll the server to retrieve the latest Standard Out which I have redirected to a Stream (or anywhere I can get access to it for that matter). I'll append newly retieved standard output to a log textbox or something equivalent.
Sounds relativly easy. My client side programming is a bit rusty though and I'm having issues with the actual streaming. I would assume this is not an uncommon task. Anyone got a decent solution for it in ASP.NET MVC?
Biggest issue seems to be that I cant get the StandardOutput until the end of execution, but I was able to get it with an event handler. Of course, using the event handler seems to lose focus of my output.
This is what I was working with so far...
    public ActionResult ProcessImport()
    {
        // Get the file path of your Application (exe)
        var importApplicationFilePath = ConfigurationManager.AppSettings["ImportApplicationFilePath"];

        var info = new ProcessStartInfo
        {
            FileName = importApplicationFilePath,
            RedirectStandardError = true,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            CreateNoWindow = true,
            WindowStyle =  ProcessWindowStyle.Hidden,
            UseShellExecute = false
        };

        _process = Process.Start(info);
        _process.BeginOutputReadLine();

        _process.OutputDataReceived += new DataReceivedEventHandler(_process_OutputDataReceived);

        _process.WaitForExit(1);

        Session["pid"] = _process.Id;

        return Json(new { success = true }, JsonRequestBehavior.AllowGet);
    }

    void _process_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        _importStandardOutputBuilder.Insert(0, e.Data);
    }

    public ActionResult Update()
    {
        //var pid = (int)Session["pid"];
        //_process = Process.GetProcessById(pid);

        var newOutput = _importStandardOutputBuilder.ToString();
        _importStandardOutputBuilder.Clear();

        //return View("Index", new { Text = _process.StandardOutput.ReadToEnd() });
        return Json(new { output = newOutput }, "text/html");
    }

I haven't written the client code yet as I am just hitting the URL to test the Actions, but I'm also interested how you would approach polling for this text. If you could provide the actual code for this too, it would be great. I would assume you'd have a js loop running after kicking off the process that would use ajax calls to the server which returns JSON results... but again, its not my forte so would love to see how its done.
Thanks!

A: Right, so from the couple of suggestions I received and a lot of trial and error I have come up with a work in progress solution and thought I should share with you all. There are definitely potential issues with it at the moment, as it relies on static variables shared across the website, but for my requirement it does the job well. Here goes!
Let's start off with my view. We start off by binding the click event of my button with some jquery which does a post to /Upload/ProcessImport (Upload being my MVC Controller and ProcessImport being my MVC Action). Process Import kicks off my process which I will detail below. The js then waits a short time (using setTimeout) before calling the js function getMessages.
So getMessages gets called after the button is clicked and it does a post to /Upload/Update (my Update action). The Update action basically retrieves the status of the Process and returns it as well as the StandardOutput since last time Update was called. getMessages will then parse the JSON result and append the StandardOutput to a list in my view. I also try to scroll to the bottom of the list, but that doesn't work perfectly. Finally, getMessages checks whether the process has finished, and if it hasn't it will recursivly call itself every second until it has.

Upload

    Description of the upload process and any warnings or important information here.

Process files

The Controller. I chose not to go with an AsyncController, mainly because I found I didn't need to. My original issue was piping the StdOut of my Console application to the view. I found couldn't ReadToEnd of the standard out, so instead hooked the event handler ProcessOutputDataReceived up which gets fired when standard out data is recieved and then using a StringBuilder, append the output to previously received output. The issue with this approach was that the Controller gets reinstantiated every post and to overcome this I decided to make the Process and the StringBuilder static for the application. This allows me to then receive a call to the Update Action, grab the static StringBuilder and effectivly flush its contents back to my view. I also send back to the view a boolean indicating whether the process has exited or not, so that the view can stop polling when it knows this. Also, being static I tried to ensure that if an import in in progress, don't allow other's to begin.
public class UploadController : Controller
{
    private static Process _process;
    private static StringBuilder _importStandardOutputBuilder;

    public UploadController()
    {
        if(_importStandardOutputBuilder == null)
            _importStandardOutputBuilder = new StringBuilder();
    }

    public ActionResult Index()
    {
        ViewData["Title"] = "Upload";
        return View("UploadView");
    }

    //[HttpPost]
    public ActionResult ProcessImport()
    {
        // Validate that process is not running
        if (_process != null && !_process.HasExited)
            return Json(new { success = false, message = "An Import Process is already in progress. Only one Import can occur at any one time." }, "text/html");

        // Get the file path of your Application (exe)
        var importApplicationFilePath = ConfigurationManager.AppSettings["ImportApplicationFilePath"];

        var info = new ProcessStartInfo
        {
            FileName = importApplicationFilePath,
            RedirectStandardError = true,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            CreateNoWindow = true,
            WindowStyle =  ProcessWindowStyle.Hidden,
            UseShellExecute = false
        };

        _process = Process.Start(info);
        _process.BeginOutputReadLine();
        _process.OutputDataReceived += ProcessOutputDataReceived;
        _process.WaitForExit(1);

        return Json(new { success = true }, JsonRequestBehavior.AllowGet);
    }

    static void ProcessOutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        _importStandardOutputBuilder.Append(String.Format("{0}{1}", e.Data, "
"));
    }

    public ActionResult Update()
    {
        var newOutput = _importStandardOutputBuilder.ToString();
        _importStandardOutputBuilder.Clear();
        return Json(new { message = newOutput, processExited = _process.HasExited }, "text/html");
    }
}

Well, that's it so far. It works. It still needs work, so hopefully I'll update this solution when I perfect mine. What are your thoughts on the static approach (assuming the business rule is that only one import can occur at any one time)?

A: Look into long poll. Basically you can open an ajax request and then hold onto it inside the controller.
Sample of long poll
This is something that you will want to do Async or you will possibly have issues with thread starvation.

A: Consider writing a service that runs on a server somewhere and pipes its output to a file/db accessible by your web server. Then you can just load the generated data in your website and returning them to your caller.
Understand that tying up your web server's threads for extended periods of time can result in thread starvation and make it look like your website has crashed (even though it's acutally just busy waiting for your console app to run).


text:
Q: Publishing messages to AWS SNS with Micronaut and Kotlin I'm tryin to send a list of objects to an SNS topic, with Micronaut and Kotlin.
Following the documentation https://micronaut-projects.github.io/micronaut-aws/latest/guide/#sdkv2

*

*I added implementation("io.micronaut.aws:micronaut-aws-sdk-v2").

*accessKeyId, secretKey, sessionToken and region to the application yml file.

*Added implementation("software.amazon.awssdk:sns")
After which you should have these beans:

*

*software.amazon.awssdk.services.sns.SnsAsyncClientBuilder

*software.amazon.awssdk.services.sns.SnsAsyncClient
I'm assuming asynchronous calls...

Now it's not clear what else should I do how to create the clients to make the calls to
publish a message.
I was inclined to use Netty but what about URLConnection ??
Whats the next step in here?
I've also found another article but they use Java https://agorapulse.github.io/micronaut-aws-sdk/#_simple_notification_service_sns
it uses another package
Is there any example of how to do this? can you do this with Micronaut?


text:
Q: Optimizing my mysql query to use index for sorting I need your help to optimize the query below. Let us assume we have a web application for articles. The software use two table;one is the article table and the second one is the users table. The article table hold the date when the article is created,the id,the body,the title & the section. Let us assume that we have one section called "news" and there are one million article belong to news section. So in this case, how to optimize the following query:
SELECT username,title FROM article,users
WHERE article.auther_id=users.id AND section LIKE 'news'
ORDER BY article.date DESC
LIMIT 0,40

The table structures are:
CREATE TABLE `article` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 100 ) NOT NULL ,
`body` VARCHAR( 200 ) NOT NULL ,
`date` VARCHAR( 30 ) NOT NULL ,
`auther_id` INT NOT NULL ,
`section` VARCHAR( 30 ) NOT NULL
) ENGINE = MYISAM ;

CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 30 ) NOT NULL
) ENGINE = MYISAM ;

I tried to create one index that consists of the section & the date but it is not the best,because if we have 2 millions record and one million of them belong to one section,the DB will scan one million row.

A: Add an index on article.auther_id. in addition to the index you've already added on date and section.

A: From looking at the query it seems you would need an index on section and an index on date (two separate indexes). Try adding these and then look at the explain plan to see if they work or if there are some other tweaks that might help.

A: OK, first off use the DATE datatype for dates as this will be a lot faster than using a VARCHAR.
Secondly, you simply need to add the following keys to your create table syntax for the article table.
KEY auther_id (auther_id),
KEY section (section),

Somewhat irrelevant, but if you were using InnoDB you could additionally make the auther_id as a foreign key.
Also, if you don't need to use 'LIKE' don't - simply checking for section="news" will be a lot faster. (You could even use an ENUM for the sections if there's a finite list.)

A: As others have said, indexes on date, section and auther_id. According to this:
http://www.mysqlperformanceblog.com/2008/08/22/multiple-column-index-vs-multiple-indexes/
it may well be beneficial to have one multiple-column index rather than three separate ones, like this:
...
key idx_combo (auther_id, section, date)
...

in your table definition.

A: Best thing to do is to create a partitioned table basing on date/sections.
then create locally partitioned indexes suchthat the performance will be much higher.

A: You need to create an index on (section, date).
Don't include auther_id as a leading column: articles will be leading in the join and no searching will be performed on this column.
Since there is a LIMIT 0, 40 in your query, MySQL will not have to scan the whole index. It will just pick the first 40 records.
Here's a test script to check:
CREATE TABLE `article` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 100 ) NOT NULL ,
`body` VARCHAR( 200 ) NOT NULL ,
`date` VARCHAR( 30 ) NOT NULL ,
`auther_id` INT NOT NULL ,
`section` VARCHAR( 30 ) NOT NULL
) ENGINE = MYISAM ;

CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 30 ) NOT NULL
) ENGINE = MYISAM ;

INSERT
INTO    article
SELECT  id,
        CONCAT('Title ', id),
        CONCAT('Body ', id),
        DATE_FORMAT('2009-12-18' - INTERVAL id MINUTE, '%Y-%m-%d %H:%i:%S'),
        (id - 1) % 500 + 1,
        'news'
FROM    t_source;

INSERT
INTO    users
SELECT  id, CONCAT('Username ', id)
FROM    t_source
LIMIT 500;

CREATE INDEX ix_article_section_date ON article (section, date);

SELECT  username,title
FROM    article
JOIN    users
ON      users.id = article.auther_id
WHERE   section = 'news'
ORDER BY
        article.date DESC
LIMIT 0, 40;

t_source is a dummy table with 1,000,000 rows in it.
The final query completes in 0.0018 s on my machine (instantly)
Here's the execution plan:
1, 'SIMPLE', 'article', 'range', 'ix_article_section_date', 'ix_article_section_date', '92', '', 999998, 'Using where'
1, 'SIMPLE', 'users', 'eq_ref', 'PRIMARY', 'PRIMARY', '4', 'test.article.auther_id', 1, ''


text:
Q: PySpark how to sort array of struct with 2 elements I have the following schema
|-- node: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- score: string (nullable = true)
 |    |    |-- toID: string (nullable = true)

+-----------
 node|
+-------------
|[[57753, XV0912938...|
|[[51959, 02384848...|
|[[63487, 898898989...|

I want to sort based on score and select top 10 toID . What is an easy pyspark way to do this ?

A: sort_array(<array column>, asc=False) function can be used to sort the elements within the array. If the elements are structs, the array is sorted based on the first field in the struct. Since, the score field is the first field in the struct, you can directly sort the array of structs using this function.
Here's an example to get the top 5 IDs based on the score within the struct.
Suppose your data looks like the following
+----------------------------------------------------------------------------------------------------------------------------------------+
|arr_of_structs                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------+
|[{270, foo0}, {237, foo1}, {2440, foo2}, {2059, foo3}, {3960, foo4}, {3009, foo5}, {842, foo6}, {1043, foo7}, {852, foo8}, {3925, foo9}]|
|[{1028, bar0}, {2571, bar1}, {1682, bar2}, {2543, bar3}, {689, bar4}, {11, bar5}, {1, bar6}, {740, bar7}, {113, bar8}, {701, bar9}]     |
+----------------------------------------------------------------------------------------------------------------------------------------+

root
 |-- arr_of_structs: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _1: long (nullable = true)
 |    |    |-- _2: string (nullable = true)

The code would be very simple

*

*use sort_array to sort the array of structs

*use slice function to retain the first N elements in the sorted array.

data_sdf. \
    withColumn('arr_of_structs_top5', func.slice(func.sort_array('arr_of_structs', asc=False), 1, 5)). \
    withColumn('top5_id_only', func.expr('transform(arr_of_structs_top5, x -> x._2)')). \
    drop('arr_of_structs'). \
    show(truncate=False)

# +----------------------------------------------------------------------+------------------------------+
# |arr_of_structs_top5                                                   |top5_id_only                  |
# +----------------------------------------------------------------------+------------------------------+
# |[{3960, foo4}, {3925, foo9}, {3009, foo5}, {2440, foo2}, {2059, foo3}]|[foo4, foo9, foo5, foo2, foo3]|
# |[{2571, bar1}, {2543, bar3}, {1682, bar2}, {1028, bar0}, {740, bar7}] |[bar1, bar3, bar2, bar0, bar7]|
# +----------------------------------------------------------------------+------------------------------+


text:
Q: How to update ipyvolume shapes immediately without intermediate views Given jupyter notebook with a scene rendered with ipyvolume and sliders that updates the x,y,z traits of a shape on the scene, the 3D renderer has a scene change animation which draws intermediate views of the shape that do not correspond to views on the slider.
How do I force ipyvolume to render only the final scene on update, without the scene change animation?
For example, run the following in a jupyter notebook and drag theta/phi:
import numpy as np
from numpy import pi, sin, cos, radians
import ipyvolume as ipv
import ipywidgets as widgets

def transform_xyz(theta, phi, x, y, z):
    x, y, z = [np.asarray(v) for v in (x, y, z)]
    shape = x.shape
    points = np.matrix([x.flatten(), y.flatten(), z.flatten()])
    Ry_theta = [[+cos(theta), 0, +sin(theta)],
                [0, 1, 0],
                [-sin(theta), 0, +cos(theta)]]
    Rz_phi = [[+cos(phi), -sin(phi), 0],
              [+sin(phi), +cos(phi), 0],
              [0, 0, 1]]
    points = np.matrix(Rz_phi)*np.matrix(Ry_theta)*points
    x, y, z = [np.array(v).reshape(shape) for v in points]
    return x, y, z

def torus(R=100, r=10, Rsteps=100, rsteps=100):
    u = np.linspace(0, 2*pi, rsteps) # tube
    v = np.linspace(0, 2*pi, Rsteps) # ring
    U, V = np.meshgrid(u, v)
    x = (R + r*cos(U))*cos(V)
    y = (R + r*cos(U))*sin(V)
    z = r*sin(U)
    return x, y, z

class Scene:
    def __init__(self, view=(0, 0, 0), hkl=(1,1,1)):
        self.view = view
        self.figure = ipv.figure()
        R = 100.
        r = R/30.
        ipv.xlim(-R, R)
        ipv.ylim(-R, R)
        ipv.zlim(-R, R)
        ipv.style.box_off()
        self.torus_xyz = torus(R=R, r=R/10)
        self.torus = ipv.plot_surface(*self.torus_xyz)
        ipv.show()
        self.ui = widgets.interact(self.update, theta=(-90.,90.), phi=(-180., 180.))
        #self.ui.widget.children[0].continuous_update = False
        #self.ui.widget.children[1].continuous_update = False

    def update(self, theta, phi):
        print("update with", theta, phi)
        x, y, z = transform_xyz(radians(theta), radians(phi), *self.torus_xyz)
        self.torus.x = x.flatten()
        self.torus.y = y.flatten()
        self.torus.z = z.flatten()

scene = Scene()

A: Setting the animation time for the transition to zero when the figure is created mostly solves the problem:
...
self.figure = ipv.figure(animation=0.)
...

The figure still jitters a bit when ui sliders are set to continuous update, presumably because there is an occasional transition frame that is being drawn.

Another possible source of jitter is that traitlets is not sending x, y, z updates synchronously, and so maybe it is sometimes showing updates with x and y for the new view while retaining z from the old view.

A: You could also try setting the animation_exponent to 0. Ipyvolume uses linear interpolation to update the figure on a data change, the exponent sets the speed of this interpolation. A zero exponent should result in an instant update.
self.figure = ipv.figure(animation=0.,animation_exponent=0.)


text:
Q: How to use interrupt handlers written in C in a C++ program? I'm writing a program in C++ for my Tiva C Series board (EK-TM4C123GXL) and I'd like to use the USB lib provided by TI to make it a device for another board.
I use the startup_gcc.c file provided here.
Unfortunately, I cannot compile with those declarations :
extern void SysTickIntHandler(void);
extern void USB0DeviceIntHandler(void);

I get
(.isr_vector+0x3c):-1: error: undefined reference to `SysTickIntHandler'

I tried
#ifdef __cplusplus
extern "C"
{
#endif
void SysTickIntHandler(void);
void USB0DeviceIntHandler(void);
#ifdef __cplusplus
}
#endif

but nothing better.


text:
Q: "once I receive it" vs. "once received" What is the difference between once I receive it and once received?
Ex.

*

*I will send the picture to you once I receive it from John.

*I will send the picture to you once received.

A: I think the only difference is that the first sentence makes it explicitly clear who is expected to receive the picture from whom.
The second sentence does not state that explicitly, but only assures the listener that the speaker will send him the picture once "someone" receives the picture from "someone". For instance, your second sentence could imply the following, among many other possibilities:

I will send the picture to you once received (by my assistant from John's secretary).

Note though, that the parenthesized part is only used to explain my point. A more natural phrasing of that sentence would be:

I will send you the picture once my assistant receives it from John's secretary.

A: I would like to add that example 1 is in the active voice and example 2 is in the passive voice (hence the unspoken by-phrase, "once received (by...)."


text:
Q: Explode multiple columns of same type with different lengths I have a spark data frame with the following format that needs to be exploded. I check other solutions such as this one. However, in my case, before and after can be arrays of different length.
root
 |-- id: string (nullable = true)
 |-- before: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- start_time: string (nullable = true)
 |    |    |-- end_time: string (nullable = true)
 |    |    |-- area: string (nullable = true)
 |-- after: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- start_time: string (nullable = true)
 |    |    |-- end_time: string (nullable = true)
 |    |    |-- area: string (nullable = true)

For instance, if the data frame has just one row, before is a array of size 2 and after is an array of size 3, the exploded version should be have 5 rows with the following schema:
root
 |-- id: string (nullable = true)
 |-- type: string (nullable = true)
 |-- start_time: integer (nullable = false)
 |-- end_time: string (nullable = true)
 |-- area: string (nullable = true)

where type is a new column which can be "before" or "after".
I can do thss in two separate explodes where I make type column in each explode and union then.
val dfSummary1 = df.withColumn("before_exp",
explode($"before")).withColumn("type",
lit("before")).withColumn(
"start_time", $"before_exp.start_time").withColumn(
"end_time", $"before_exp.end_time").withColumn(
"area", $"before_exp.area").drop("before_exp", "before")

val dfSummary2 = df.withColumn("after_exp",
explode($"after")).withColumn("type",
lit("after")).withColumn(
"start_time", $"after_exp.start_time").withColumn(
"end_time", $"after_exp.end_time").withColumn(
"area", $"after_exp.area").drop("after_exp", "after")

val dfResult = dfSumamry1.unionAll(dfSummary2)

But, I was wondering if there is a more elegant way to do this. Thanks.

A: You can also achieve this without union. With the data :
case class Area(start_time: String, end_time: String, area: String)

val df = Seq((
  "1", Seq(Area("01:00", "01:30", "10"), Area("02:00", "02:30", "20")),
  Seq(Area("07:00", "07:30", "70"), Area("08:00", "08:30", "80"), Area("09:00", "09:30", "90"))
)).toDF("id", "before", "after")

you can do
df
  .select($"id",
    explode(
      array(
        struct(lit("before").as("type"), $"before".as("data")),
        struct(lit("after").as("type"), $"after".as("data"))
      )
    ).as("step1")
  )
 .select($"id",$"step1.type", explode($"step1.data").as("step2"))
 .select($"id",$"type", $"step2.*")
 .show()

+---+------+----------+--------+----+
| id|  type|start_time|end_time|area|
+---+------+----------+--------+----+
|  1|before|     01:00|   01:30|  10|
|  1|before|     02:00|   02:30|  20|
|  1| after|     07:00|   07:30|  70|
|  1| after|     08:00|   08:30|  80|
|  1| after|     09:00|   09:30|  90|
+---+------+----------+--------+----+

A: I think exploding the two columns separately followed by a union is a decent straightforward approach.  You could simplify the StructField-element selection a little and create a simple method for the repetitive explode process, like below:
import org.apache.spark.sql.functions._
import org.apache.spark.sql.DataFrame

case class Area(start_time: String, end_time: String, area: String)

val df = Seq((
  "1", Seq(Area("01:00", "01:30", "10"), Area("02:00", "02:30", "20")),
  Seq(Area("07:00", "07:30", "70"), Area("08:00", "08:30", "80"), Area("09:00", "09:30", "90"))
)).toDF("id", "before", "after")

def explodeCol(df: DataFrame, colName: String): DataFrame = {
  val expColName = colName + "_exp"
  df.
    withColumn("type", lit(colName)).
    withColumn(expColName, explode(col(colName))).
    select("id", "type", expColName + ".*")
}

val dfResult = explodeCol(df, "before") union explodeCol(df, "after")

dfResult.show
// +---+------+----------+--------+----+
// | id|  type|start_time|end_time|area|
// +---+------+----------+--------+----+
// |  1|before|     01:00|   01:30|  10|
// |  1|before|     02:00|   02:30|  20|
// |  1| after|     07:00|   07:30|  70|
// |  1| after|     08:00|   08:30|  80|
// |  1| after|     09:00|   09:30|  90|
// +---+------+----------+--------+----+


text:
Q: adjust keys in an array For example I have the following array :
$arr[0] = "1"
$arr[7] = "p"
$arr[10] = "c"
$arr[12] = 'k"

How do I transform it to :
$arr[0] = "1"
$arr[1] = "p"
$arr[2] = "c"
$arr[3] = 'k"

A: Like this:
$arr = array_values($arr);

http://www.php.net/manual/en/function.array-values.php


text:
Q: Can I change an existing partition from MBR to GPT? I needed to add extra 2.5TB to the existing 400GB disk (sda) on my system. I added new virtual disks with 2.5TB (sdb), proceeded to create the partition table with fdisk.
Used pvcreate /dev/sdb1, to create the physical volume, then extended the volume group and finally extended the logical volume.
At the end I used the xfs_grow2fs for the filesystem to recognize. Only until then I realized that I only got 2TB out of the 2.5TB on the new disk due to MBR limitation.
Can I convert this drive to GPT without affecting sda? Will this movement affect the filesystem due to xfs_grow2fs being used? The worst case scenario would be having .5TB missing.
Using CentOS 7.
lsblk command output
NAME                 MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
fd0                    2:0    1     4K  0 disk
sda                    8:0    0   420G  0 disk
├─sda1                 8:1    0   500M  0 part /boot
└─sda2                 8:2    0 419.5G  0 part
  ├─centos_sftp-root 253:0    0    15G  0 lvm  /
  ├─centos_sftp-swap 253:1    0     2G  0 lvm  [SWAP]
  └─centos_sftp-home 253:2    0   2.4T  0 lvm  /home
sdb                    8:16   0   2.5T  0 disk
└─sdb1                 8:17   0     2T  0 part
  └─centos_sftp-home 253:2    0   2.4T  0 lvm  /home
sr0                   11:0    1  1024M  0 rom

lvs command
  LV   VG          Attr       LSize  Pool Origin Data%  Meta%  Move Log
Cpy%Sync Convert
  home centos_sftp -wi-ao----  2.39t
  root centos_sftp -wi-ao---- 15.00g
  swap centos_sftp -wi-ao----  2.00g

df command
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/centos_sftp-root   15G  2.7G   13G  18% /
devtmpfs                      2.9G     0  2.9G   0% /dev
tmpfs                         2.9G     0  2.9G   0% /dev/shm
tmpfs                         2.9G  8.6M  2.9G   1% /run
tmpfs                         2.9G     0  2.9G   0% /sys/fs/cgroup
/dev/mapper/centos_sftp-home  2.4T  103G  2.3T   5% /home
/dev/sda1                     497M  171M  326M  35% /boot
tmpfs                         581M     0  581M   0% /run/user/1000
tmpfs                         581M     0  581M   0% /run/user/0

I used xfs_growfs to extend home to use the additional 2.5TB but only got 2TB from the new disk due to MBR limits.
output of fdisk -l /dev/sdb
Disk /dev/sdb: 2748.8 GB, 2748779069440 bytes, 5368709120 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x3633c5d9

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048  4294967294  2147482623+  8e  Linux LVM

A: The MBR partition /dev/sdb1 starts at the offset 1MB. This is good, because the first GPT partition would also start at the offset 1MB.
So delete the current partition with fdisk and use g to create a new GPT partition. Choose type LVM for this partition. Make sure that the new partition starts at the same offset as the old one, before you use the w command. Otherwise you will lose all your data.
You can now use the full extent of the 2.5TB instead of the 2TB limit on MBR. Write the changes on disk and reboot. Use fdisk -l to check that changes on sdb are okay. Now we read 2.5TB available. Time to resize the volume groups and physical volumes.
Use pvresize /dev/sdb1 to resize to the new additional space appropriately. Afterwards use lvresize to resize the logical volume group. And finally xfs_growfs to increase the filesystem. Use df to confirm the changes at the end.
For this last part you may refer to this article.


text:
Q: jquery Masonry - Not working Please can someone tell me where I'm going wrong with my jQuery masonry code. I've posted the link to my test page below:
http://davidlloydphotography.com/home.html
I have followed the step by step guide the Masonry website (http://masonry.desandro.com/). I think it might be how I'm initialising the jQuery, not sure where it goes, the tutorial is not clear:
$('.grid').masonry({
  // options
  itemSelector: '.grid-item',
  columnWidth: 700
});

No idea why it won't flow into the layout, the placeholder images just hang to the left :(
Any help would be greatly appreciated I've been at this for days, its got to be a simple problem.

A: You should use only one version of jQuery, (not 2 depending on the browser) and put your js at the bottom of the page and load masonry with "document ready".
If you are loading many images, consider using imagesloaded as well.
HTML:

JS:


text:
Q: gnuplot: line break following a comment line Why this code doesn't work?
plot \
#sin(x),\
cos(x)

the error info is
plot
     ^
"a.plt", line 3: function to plot expected

gnuplot --version
gnuplot 5.0 patchlevel 0

A: That code doesn't work, because a \ at the end of a comment line makes gnuplot treat the next line also as comment. See the documentation about comments.


text:
Q: Texture atlas to texture array via PIXEL_UNPACK_BUFFER I have two questions:
First, is there any more direct, sane way to go from a texture atlas image to a texture array in WebGL than what I'm doing below? I've not tried this, but doing it entirely in WebGL seems possible, though four-times the work and I still have to make two round trips to the GPU to do it.
And am I right that because buffer data for texImage3D() must come from PIXEL_UNPACK_BUFFER, this data must come directly from the CPU side? I.e. There is no way to copy from one block of GPU memory to a PIXEL_UNPACK_BUFFER without copying it to the CPU first. I'm pretty sure the answer to this is a hard "no".
In case my questions themselves are stupid (and they may be), my ultimate goal here is simply to convert a texture atlas PNG to a texture array. From what I've tried, the fastest way to do this by far is via PIXEL_UNPACK_BUFFER, rather than extracting each sub-image and sending them in one at a time, which for large atlases is extremely slow.
This is basically how I'm currently getting my pixel data.
const imageToBinary = async (image: HTMLImageElement) => {
    const canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;

    const context = canvas.getContext('2d');
    context.drawImage(image, 0, 0);

    const imageData = context.getImageData(0, 0, image.width, image.height);

    return imageData.data;
};

So, I'm creating an HTMLImageElement object, which contains the uncompressed pixel data I want, but has no methods to get at it directly. Then I'm creating a 2D context version containing the same pixel data a second time. Then I'm repopulating the GPU with the same pixel data a third time. Seems bonkers to me, but I don't see a way around it.


text:
Q: checkbox :checked cambiar el color background jQuery https://jsfiddle.net/Chusi/w5gwdjac/5/
Como marcar el fondo a negro del div cuando el radio esté en checked , y solo un div a la vez pueda estar en negro JQuery.
El problema que tengo ahora es que los div se marcan con color negro, pero cuando marco uno al marcar el siguiente, el primero no vuelve al color inicial sino que se queda marcado con color negro.

A: Aquí tienes el código.
Simplemente cuando hagas un on('change') tienes que devolver todos los box a su estado original y al seleccionado darle los estilos que quieras darles.
https://jsfiddle.net/w5gwdjac/10/
añado: también puedes crear clases como "radioSelected" y así puedes tener el código aún más limpio y más "readable"
CSS:
.box.selected {
    background-color: #000;
}
.box.selected p {
  color: #fff;
}

Jquery:
$input.each(function() {
    if ($(this).prop("checked")) {
        $(this).parent(".box").addClass("selected");
    }
});
$input.on('change', function() {
    if ($(this).prop("checked")) {
        $input.each(function() {
            $(this).parent(".box").removeClass("selected");
        });
        $(this).parent(".box").addClass("selected");
    }
});


text:
Q: BaseActivity as Lifecycle Owner for DataBinding My project structure has a BaseActivity which is extended by multiple child activities, so the structure is like
                  BaseActivity
                        ^
                        |
          -------------------------------
          |             |               |
 ChildActivityA  ChildActivityB  ChildActivityC

I am using DataBinding with LiveData, and hence every time I need to set up the lifecycleOwner for the respective binding class i.e (in ChildActivityA)
  val binding = DataBindingUtil.setContentView(R.layout.somelayout)
  binding.lifecycleOwner = this@ChildActivityA

Now I need to repeat this boilerplate in each Activity, so instead I created a helper extension function to replace the above two lines i.e
fun <T : ViewDataBinding> BaseActivity.setDataBindingView(layoutId: Int): T {
   val binding = DataBindingUtil.setContentView(this, layoutId)
   binding.lifecycleOwner = this@BaseActivity
}

and then call in my ChildActivityA as
val binding = setDataBindingView(R.layout.someLayout)

As you can see the binding.lifecycleOwner is set to BaseActivity instead of the actual ChildActivityA, now will this cause any trouble? Will the binding.lifecycleOwner be still following the lifecycle of ChildActivityA?

A: this@ChildActivityA and this@BaseActivity refer to the same actual object in memory - there's only one activity object that exists. Therefore they're entirely equivalent.


text:
Q: Windows Server 2008 R2 DC can't ping to other computers except other DC I have been trying to troubleshoot this problem since 20 hours ago, and still can't find a solution.
I brought down (orderly shutdown) a Domain Controller yesterday. No problem at all connecting to it (via RDP).
The Domain Controller is a VM running on top of XenServer 6.0.2.
The problem started after I brought the VM back up. I cannot ping from my computer to the Domain Controller, &vv. However, the Domain Controller can ping to (and be pinged from) the PDC, the Default Gateway, and some other servers.
Since the DC is not the PDC, it's not as critical... but I still wonder what went wrong...
I've even added a Firewall rule to allow any traffic from my computer... still no go. I can't ping to it, and it can't ping to me.
Since it can ping to the PDC, the DG, and (some) other servers, it's not a problem of XenServer's virtual NIC (I think).
What else should I be looking at?

Edit:
More information:

*

*The problematic DC's address: 10.153.198.59/22

*Ping to PDC ( 10.153.199.252/22 ) : successful

*Ping to My PC ( 10.153.199.77/22 ) : FAILED

*Ping to Default Gateway ( 10.153.197.254 ) : successful

*Ping to another (non-DC) server ( 10.153.192.40/23 ) : successful

Note that the problematic DC and My PC are on the same subnet. Yet, pinging to a server on a different subnet works.
Pinging my computer results in an output like this:
Pinging pepoluan.my.domain.com [10.153.199.77] with 32 bytes of data:
Reply from 10.153.198.59: Destination host unreachable.
Reply from 10.153.198.59: Destination host unreachable.
Reply from 10.153.198.59: Destination host unreachable.
Reply from 10.153.198.59: Destination host unreachable.

Finally, output of route print:
===========================================================================
Interface List
 13...1e a1 17 a3 d9 74 ......Citrix PV Ethernet Adapter #0
  1...........................Software Loopback Interface 1
 11...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
 14...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0   10.153.197.254    10.153.198.59    266
     10.153.196.0    255.255.252.0         On-link     10.153.198.59    266
    10.153.198.59  255.255.255.255         On-link     10.153.198.59    266
   10.153.199.255  255.255.255.255         On-link     10.153.198.59    266
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link     10.153.198.59    266
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link     10.153.198.59    266
===========================================================================
Persistent Routes:
  Network Address          Netmask  Gateway Address  Metric
          0.0.0.0          0.0.0.0   10.153.197.254  Default
===========================================================================

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
  1    306 ::1/128                  On-link
 13    266 fe80::/64                On-link
 13    266 fe80::d993:f856:31c6:4cbe/128
                                    On-link
  1    306 ff00::/8                 On-link
 13    266 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None


text:
Q: R Different years on axes for scatter in panel I would like to receive your help. I am struggling (not so much familiar with R and further motivation to study it more)
I have a panel (countries) and 1 variable (field_mismatch) available only for 2 years (2015-2016). I would like to have a scatterplot with on the x-axis the year 2015 while, on the y-axis the year 2016.
Within it, the values that those countries have and a 45 degree line. I would like to have a different color for EU28 and LVA.
Can someone help me in what kind of code should I write?
Thank you very much


text: Q: How to determine significant differences between frequency spectra? I want to determine whether the mean of frequency spectra are statistically different from each other. I have a set of trials in different drug conditions and I want to test whether a drug had an effect on the frequency distribution and/or power across frequency range. This is opposed to determining whether power in a particular frequency band is different across conditions. For example, below are two experiments. I want to determine whether the red line differs from the blue. Standard error is marked by grey shading. Thank you for any suggestions and pointers!


text:
Q: Relayjs performance really bad, setVariables Does anyone know what causes these huge blocking functions in Relay when making requests? I have a search box that calls setVariables and it's immensely noticeable.

It's much better in production. Still curious though


text:
Q: Validate french date format in unobtrusive jQuery Validate in ASP MVC 4 I'd like to validate the dateformat in ASP MVC 4 with Unobtrusive jQuery Validation.
My Views/Shared/EditorTemplates/DateTimeNotNullable.cshtml :
@model DateTime

@Html.TextBox("", Model.ToShortDateString(), new { maxlength = 10, @class = "editor-datetime", style = "width: 150px" })

<script type="text/javascript">
    if (typeof (jQuery) == 'function')
    {
        $(function () {
            if ($.datepicker) {
                $("#@this.ViewData.TemplateInfo.GetFullHtmlFieldId("")").datepicker();
            }
        });
    }
</script>

But when I put a french date format (dd/MM/yy) ex: 18/04/2013, I always have a valiation error.
I already tryied to use the Microsoft Globalization library, it worked but I had a regression on the validation of the decimal format.
Do you have simple javascript to correct that behaviour ?


text:
Q: Specialize hashmap template I'm using the hash_map in C++ and want to supply a simplified type name for it:
The key type and hasher function are always the same.
stdext::hash_map<std::string, [MAPPED TYPE], CStringHasher>

However, I don't really want to write all this every time I declare a hash map which maps strings to type X.

*

*Can I write a template or macro that simplifies this?

So the above declaration would look like:
template<typename T> StringHashmap = stdext::hash_map<std::string, T, CStringHasher>

StringHashmap<int> mapA; //Maps std::string to int
StringHashamp<bool> mapB; //Maps std::string to bool

A: As others said, template aliases is the way to go if you can use C++0x:
template < typename MappedType >
using StringHashMap = stdext::hash_map< std::string, MappedType, CStringHasher >;

StringHashMap< int > mapA;
StringHashMap< bool > mapB;

(As @MSalters noted, if you have C++0x available, you should probably use std::unordered_map.)
Otherwise, you can still use the usual workaround, which is to define a class template containing a typedef:
template < typename MappedType >
struct StringHashMap
{
    typedef stdext::hash_map< std::string, MappedType, CStringHasher > type;
};

StringHashMap< int >::type mapA;
StringHashMap< bool >::type mapB;

A drawback with this solution (which have engendered many questions here on SO) is that you sometimes need to prefix StringHashMap< T >::type by the typename keyword in order to assert to the compiler that this name effectively denotes a type. I will not dwell on this subject in this answer, you can check out this FAQ, and especially the accepted answer, for more information. (Thanks to @sbi for evoking this matter.)

A: With the current version of C++ (C++03), there really isn't a good way to do this.  You could try something like
#define StringHashMap(type) stdext::hash_map<std::string, type, CStringHasher>

But then you run into trouble if you try to specify a template type with a comma in it, like this:
StringHashMap(pair<int, string>) myMap; // Error!

This fails because the preprocessor will tokenize this as
StringHashMap((pair<int), (string>)) myMap; // Error!

which isn't what you want.  If you're not going to do anything like this, though, you should be fine.  You could alternatively use typedefs to get around it:
typedef pair<int, int> IntPair;
StringHashMap(IntPair) myMap; // Okay

If you're allowing use of C++0x features, you can use a template using declaration, like this one here:
template <typename T>
    using StringHashMap = stdext::hash_map<std::string, T, CStringHasher>;

Unfortunately, C++03 doesn't have a "template typedef" feature like this one, so you'd have to use a newer compiler and won't have as good a portability guarantee.
Hey, wait a minute!  My name is templatetypedef and this is the first time on Stack Overflow that I've ever written that phrase in an answer!  You just made my night. :-)

A: If you're using C++ 0x, template typedefs were designed to do exactly this kind of thing:
http://en.wikipedia.org/wiki/C%2B%2B0x#Template_aliases


text:
Q: c++ mcrypt error at mcrypt_generic I have the following code:
[test.cpp]
#include <mcrypt.h>
#include <string>
#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>

#include <string>
using namespace std;
int main()
{
  char algo[] = "rijndael-256";
  char mode[] = "cbc";
   char *block_buffer=(char*)"HELLO!! MY NAME IS: ";
cout<<"here"<<endl;
string s;
char key="1234-5678-9654-7512-7895-2543-12";

  char iv[]  = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};;

  MCRYPT td = mcrypt_module_open(algo, NULL, mode, NULL);
  if (td == MCRYPT_FAILED) { cout<<"error"<<endl;}

int keysize=32;
  int r =  mcrypt_generic_init(td, key, keysize, iv);
if (r<0)
{
    cout<<"error2"<<endl;
    mcrypt_perror(r);
            return 1;

}

 //while ( fread (&block_buffer, 1, 1, stdin) == 1 ) {
   int j=          mcrypt_generic (td, &block_buffer, sizeof(block_buffer));
if (j!=0){std::cout<<"error encrypting"<<std::endl;} // I HAVE ERROR HERE J==0

 //how to print the encrypted string??

 cout<<"buffer "<<block_buffer<<endl; //this is not the encriperd string. why?

    mcrypt_generic_deinit(td);

  mcrypt_module_close(td);
}

I am testing the code:
$: g++ test.cpp -o tst -lmcrypt
                      $: ./tst

WHERE SHOULT I ADD THE PKCS 7?
I have the following method:
std::string add_pkcs7_padding(std::string s, std::size_t n)
{
  const std::size_t fill = n - (s.length() % n);
  s.append(fill, static_cast<char>(fill));
  return s;
}

std::string strip_pkcs7_padding(std::string s, std::size_t n)
{
  const std::size_t pad = static_cast<unsigned char>(*s.rbegin());
  return s.substr(0, s.length() - pad);
}

I din't know when should i run it and where in my code.
NEED SOME HELP. APPRECIATE A LOT!!
EDIT:
I have error at:  mcrypt_generic (td, &block_buffer, sizeof(block_buffer)); The compiler prints
that the value j=0;

A: You should invoke mcrypt_generic() with a char*, not a char** as you do:
mcrypt_generic(td, block_buffer, sizeof(block_buffer));
                   ^^^           ^^^^^^^^^^^^^^^^^^^^
                                      ouch!

Also, the length is wrong, as sizeof(block_buffer) is just be the size of the pointer, not the string; if anything you need strlen(block_buffer).
But this is still going to be wrong in general because you need your message to be a multiple of the block size. Use the padding function:
std::string s = add_pkcs7_padding(block_buffer, mcrypt_enc_get_block_size(td));
std::vector<char> v(s.begin(), s.end());  // this will hold the encrypted data
mcrypt_generic(td, v.data(), v.size());

By the way, your plaintext should be declared like this:
const char * block_buffer = "HELLO!! MY NAME IS: ";
^^^^^                       ^^^^
  constness!                  no explicit cast!

But why so clumsy, it's better to just use a string:
std::string plaintext = "HELLO!! MY NAME IS: ";

I think you might benefit from picking up a good C++ book and familiarizing yourself with the basics of the language a bit - it's good to have a project to work on, but most of your problems aren't really related to encryption or mcrypt, but just general C++ programming.


text:
Q: Swagger OpenAPI 3 documentation for Firebase Authentication securityScheme What is the correct way to format the security scheme for Firebase using oauth 2.0 and OpenAPI 3.0?
The current documentation at https://cloud.google.com/endpoints/docs/openapi/authenticating-users-firebase is intended for OpenAPI 2.0, but not for OpenAPI 3.0.
I have reviewed the swagger documentation for OpenAPI 3.0, at https://swagger.io/docs/specification/authentication/, and
I also came across a similar question at Swagger definition for firebase authentication, but again, the suggested answers point to OpenAPI 2.0, rather than 3.0

A: components:
  securitySchemes:
    firebase:
      type: "oauth2"
      flows:
        implicit:
          authorizationUrl: ""
          scopes:
            read: Grants read access
            write: Grants write access
            admin: Grants access to admin operations
      # Replace YOUR-PROJECT-ID with your project ID
      x-google-issuer: "https://securetoken.google.com/YOUR-PROJECT-ID"
      x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com"
      x-google-audiences: "YOUR-PROJECT-ID"

security:
  - firebase: [ ]


text:
Q: Angularjs : Validating modal elements without using form I have this modal which dont have form tag. But i want to validate all the elements inside before user proceed with clicking on any of these two buttons.

                    ×

 Member Details

                                Name*

                                    <input type="text" style="text-transform: capitalize;" name="name" ng-model="user.name" class="form-control input" placeholder="First...  Last...  Middle..." required>

                                Contact*

                                        <input type="text" ng-pattern="/^[7-9][0-9]{9}$/" style="text-transform: capitalize;" name="mobile" ng-model="user.mobile" class="form-control digits" maxlength="10" placeholder="Mobile" required>

                                        <input type="text"  name="email" ng-model="user.email"  class="form-control input" placeholder="Email" required>

                                Gender*

                                        <input type="radio" id="gender" name="gender" ng-model="user.gender" value="F" required=""> Female

                                       <input type="radio" id="gender" name="gender" ng-model="user.gender" value="M"  ng-checked="true" required=""> Male

                                        <input type="radio" id="gender" name="gender" ng-model="user.gender" value="O" required=""> Other

            <button class="btn btn-success" type="submit"  ng-click="saveMember()"> Save</button>
            <button class="btn btn-warning" data-dismiss="modal" ng-click="addItem()"> Add Item</button>

I want to all fields to get filled before user click on any buttons. Border color should get red when there is an empty element .
New idea also welcome .
Thank you


text:
Q: Spring Boot with maven war dependancy I have Spring Boot web project with dependency to maven overlay war file which is also Spring web project. War is included in pom.xml.
How can I deploy that war along with Spring Boot application so I can use rest endpoints that belong to war file. I'm trying to start application from STS simply by running it as Java application. While application is starting, I can see only URLs that belong to Spring Boot project, but URLs that belong to war file are missing.

A: I believe Spring boot does not support that. See issue here
Try building a war and deploying it into a container.


text:
Q: Converting dictionary to Json? I'm trying to convert my dictionary to JSON. I have a client server application set and I'm trying to create an outgoing packet on the server side, but I have the packet data in a dictionary.
My dictionary structure is set up something like this.
"device.name" => "Machine-39FK394S"
"device.username" => "admin"
"device.operating_system" => "Windows 10"
"something.else" => 294

A dot represents another level in JSON, the output in JSON would be like this.
{
    "device" : {
        "name" : "Machine-39FK394S",
        "username" : "admin",
        "operating_system" : "Windows 10",
    }

    "something" : {
        "else" : 294,
    }
}

What have I tried so far?
public string GetJson()
{
    var entries = _packetData.Select(d => string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
    return "{" + string.Join(",", entries) + "}";
}

Although the above method just outputs an empty {} json string.

A: How about something like this, it should work for any number of properties:
var inputDict = new Dictionary<string, object>();

inputDict["device.name"] = "Machine-39FK394S";
inputDict["device.username"] = "admin";
inputDict["device.operating_system"] = "Windows 10";
inputDict["something.else"] = 294;

var outputObject = new Dictionary<string, object>();

foreach (var kvp in inputDict)
{
    var currentDict = outputObject;
    var depth = 0;
    var fields = kvp.Key.Split('.');

    foreach (var field in fields)
    {
        if (++depth == fields.Length)
        {
            currentDict[field] = kvp.Value;
        }
        else if (!currentDict.ContainsKey(field))
        {
            currentDict[field] = new Dictionary<string, object>();
        }
        currentDict = currentDict[field] as Dictionary<string, object>;
    }
}

var json = JsonConvert.SerializeObject(outputObject, Formatting.Indented);
Console.WriteLine("JSON: " + json);

I get the output below:
{
  "device": {
    "name": "Machine-39FK394S",
    "username": "admin",
    "operating_system": "Windows 10"
  },
  "something": {
    "else": 294
  }
}

This uses Newtonsoft Json.Net, however I do believe it would be hard to compose this JSON without such a library. Json.Net will handle all the conversion of various types of objects to string, plus it will handle escaping JSON delimiters. Writing this type of code yourself will be very nasty. In addition it's highly customizable and will allow datetime formats etc. to be changed.
You might need a little refinement to handle NULLs etc.
If you wish to avoid using Json.Net, you can add a reference to System.Web.Extensions and like so:
using System.Web.Script.Serialization;
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(outputObject);

A: You can use Newtonsoft.Json from NuGet to do that. ie:
var data = new
{
    device = new
    {
        name = "Machine-39FK394S",
        username = "admin",
        operating_system = "Windows 10"
    },
    something = new {_else=294}
};

var json = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);


text:
Q: Display an external web page in a width of 100px and height of 400px area I wanted to display an external web page with a width of 100px and a height of 400px area. This is the code I wrote.

      www.example.com/exmo_frame.html

But I couldn't get the height and width as I wish. Can You help me to get the correct output?

A: You will need to use iframe, you can try the following:


text:
Q: Finding number of relations on a set with 3 elements How do I find find out how many non reflexive relations X on the set P = {1, 2, 3}?
I know $2^{n^2 - n}$ returns how many reflexive relations there on a set. Do I subtract that from something to get my result?

A: A relation on set $P$ is a subset of $P\times P$.  In this case, $|P|=3$ so $|P\times P|=9$.  Hence there are $2^9$ subsets of $P\times P$, and thus $2^9$ relations on $P$.

A: Non-Reflexive relations are simply those that do not satisfy the aRa criteria for all 'a' in the corresponding set. Therefore the number of these is mostly irrelevant.
Now, Irreflexive relations are those relations such that for every a in the set, aRa is False. They are in stark contrast to reflexive relations.
Therefore, the number of irreflexive relations on a set of cardinality n is easily the difference of the total number of binary relations possible on the set and the total number of reflexive relations on the set.
=2^(n^2)-2^(n(n-1))


text:
Q: Merging Two Pandas Data-frames where two sets of criteria are met (VLOOKUP EQUIVALENT) I have been searching high and low on merging two data-frames based on meeting two criteria. Essentially what I am trying to do is vlookup from one data-frame into my main data-frame where date and ticker symbol match.
A basic version of my main data-frame called df1 looks like below. It is the stock symbols that are in an account on 5/1/2016 and 5/2/2016.
   Account_Num    Date          Symbol
0     1           2016-05-01    AAPL
1     1           2016-05-01    UA
2     1           2016-05-01    DIS
3     2           2016-05-01    CVX
4     2           2016-05-01    GOOGL
5     2           2016-05-01    PX
6     3           2016-05-01    MOS
7     3           2016-05-01    BLK
8     3           2016-05-01    TMO
9     1           2016-05-02    AAPL
10    1           2016-05-02    UA
11    1           2016-05-02    DIS
12    2           2016-05-02    CVX
13    2           2016-05-02    GOOGL
14    2           2016-05-02    PX
15    3           2016-05-02    MOS
16    3           2016-05-02    BLK
17    3           2016-05-02    TMO

My second data-frame df2 holds the prices of the stocks that are in the above accounts on 5/1/2016 and 5/2/2016, looks like this (Made up Prices):
   Date          Symbol   Price
0    2016-05-01    AAPL     99.02
1    2016-05-02    AAPL     94.00
2    2016-05-01    UA       43.00
3    2016-05-02    UA       40.67
4    2016-05-01    DIS      67.88
5    2016-05-02    DIS      70.03
6    2016-05-01    CVX      22.00
7    2016-05-02    CVX      24.47
8    2016-05-01    GOOGL    85.52
9    2016-05-02    GOOGL    84.33
10   2016-05-01    PX       44.22
11   2016-05-02    PX       47.16
12   2016-05-01    MOS      23.77
13   2016-05-02    MOS      21.56
14   2016-05-01    BLK      38.48
15   2016-05-02    BLK      41.22
16   2016-05-01    TMO      67.43
17   2016-05-02    TMO      65.11

What I want to end up with is df3 as follows:
   Account_Num    Date          Symbol    Price
0      1           2016-05-01    AAPL      99.02
1      1           2016-05-01    UA        43.00
2      1           2016-05-01    DIS       67.88
3      2           2016-05-01    CVX       22.00
4      2           2016-05-01    GOOGL     85.52
5      2           2016-05-01    PX        44.22
6      3           2016-05-01    MOS       23.77
7      3           2016-05-01    BLK       38.48
8      3           2016-05-01    TMO       67.43
9      1           2016-05-02    AAPL      94.00
10     1           2016-05-02    UA        40.67
11     1           2016-05-02    DIS       70.03
12     2           2016-05-02    CVX       24.47
13     2           2016-05-02    GOOGL     84.33
14     2           2016-05-02    PX        47.16
15     3           2016-05-02    MOS       21.56
16     3           2016-05-02    BLK       41.22
17     3           2016-05-02    TMO       65.11

The issue I am seeing is that the two data frames are different lengths, my df1 has 100,000 rows whereas df2 has 23,000. Therefore it's not as if there is a one to one match using the index. The above data-frame examples are very basic, as in the the real data different accounts hold many more stocks than other accounts. So what I think needs to happen is I need to loop through the rows in df1 and bring in the price from df2 where date and symbol match.
I have found examples on the equivalent of a vlookup in Pandas, but it is only matching on one criteria, where as I am looking for date and symbol to match and then pull in the price of the stock on that day.
If anyone knows of info out there on how to do this or has any suggestions it would be greatly appreciated
Thanks,
da4l

A: Well thanks to the hint from @Merlin I was able to do what I needed with the following:
#cretaed a new column in both data-frames concatenating the Date and Symbol variables called 'DateSym'

df1['DateSym'] = df1['Date'].map(str) + df1['Symbol']
df1

df2['DateSym'] = df1['Date'].map(str) + df1['Symbol']
df1

#then created df3 by merging the two data-frames using 'DateSym' as the index after rearranging so both data-frames had the new 'DateSym' column on the left

df3 = df1.merge(df2, on='DateSym', how='left')
df3

A: maybe this is what you want:
df3 = df1.merge(df2,on=['Symbol','Date'])
>>> df1.merge(df2,on=['Symbol','Date'])
Account_Num        Date Symbol  Price
0             1  2016-05-01   AAPL  99.02
1             1  2016-05-01     UA  43.00
2             1  2016-05-01    DIS  67.88
3             2  2016-05-01    CVX  22.00
4             2  2016-05-01  GOOGL  85.52
5             2  2016-05-01     PX  44.22
6             3  2016-05-01    MOS  23.77....


text:
Q: How to give package names to django javascript_catalog view? From django documentation:

js_info_dict = {
      'packages': ('your.app.package',), }
urlpatterns = patterns('',
      (r'^jsi18n/$', 'django.views.i18n.javascript_catalog',
  js_info_dict), )
Each string in packages should be in
  Python dotted-package syntax (the same
  format as the strings in
  INSTALLED_APPS) and should refer to a
  package that contains a locale
  directory.

It says "a package that contains a locale directory." , but i created translation files with djangoadmin.py makemessages -a and it creates locale just inside project directory. Not under any of my application directories. And i try to set packages as

js_info_dict = {
      'packages': ('my_project_dir',), }

Apparently that's not working for me. Every string from django domain gets translated but i get an empty translation catalog in javascript from javascript_catalog view. What am i missing here?

A: First you need to be sure that your js_info_dict is like this:
js_info_dict = {
    'domain': 'djangojs',
    'packages': ('my_project_name',),
}

And as @daonb suggested, add 'my_project_name' to your INSTALLED_APPS in settings.py.
Make sure that you compile your messages like this:
django-admin.py makemessages -a -d djangojs

That's all!
I don't know why Django doesn't have that information into its documentation. I could find the solution with using these articles below:
http://www.aminche.com/blog/2010/07/06/playground-editor
http://code.djangoproject.com/ticket/5494
http://osdir.com/ml/django-users/2010-04/msg00231.html

A: Try adding 'my_project_dir' to INSTALLED_APPS in settings.py

A: For others with my particular case, js messages are generated and compiled OK but not rendered in templates or pages when you use i18n language urls.
This is because javascript catalog should be added to i18n urls patterns, not to normal patterns.
urlpatterns += patterns('', (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), )

=>
urlpatterns += i18n_patterns('', (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), )


text:
Q: How to show dropdownlist dynamically I am using grid view to display data from database. There is a status column which holds 3 values. I wan the user to be able to change the value using a dropdownlist in the grid which will be visible when the user clicks on the ChangeStatus but which is present on each row.Any ideaa how to achieve this??

A: Using a hidden  that is populated with the three options, and an additional value that is the ID of the row that is being modified. Then add an onclick event handler to the status column text. When it's clicked, replace the text with the dropdown menu and set the value to the ID of the row.
The dropdown menu should have an event, onselectedindexchange, that will trigger an ajax call back to a webservice (or method) that takes in the value and the ID of the row to change. Finally, once the ajax call is made, hide the  and make the text of that cell the value (or text) of the select item selected.
Edit - some psudeo code to help you out

        Status

<select id="statusSel" >
    <option value="0"> - Select Status - </option>
    <option value="Status1">Status 1</option>
    <option value="Status1">Status 1</option>
    <option value="Status1">Status 1</option>
</select>

var statusSel = $('#statusSel');
var recordId = 0;

statusSel.change(function() {
    var newStatus = $(this).value(); //I think this is right for select

    //Ajax Call to web server (see $.ajax() in jQuery notes)
    $.ajax( /* pass newStatus and recordId */ );

    $('#hiddenDiv').html(statusSel);  //Move statusSel back to hidden div
    $(this).parent().html(newStatus); //set the span value to the new status
});

$('.select').click(function () {
    $(this).html(statusSel);
});

probably a number of ways to do this cleaner - but this should give you the rough idea.

A: Can you use jQuery in your project? If so, then you could use jQuery show() API call to make the dropdown list appear when the user clicks on the "Change Status" link/button.


text:
Q: Getting totals from tables related to a parent table - SQL I have 4 tables that T2 is related to Tb1 and other Tb3 and T4 is related to the Tb2.
as showing in the picture bellow .
what i am trying to do is to get the totals from Tb3 And Tb4 biased on the Tb1 id which is related Tb2
Sql-Query Image
SELECT        DepartmentType.Type_ID, DepartmentType.DepType, SUM(TransByDep.Amount) AS SALES, SUM(TRANSUP.Check_amount) AS PURCHASE
FROM            dep INNER JOIN
                         DepartmentType ON dep.Type_ID = DepartmentType.Type_ID INNER JOIN
                         TransByDep ON dep.Dep_ID = TransByDep.Dep_Id INNER JOIN
                         TRANSUP ON dep.Dep_ID = TRANSUP.Dep_id
GROUP BY DepartmentType.Type_ID, DepartmentType.DepType

this what i have triad but it give me wrong numbers