问:
Using position to count nodes - sometimes enumeration starts at 0 instead of 1
Hey folks,
 I've got this rather clumbsy piece of xslt which I use to transform SOAPUI test cases into a more readable format. Currently it enumerates the test cases using the following

<xsl:value-of select="position()-3"/>

My question Sometimes the test case enumeration starts at 0 and sometimes it starts at 1. I don't understand why this is happening? Is it something to do with how the position selector is implemented? Is there a neater way to count instances of a node?

Many thanks,

Richard

Here is the code in its entirety - sans styling.

`

```<code>  <!-- Edited by XMLSpy® -->
  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:con="http://eviware.com/soapui/config">
    <xsl:output method="html" encoding ="utf-8"/>
    <xsl:template match="/">
      <html>
        <head>
          <script type="text/javascript">
            function toggleDiv(divid){
                var ele = document.getElementById(divid);

                if(ele.style.display == 'none')
                    {
                        ele.style.display = 'block';
                    }
                else
                    {
                        ele.style.display = 'none';
                    }
                }
          </script>

            <style type="text/css"></style>

        </head>

        <body>

          <xsl:apply-templates/>

          <div class="help">This report is generated automatically by a scheduled job running on Richard Fortune's machine. The SOAPUI project files it references are located in sourcecontrol SVN (https://svn.xxx.xxxxxx.com/svn/network/TEST). These reports are generated daily as the projects they reference are subject to change.</div>

        </body>
      </html>

    </xsl:template>

    <xsl:template match="con:soapui-project">
     <div><h1>Project Name : <xsl:value-of select="@name"/></h1></div>
      <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="con:testSuite">

    <xsl:if test="con:description=''">
                <p class="warn"> (RICHARD - PLEASE PROVIDE A DESCRIPTION!!)</p>
    </xsl:if>
      <div id="content" onmousedown="toggleDiv('{position()}');"><h2 class="ex">TestSuite:  <xsl:value-of select="@name"/></h2></div>
      <br>
        <p class="descSuite"><b>Suite Description: </b><xsl:value-of select="con:description"/></p>
      </br>

      <div style="display:none" id="{position()}"><xsl:apply-templates />
      </div>
    </xsl:template>

    <xsl:template match="con:testCase">

        <ul>
          <li class="tc"><b>
            (#<xsl:value-of select="position()-3"/>) Testcase: </b><xsl:value-of select="@name"/>
          </li>

          <xsl:if test="con:description=''">
            <p class="warn">(Gentle reminder Richard - PLEASE PROVIDE A DESCRIPTION!!)</p>
          </xsl:if>

          <p class="descTc">
            <strong><i>Description:</i></strong> <xsl:value-of select="con:description"/>
          </p>
          <ol class="step">
          <xsl:for-each select="con:testStep"><li>TestStep: <xsl:value-of select="@name"/> </li></xsl:for-each>
          </ol>

        </ul>
        <xsl:apply-templates />

    </xsl:template>

    <xsl:template match="*"></xsl:template>

  </xsl:stylesheet>
</code>```

`

答:
The problem with position() is it can (and frequently does) include nodes you don't expect, such as text or even whitespace nodes, if whatever read the XML preserved it.

Depending on your precise requirements, you can count the number of preceding siblings (as @empo described), or it might be worth looking into the <xsl:number> instruction.

Body:
Hey folks,
 I've got this rather clumbsy piece of xslt which I use to transform SOAPUI test cases into a more readable format. Currently it enumerates the test cases using the following

<xsl:value-of select="position()-3"/>

My question Sometimes the test case enumeration starts at 0 and sometimes it starts at 1. I don't understand why this is happening? Is it something to do with how the position selector is implemented? Is there a neater way to count instances of a node?

Many thanks,

Richard

Here is the code in its entirety - sans styling.

`

  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:con="http://eviware.com/soapui/config">
    <xsl:output method="html" encoding ="utf-8"/>
    <xsl:template match="/">

          <xsl:apply-templates/>

This report is generated automatically by a scheduled job running on Richard Fortune's machine. The SOAPUI project files it references are located in sourcecontrol SVN (https://svn.xxx.xxxxxx.com/svn/network/TEST). These reports are generated daily as the projects they reference are subject to change.

    </xsl:template>

    <xsl:template match="con:soapui-project">

Project Name : <xsl:value-of select="@name"/>

      <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="con:testSuite">

    <xsl:if test="con:description=''">

 (RICHARD - PLEASE PROVIDE A DESCRIPTION!!)

    </xsl:if>

TestSuite:  <xsl:value-of select="@name"/>

Suite Description: <xsl:value-of select="con:description"/>

<xsl:apply-templates />

    </xsl:template>

    <xsl:template match="con:testCase">

            (#<xsl:value-of select="position()-3"/>) Testcase: <xsl:value-of select="@name"/>

          <xsl:if test="con:description=''">

(Gentle reminder Richard - PLEASE PROVIDE A DESCRIPTION!!)

          </xsl:if>

            Description: <xsl:value-of select="con:description"/>

          <xsl:for-each select="con:testStep">
TestStep: <xsl:value-of select="@name"/>
</xsl:for-each>

        <xsl:apply-templates />

    </xsl:template>

    <xsl:template match="*"></xsl:template>

  </xsl:stylesheet>

`


来源: stackexchange

问:
how to unsort after sorting data
I am trying to get back the original data after sorting the data here is the code, it runs very slowly:

```<code>[Rs,iR] = sort(R,1);
for j = 1:length(Rs)
   for q = 1:length(iR)
     if(iR(q) == j)
         R_org(j,1) = Rs(iR(q));

     end
end
</code>```

After using the method shown in comment, I am not getting same answer:

```<code>K>> R = [8;2;7;9;10]

R =

     8
     2
     7
     9
    10

K>> [Rs,iR] = sort(R,1)

Rs =

     2
     7
     8
     9
    10

iR =

     2
     3
     1
     4
     5

K>> R_org = Rs(iR)

R_org =

     7
     8
     2
     9
    10
</code>```

R and R_org does not match

答:
Given a list W, sorted with f, U = W(f), find g such that, W = U(g):
W -- f --> U -- g --> W

Solution:

[U, f] = sort(W);
[~, g] = sort(f);
```

("~" here means don't care)

ContentLicense: CC BY-SA 3.0

Title: how to unsort after sorting data

Body:
I am trying to get back the original data after sorting the data here is the code, it runs very slowly:

[Rs,iR] = sort(R,1);
for j = 1:length(Rs)
   for q = 1:length(iR)
     if(iR(q) == j)
         R_org(j,1) = Rs(iR(q));

     end
end

After using the method shown in comment, I am not getting same answer:

K>> R = [8;2;7;9;10]

R =

     8
     2
     7
     9
    10

K>> [Rs,iR] = sort(R,1)

Rs =

     2
     7
     8
     9
    10

iR =

     2
     3
     1
     4
     5

K>> R_org = Rs(iR)

R_org =

     7
     8
     2
     9
    10

R and R_org does not match

Body:
Given a list W, sorted with f, U = W(f), find g such that, W = U(g):
W -- f --> U -- g --> W

Solution:

[U, f] = sort(W);
[~, g] = sort(f);

("~" here means don't care)

ContentLicense: CC BY-SA 4.0


问:
Python - webscraping , get(url) taking infinite time
get is fetching information from other website , but not from this particular website "nseindia"</p>

```<code>hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko)
         Chrome/23.0.1271.64 Safari/537.11',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
         'Referer': 'https://cssspritegenerator.com',
         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
         'Accept-Encoding': 'none',
         'Accept-Language': 'en-US,en;q=0.8',
         'Connection': 'keep-alive'}

page_url = "https://www1.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-9999&symbol=BANKNIFTY&symbol=BANKNIFTY&instrument=OPTIDX&date=-&segmentLink=17"

d = get(page_url,headers =hdr)
</code>```

答:
Try requests:

pip install requests

```<code>import requests
from requests.exceptions import HTTPError

page_url = "https://www1.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-9999&symbol=BANKNIFTY&symbol=BANKNIFTY&instrument=OPTIDX&date=-&segmentLink=17"

try:
    response.headers['content-type'] = '...yours header ...'
    response = requests.get(page_url)

except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
except Exception as err:
    print(f'Other error occurred: {err}')
</code>```

Body:
get is fetching information from other website , but not from this particular website "nseindia"

hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko)
         Chrome/23.0.1271.64 Safari/537.11',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
         'Referer': 'https://cssspritegenerator.com',
         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
         'Accept-Encoding': 'none',
         'Accept-Language': 'en-US,en;q=0.8',
         'Connection': 'keep-alive'}

page_url = "https://www1.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-9999&symbol=BANKNIFTY&symbol=BANKNIFTY&instrument=OPTIDX&date=-&segmentLink=17"

d = get(page_url,headers =hdr)

Body:
Try requests:

pip install requests

import requests
from requests.exceptions import HTTPError

page_url = "https://www1.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-9999&symbol=BANKNIFTY&symbol=BANKNIFTY&instrument=OPTIDX&date=-&segmentLink=17"

try:
    response.headers['content-type'] = '...yours header ...'
    response = requests.get(page_url)

except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
except Exception as err:
    print(f'Other error occurred: {err}')


问:
BottomSheet fly away with visibility change
I have a bottom sheet with a NestedScrollView inside (see below). When I press on a FAB button, I want to make some parts in this NestedScrollView invisible. But when I change some linearlayouts visibilities to GONE, bottomsheet fly aways from the top. See here:

You can get the whole code from https://github.com/Tanrikut/BottomSheetExample

My change visibility method:

```<code>private void changeVisibility() {
    subtitleLayout.setVisibility(View.GONE);

    coordinateLayout.setVisibility(View.GONE);
    timeLayout.setVisibility(View.GONE);

}
</code>```

My NestedScrollView xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:behavior_peekHeight="120dp"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
    android:id="@+id/bottom_sheet_main">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="28dp"
            android:background="@android:color/white"
            android:animateLayoutChanges="true"
            android:orientation="vertical"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingLeft="10dp"
                android:paddingStart="10dp"
                android:paddingTop="@dimen/activity_horizontal_margin">

                <TextView
                    style="@style/TextAppearance.AppCompat.Headline"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Dandelion Chocolate"
                    android:id="@+id/title" />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="@dimen/activity_horizontal_margin"
                    android:layout_marginTop="16dp"
                    android:orientation="horizontal"
                    android:id="@+id/subtitleLayout">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/subtitle"
                        android:text="Subtitle" />

                </LinearLayout>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="@dimen/activity_horizontal_margin"
                android:id="@+id/coordinateLayout">

                <ImageButton
                    android:layout_width="24dp"
                    android:layout_height="24dp"
                    android:alpha="0.36"
                    android:src="@drawable/ic_room_24dp"
                    android:background="@null" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/activity_horizontal_margin"
                    android:layout_marginStart="@dimen/activity_horizontal_margin"
                    android:text="740, Valencia St, San Francisco, CA"
                    android:textColor="@android:color/primary_text_light"
                    android:id="@+id/bottom_sheet_coordinate" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="@dimen/activity_horizontal_margin"
                android:id="@+id/timeLayout">

                <ImageButton
                    android:layout_width="24dp"
                    android:layout_height="24dp"
                    android:alpha="0.36"
                    android:src="@drawable/ic_query_builder_24dp"
                    android:background="@null" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/activity_horizontal_margin"
                    android:layout_marginStart="@dimen/activity_horizontal_margin"
                    android:text="Wed, 10 AM - 9 PM"
                    android:textColor="@android:color/primary_text_light"
                    android:id="@+id/bottom_sheet_time" />

            </LinearLayout>

        </LinearLayout>

    </FrameLayout>
</android.support.v4.widget.NestedScrollView>
</code>```

答:
Removing the following line from my root layout solved this problem:</p>
```<code>android:animateLayoutChanges="true"
</code>```

Body:
I have a bottom sheet with a NestedScrollView inside (see below). When I press on a FAB button, I want to make some parts in this NestedScrollView invisible. But when I change some linearlayouts visibilities to GONE, bottomsheet fly aways from the top. See here:

You can get the whole code from https://github.com/Tanrikut/BottomSheetExample

My change visibility method:

private void changeVisibility() {
    subtitleLayout.setVisibility(View.GONE);

    coordinateLayout.setVisibility(View.GONE);
    timeLayout.setVisibility(View.GONE);

}

My NestedScrollView xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:behavior_peekHeight="120dp"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
    android:id="@+id/bottom_sheet_main">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="28dp"
            android:background="@android:color/white"
            android:animateLayoutChanges="true"
            android:orientation="vertical"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingLeft="10dp"
                android:paddingStart="10dp"
                android:paddingTop="@dimen/activity_horizontal_margin">

                <TextView
                    style="@style/TextAppearance.AppCompat.Headline"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Dandelion Chocolate"
                    android:id="@+id/title" />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="@dimen/activity_horizontal_margin"
                    android:layout_marginTop="16dp"
                    android:orientation="horizontal"
                    android:id="@+id/subtitleLayout">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/subtitle"
                        android:text="Subtitle" />

                </LinearLayout>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="@dimen/activity_horizontal_margin"
                android:id="@+id/coordinateLayout">

                <ImageButton
                    android:layout_width="24dp"
                    android:layout_height="24dp"
                    android:alpha="0.36"
                    android:src="@drawable/ic_room_24dp"
                    android:background="@null" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/activity_horizontal_margin"
                    android:layout_marginStart="@dimen/activity_horizontal_margin"
                    android:text="740, Valencia St, San Francisco, CA"
                    android:textColor="@android:color/primary_text_light"
                    android:id="@+id/bottom_sheet_coordinate" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="@dimen/activity_horizontal_margin"
                android:id="@+id/timeLayout">

                <ImageButton
                    android:layout_width="24dp"
                    android:layout_height="24dp"
                    android:alpha="0.36"
                    android:src="@drawable/ic_query_builder_24dp"
                    android:background="@null" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/activity_horizontal_margin"
                    android:layout_marginStart="@dimen/activity_horizontal_margin"
                    android:text="Wed, 10 AM - 9 PM"
                    android:textColor="@android:color/primary_text_light"
                    android:id="@+id/bottom_sheet_time" />

            </LinearLayout>

        </LinearLayout>

    </FrameLayout>
</android.support.v4.widget.NestedScrollView>

Body:
Removing the following line from my root layout solved this problem:

android:animateLayoutChanges="true"


问:
Autocad 2018 NETLOAD not showing my command method
I'm trying to make a plug in for Autocad 2018 with Visual Studio 2019 using .Net
Firstly, I am getting a warning in VS when the debug is "Any CPU" the bug goes off when I switch to x64.
After building the project and having the .dll file and I go to Autocad and load it using NETLOAD command, when I try to load my method or "CommandMethod" it doesn't show up.

I tried changing the .Net Framework to whatever version I have from 4.7.2 to 4.5

Tried different codes from other sources and still no results
Should I use a higher version of AutoCad? or should I use a lower version of VS like 2017?
What could be the problem?
Here's the code:

```<code>using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices.Core;

[assembly: CommandClass(typeof(Testing.Class1))]
   namespace Testing
{
    public class Class1
    {
        [CommandMethod("MyFirstCommand")]
        public void my()
        {

        Document doc=Application.DocumentManager.MdiActiveDocument;
        Database db = doc.Database;
        Editor edt = doc.Editor;

        using (Transaction trans=db.TransactionManager.StartTransaction())
        {
            try
            {

                BlockTable bt;
                bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr;
                btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                // send message to the user
                edt.WriteMessage("\nDrawing a line objet");

                Point3d pt1 = new Point3d(0, 0, 0);
                Point3d pt2 = new Point3d(100, 0, 0);

                Line ln = new Line(pt1, pt2);
                ln.ColorIndex = 1;
                btr.AppendEntity(ln);
                trans.AddNewlyCreatedDBObject(ln, true);
                trans.Commit();
            }
            catch (System.Exception e)
            {
                edt.WriteMessage("Error Encountered" + e.Message);
                trans.Abort();
            }
        }
        edt.WriteMessage("Script loaded");

    }

}
</code>```

}

答:
Check your references. I have had problems with this in the past when I have a broken or incorrect reference.

Are any of your settings for your AutoCAD references different than the settings in the below image?

Body:
I'm trying to make a plug in for Autocad 2018 with Visual Studio 2019 using .Net
Firstly, I am getting a warning in VS when the debug is "Any CPU" the bug goes off when I switch to x64.
After building the project and having the .dll file and I go to Autocad and load it using NETLOAD command, when I try to load my method or "CommandMethod" it doesn't show up.

I tried changing the .Net Framework to whatever version I have from 4.7.2 to 4.5

Tried different codes from other sources and still no results
Should I use a higher version of AutoCad? or should I use a lower version of VS like 2017?
What could be the problem?
Here's the code:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices.Core;

[assembly: CommandClass(typeof(Testing.Class1))]
   namespace Testing
{
    public class Class1
    {
        [CommandMethod("MyFirstCommand")]
        public void my()
        {

        Document doc=Application.DocumentManager.MdiActiveDocument;
        Database db = doc.Database;
        Editor edt = doc.Editor;

        using (Transaction trans=db.TransactionManager.StartTransaction())
        {
            try
            {

                BlockTable bt;
                bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr;
                btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                // send message to the user
                edt.WriteMessage("\nDrawing a line objet");

                Point3d pt1 = new Point3d(0, 0, 0);
                Point3d pt2 = new Point3d(100, 0, 0);

                Line ln = new Line(pt1, pt2);
                ln.ColorIndex = 1;
                btr.AppendEntity(ln);
                trans.AddNewlyCreatedDBObject(ln, true);
                trans.Commit();
            }
            catch (System.Exception e)
            {
                edt.WriteMessage("Error Encountered" + e.Message);
                trans.Abort();
            }
        }
        edt.WriteMessage("Script loaded");

    }

}

}


问:
Sum of a series using for loop in C
I am a complete beginner in C and learning to code on my own using the internet and i have written the following code to find the sum of the series
s= 1/1 + 2^2/2 + 3^3/3 .........
using the for loop in c.
Here is the code:

```<code>#include<stdio.h>
#include<math.h>
int main()
{
     int i,n;
     float a,b;
     printf("Enter the number of terms in the series: \n");
     scanf("%i",&n);
     for(i=1;i<=n;i++)
     {
          a=pow(i,i)/i;
          b=a+a;
     }
     printf("The sum of the series is %f\n",b);
     return 0;
}
</code>```

I am pretty sure that i am making a logical error but i seem to be too dumb or slow to figure that out so i would appreciate for someone to point that out for me. Thank you :)

答:
If B is trying to be your sum, you're going to want. b = b + a. not b = a + a.

Otherwise you're not summing your results together, you're calculating 2a.

Don't forget to initialize your variables as well.

Title: Sum of a series using for loop in C

Body:
I am a complete beginner in C and learning to code on my own using the internet and i have written the following code to find the sum of the series
s= 1/1 + 2^2/2 + 3^3/3 .........
using the for loop in c.
Here is the code:

#include<stdio.h>
#include<math.h>
int main()
{
     int i,n;
     float a,b;
     printf("Enter the number of terms in the series: \n");
     scanf("%i",&n);
     for(i=1;i<=n;i++)
     {
          a=pow(i,i)/i;
          b=a+a;
     }
     printf("The sum of the series is %f\n",b);
     return 0;
}

I am pretty sure that i am making a logical error but i seem to be too dumb or slow to figure that out so i would appreciate for someone to point that out for me. Thank you :)


问:
How to read 19bits out of 3 bytes in Swift?
I have a Data object with 20 bytes that I'm getting from a BLE device.

This is an example when I po the data in the CBCharacteristic:

```<code>▿ 20 bytes
  - count : 20
  ▿ pointer : 0x0000000282889ab0
    - pointerValue : 10779925168
  ▿ bytes : 20 elements
    - 0 : 16
    - 1 : 0
    - 2 : 0
    - 3 : 21
    - 4 : 0
    - 5 : 0
    - 6 : 20
    - 7 : 3
    - 8 : 87
    - 9 : 154
    - 10 : 3
    - 11 : 88
    - 12 : 204
    - 13 : 20
    - 14 : 255
    - 15 : 197
    - 16 : 7
    - 17 : 159
    - 18 : 56
    - 19 : 122
</code>```

Now I have instructions that tell me that on Byte 1,2,3 there is the signal that I'm looking for as 19 bits (0-524288)

So how can I get that signal value?

I would appreciate reading material on how to get this on my own if necessary. I don't have a proper CS background and I'm lost on how/where to even look for this.

Thank you

EDIT (in response to @Sweeper):

These are instructions for Byte 0

```<code>General state / configuration. Contains following bits:
7 (highest) – Error state, reads 0 normally and 1 if any error in hardware side
6 – button pressed (’1’ – button is pressed, ’0’ – button is not pressed)
5 – USB connected (’1’ – USB is connected, ’0’ – USB is not connected)
4 – Charging/charged (’1’ – Charging, ’0’ – not charging)
3 – Gain of channel A. 2 gains (0 is slower, 1 is higher)
2 – Gain of channel B. 2 gains (0 is slower, 1 is higher)
1 – Gain of channel C. 2 gains (0 is slower, 1 is higher)
0 – Gain of channel D. 2 gains (0 is slower, 1 is higher)
</code>```

And by doing this I can get the expected data for the first byte:

```<code>guard let data = characteristic.value else { return }
guard data.count == 20 else { return }
let val = [UInt8](data)
let general:UInt8 = val[0]
let error = general >> 7 & 1
let buttonPressed = general >> 6 & 1
let usbConnected = general >> 5 & 1
let charging = general >> 4 & 1
let gainChannelA = general >> 3 & 1
let gainChannelB = general >> 2 & 1
let gainChannelC = general >> 1 & 1
let gainChannelD = general >> 0 & 1
</code>```

Does this help in knowing the endianness of the protocol?

答:
Since the data comes from multiple bytes, the answer depends on the endianness implied by the protocol. These 19 bits use two full bytes and three bits in a third byte.

If these three bytes are stored in unsigned 8-bit variables a, b, and c, the value would be either

```<code>Int(a) << 11 + Int(b) << 3 + Int(c) & 0x07
</code>```

or

```<code>Int(c) << 11 + Int(b) << 3 + Int(a) & 0x07
</code>```

values for a b and c would come either from bytes 1, 2, and 3 or bytes 3, 2, 1, depending on the order specified in the protocol.

Note: Expression x & 0x07 means "three lower bits", because 0x07 hex is 00000111 in binary.

Body:
I have a Data object with 20 bytes that I'm getting from a BLE device.

This is an example when I po the data in the CBCharacteristic:

▿ 20 bytes
  - count : 20
  ▿ pointer : 0x0000000282889ab0
    - pointerValue : 10779925168
  ▿ bytes : 20 elements
    - 0 : 16
    - 1 : 0
    - 2 : 0
    - 3 : 21
    - 4 : 0
    - 5 : 0
    - 6 : 20
    - 7 : 3
    - 8 : 87
    - 9 : 154
    - 10 : 3
    - 11 : 88
    - 12 : 204
    - 13 : 20
    - 14 : 255
    - 15 : 197
    - 16 : 7
    - 17 : 159
    - 18 : 56
    - 19 : 122

Now I have instructions that tell me that on Byte 1,2,3 there is the signal that I'm looking for as 19 bits (0-524288)

So how can I get that signal value?

I would appreciate reading material on how to get this on my own if necessary. I don't have a proper CS background and I'm lost on how/where to even look for this.

Thank you

EDIT (in response to @Sweeper):

These are instructions for Byte 0

General state / configuration. Contains following bits:
7 (highest) – Error state, reads 0 normally and 1 if any error in hardware side
6 – button pressed (’1’ – button is pressed, ’0’ – button is not pressed)
5 – USB connected (’1’ – USB is connected, ’0’ – USB is not connected)
4 – Charging/charged (’1’ – Charging, ’0’ – not charging)
3 – Gain of channel A. 2 gains (0 is slower, 1 is higher)
2 – Gain of channel B. 2 gains (0 is slower, 1 is higher)
1 – Gain of channel C. 2 gains (0 is slower, 1 is higher)
0 – Gain of channel D. 2 gains (0 is slower, 1 is higher)

And by doing this I can get the expected data for the first byte:

guard let data = characteristic.value else { return }
guard data.count == 20 else { return }
let val = [UInt8](data)
let general:UInt8 = val[0]
let error = general >> 7 & 1
let buttonPressed = general >> 6 & 1
let usbConnected = general >> 5 & 1
let charging = general >> 4 & 1
let gainChannelA = general >> 3 & 1
let gainChannelB = general >> 2 & 1
let gainChannelC = general >> 1 & 1
let gainChannelD = general >> 0 & 1

Does this help in knowing the endianness of the protocol?

Body:
Since the data comes from multiple bytes, the answer depends on the endianness implied by the protocol. These 19 bits use two full bytes and three bits in a third byte.

If these three bytes are stored in unsigned 8-bit variables a, b, and c, the value would be either

Int(a) << 11 + Int(b) << 3 + Int(c) & 0x07

or

Int(c) << 11 + Int(b) << 3 + Int(a) & 0x07

values for a b and c would come either from bytes 1, 2, and 3 or bytes 3, 2, 1, depending on the order specified in the protocol.

Note: Expression x & 0x07 means "three lower bits", because 0x07 hex is 00000111 in binary.


问:
Server send message to client Sockets
I started working with sockets this week and I'm having a hard time.
My goal is when the client sent a message the server responded with a notification.
On the client side sending to the server has no problem, but when the server sends to the client nothing appears.
Can anybody help me with this problem?

Client:

```<code>    Thread thread = new Thread(new myServerThread());
    thread.start();

class myServerThread implements Runnable {
    Socket socket;
    ServerSocket serverSocket;
    InputStreamReader inputStreamReader;
    BufferedReader bufferedReader;
    String message;
    Handler handler = new Handler();

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(5000);
            while (true){
                socket = serverSocket.accept();
                inputStreamReader = new InputStreamReader(socket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader);
                message = bufferedReader.readLine();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), message,Toast.LENGTH_LONG).show();
                        }
                    });
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
}
</code>```

SERVER:

```<code> String EMAIL = "Email";

   try {
       serverSocket = new ServerSocket(6000);
       while(true){
       socket = serverSocket.accept();
       inputStreamReader = new InputStreamReader(socket.getInputStream());
       bufferedReader = new BufferedReader(inputStreamReader);
       email = bufferedReader.readLine();

       System.out.println(email);

       if(email.equals(EMAIL)){
           jTextArea1.setText(email);
           try {
            socket = new Socket("localHost", 5000);
            PrintWriter  printWriter = new PrintWriter(socket.getOutputStream());
            printWriter.write(message);
            printWriter.flush();
            printWriter.close();
            System.out.println("connected");

        } catch (IOException e) {
            e.printStackTrace();
        }

       }else{
       }

       }

   } catch (IOException ex) {
   }
    etEmail = findViewById(R.id.etvEmail);
</code>```

答:
First the short answer: Your Java codes are both working almost fine.

Anyway, you should always test your application against another program that is known to be OK. By testing one self-written program against another fresh self-written program, it is difficult to say which of both is broken. It seems that you are testing it with some GUI (Android?). Transforming the relevant part to a simple console application which you run on a regular PC makes troubleshooting much easier.

So let me show how I checked your code on my Linux laptop:

First copy your "client" code into a "Hello-World" template. I added some debug messages and a loop which allows the client to receive more than one single line of text:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

class Main
{

    static class myServerThread implements Runnable
    {
        Socket socket;
        ServerSocket serverSocket;
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        String message;

        @Override
        public void run()
        {
            try
            {
                serverSocket = new ServerSocket(5000);
                while (true)
                {
                    System.out.println("Accepting...");
                    socket = serverSocket.accept();
                    System.out.println("Connected...");
                    inputStreamReader = new InputStreamReader(socket.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader);
                    String message = bufferedReader.readLine();
                    while (message!=null)
                    {
                        System.out.println("Received:" + message);
                        message = bufferedReader.readLine();
                    }
                    System.out.println("Closing...");
                    socket.close();
                }

            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        Thread thread = new Thread(new myServerThread());
        thread.start();
    }
}
</code>```

I started the "client" and opened another command window to open a network connection with Netcat and send two lines of text:

```<code>nc localhost 5000
Hallo
Test
</code>```

The related output of the "client" program was:

```<code>Accepting...
Connected...
Received:Hallo
Received:Test
Closing...
Accepting...
</code>```

So the "client" part is running fine obviously.

Next I copied your "server" code into a "Hello World" template:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

class Main
{

    static class myServerThread implements Runnable
    {
        Socket socket;
        ServerSocket serverSocket;
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        String message;

        @Override
        public void run()
        {
            String EMAIL = "Email";

            try
            {
                serverSocket = new ServerSocket(6000);
                while (true)
                {
                    System.out.println("Accepting...");
                    socket = serverSocket.accept();
                    System.out.println("Connected...");
                    inputStreamReader = new InputStreamReader(socket.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader);

                    String message = bufferedReader.readLine();
                    while (message != null)
                    {
                        System.out.println("Received:" + message);

                        if (message.equals(EMAIL))
                        {
                            System.out.println("Sending...");
                            try
                            {
                                socket = new Socket("localHost", 5000);
                                PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
                                printWriter.write(message);
                                printWriter.flush();
                                printWriter.close();
                                System.out.println("sending done");

                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                            }

                        }
                        message = bufferedReader.readLine();
                    }
                    System.out.println("Closing...");
                    socket.close();
                }
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        Thread thread = new Thread(new myServerThread());
        thread.start();
    }
}
</code>```

Again I added some debug messages and a loop, so the server can receive multiple lines of text. Since this Java program handles two connections, I had to open two command windows.

In the first command window I tell NetCat to accept (listen) connection on port 5000. That is where your "server" will send the "Email" message to:

```<code>nc -lp 5000
</code>```

In the second command window I tell Netcat to connect to your "server" on port 6000, then I send two lines of text and then I press Ctrl-C to stop it:

```<code>nc localhost 6000
Test
Email
^C
</code>```

The related output of the "server" program is:

```<code>Accepting...
Connected...
Received:Test
Received:Email
Sending...
sending done
Closing...
Accepting...
</code>```

And my listening Netcat in the other (first) command windows produced this output:

```<code>stefan@stefanpc:/hdd/stefan$ nc -lp 5000
Emailstefan@stefanpc:/hdd/stefan$
</code>```

So everything looks fine on my machine. Beside one small detail: There is no line break after the "Email" that your "server" sends to the client (in this case NetCat). So the fix is simple:

```<code>printWriter.write(message+"\n");
</code>```

This final line break is required because your client consumes the input by readLine().

NetCat is a very helpful tool to test plain text TCP socket communication. It is included in all Linux distributions. If you have difficulties to find a Windows executable, then take it from my homepage: http://stefanfrings.de/avr_tools/netcat-win32-1.12.zip

Please comment if that was helpful to you.

Title: Server send message to client Sockets

Body:
I started working with sockets this week and I'm having a hard time.
My goal is when the client sent a message the server responded with a notification.
On the client side sending to the server has no problem, but when the server sends to the client nothing appears.
Can anybody help me with this problem?

Client:

    Thread thread = new Thread(new myServerThread());
    thread.start();

class myServerThread implements Runnable {
    Socket socket;
    ServerSocket serverSocket;
    InputStreamReader inputStreamReader;
    BufferedReader bufferedReader;
    String message;
    Handler handler = new Handler();

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(5000);
            while (true){
                socket = serverSocket.accept();
                inputStreamReader = new InputStreamReader(socket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader);
                message = bufferedReader.readLine();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), message,Toast.LENGTH_LONG).show();
                        }
                    });
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
}

SERVER:

 String EMAIL = "Email";

   try {
       serverSocket = new ServerSocket(6000);
       while(true){
       socket = serverSocket.accept();
       inputStreamReader = new InputStreamReader(socket.getInputStream());
       bufferedReader = new BufferedReader(inputStreamReader);
       email = bufferedReader.readLine();

       System.out.println(email);

       if(email.equals(EMAIL)){
           jTextArea1.setText(email);
           try {
            socket = new Socket("localHost", 5000);
            PrintWriter  printWriter = new PrintWriter(socket.getOutputStream());
            printWriter.write(message);
            printWriter.flush();
            printWriter.close();
            System.out.println("connected");

        } catch (IOException e) {
            e.printStackTrace();
        }

       }else{
       }

       }

   } catch (IOException ex) {
   }
    etEmail = findViewById(R.id.etvEmail);

Body:
First the short answer: Your Java codes are both working almost fine.

Anyway, you should always test your application against another program that is known to be OK. By testing one self-written program against another fresh self-written program, it is difficult to say which of both is broken. It seems that you are testing it with some GUI (Android?). Transforming the relevant part to a simple console application which you run on a regular PC makes troubleshooting much easier.

So let me show how I checked your code on my Linux laptop:

First copy your "client" code into a "Hello-World" template. I added some debug messages and a loop which allows the client to receive more than one single line of text:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

class Main
{

    static class myServerThread implements Runnable
    {
        Socket socket;
        ServerSocket serverSocket;
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        String message;

        @Override
        public void run()
        {
            try
            {
                serverSocket = new ServerSocket(5000);
                while (true)
                {
                    System.out.println("Accepting...");
                    socket = serverSocket.accept();
                    System.out.println("Connected...");
                    inputStreamReader = new InputStreamReader(socket.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader);
                    String message = bufferedReader.readLine();
                    while (message!=null)
                    {
                        System.out.println("Received:" + message);
                        message = bufferedReader.readLine();
                    }
                    System.out.println("Closing...");
                    socket.close();
                }

            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        Thread thread = new Thread(new myServerThread());
        thread.start();
    }
}

I started the "client" and opened another command window to open a network connection with Netcat and send two lines of text:

nc localhost 5000
Hallo
Test

The related output of the "client" program was:

Accepting...
Connected...
Received:Hallo
Received:Test
Closing...
Accepting...

So the "client" part is running fine obviously.

Next I copied your "server" code into a "Hello World" template:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

class Main
{

    static class myServerThread implements Runnable
    {
        Socket socket;
        ServerSocket serverSocket;
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        String message;

        @Override
        public void run()
        {
            String EMAIL = "Email";

            try
            {
                serverSocket = new ServerSocket(6000);
                while (true)
                {
                    System.out.println("Accepting...");
                    socket = serverSocket.accept();
                    System.out.println("Connected...");
                    inputStreamReader = new InputStreamReader(socket.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader);

                    String message = bufferedReader.readLine();
                    while (message != null)
                    {
                        System.out.println("Received:" + message);

                        if (message.equals(EMAIL))
                        {
                            System.out.println("Sending...");
                            try
                            {
                                socket = new Socket("localHost", 5000);
                                PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
                                printWriter.write(message);
                                printWriter.flush();
                                printWriter.close();
                                System.out.println("sending done");

                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                            }

                        }
                        message = bufferedReader.readLine();
                    }
                    System.out.println("Closing...");
                    socket.close();
                }
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        Thread thread = new Thread(new myServerThread());
        thread.start();
    }
}

Again I added some debug messages and a loop, so the server can receive multiple lines of text. Since this Java program handles two connections, I had to open two command windows.

In the first command window I tell NetCat to accept (listen) connection on port 5000. That is where your "server" will send the "Email" message to:

nc -lp 5000

In the second command window I tell Netcat to connect to your "server" on port 6000, then I send two lines of text and then I press Ctrl-C to stop it:

nc localhost 6000
Test
Email
^C

The related output of the "server" program is:

Accepting...
Connected...
Received:Test
Received:Email
Sending...
sending done
Closing...
Accepting...

And my listening Netcat in the other (first) command windows produced this output:

stefan@stefanpc:/hdd/stefan$ nc -lp 5000
Emailstefan@stefanpc:/hdd/stefan$

So everything looks fine on my machine. Beside one small detail: There is no line break after the "Email" that your "server" sends to the client (in this case NetCat). So the fix is simple:

printWriter.write(message+"\n");

This final line break is required because your client consumes the input by readLine().

NetCat is a very helpful tool to test plain text TCP socket communication. It is included in all Linux distributions. If you have difficulties to find a Windows executable, then take it from my homepage: http://stefanfrings.de/avr_tools/netcat-win32-1.12.zip

Please comment if that was helpful to you.


问:
Looping though a file in bash and filtering for a directory name beginning
I'm really new to bash scripting and I am trying to write a bash script to use with subversion hooks.

The goal is to get a list of the java projects that were comitted, then write that list to a file (so I can create a change log from it and display it inside an application) along some other information gathered using svnlook that I've already worked out.

Since subversion itself doesn't really care for projects that I commit in eclipse and instead works with directories, I have to use the "svnlook changed" command which spits out each and every file with its full path that was included in the commit.

Here's an example of what "svnlook changed" returns:

```<code>U   Project/branches/11.4.11.001/LIB1/com/some/other/directory/some_java_class.java
U   Project/branches/11.4.11.001/LIB2/com/some/other/directory/another_thingy.java
U   Project/branches/11.4.11.001/new/directories/LIB1/com/something/some_java_class.java
U   Project/branches/11.4.11.001/PRJ1/com/directory/some_java_class.java
</code>```

Now I can't guarantee that this directory structure will always be the same, so what I want to do is to find the java project names by filtering for "PRJ" and "LIB", since they will always begin with those letters and I can be sure this will not change.

So what I am trying to do in the script:

Step 1: Put the output of "svnlook changed" into a file:

```<code>tempfile=/data/svn/scratch.txt
input=/data/svn/scratch2.txt
touch $tempfile
touch $input

$SVNLOOK changed -r "$REVISION" "$REPOS" >> $input
</code>```

This works.

Step 2: iterate over every line of the file, get the substring that represents the project by looking for "LIB" or "PRJ" in the path. Write these into a file. For now I am just assuming there are no more than 9 child directories and I am looping over the path 10 times to look at each:

```<code>for i in {1..10}
do
        cat $input | cut -d "/" -f $i | grep -i -s -e PRJ -e LIB | tr [:lower:]äöü [:upper:]ÄÖÜ >> $tempfile
done
</code>```

This doesn't work in the script. The file at /data/svn/scratch.txt is always empty. When I run the command from the command line and replace $input and $i, it works and all of the following commands work, too.

Step 3: Set all the other variables. I iterate over the temporary file, filtering out the duplicates and putting commas to seperate them:

```<code>DATE=$(date '+%d-%m-%Y')
REVISION=$($SVNLOOK youngest "$REPOS")
CHANGEDPRJ=$(cat $tempfile | sort -u |  xargs | sed -e 's/ /, /g')
COMMENT=$($SVNLOOK log -t "$TXN" "$REPOS")
</code>```

Step 4:Output this variable along other stuff into the file in which I'd like to store it all:

```<code>echo "$DATE" , "$REVISION" , "$CHANGEDPRJ" , "$COMMENT" >> /data/svn/commit.log
</code>```

So right now I am getting:

17-02-2020 , 571 ,  , Cleanup of outdated comments

Instead of:

17-02-2020 , 571 , LIB1,LIB2,PRJ1 , Cleanup of outdated comments

I'm pretty sure there is a very obvious and easy solution to get this working, but I'm bash scripting for the very first time today and I can't seem to google for the right thing to find out what I'm doing wrong.... If someone could point me into the right direction that'd be amazing!

答:
The following:

```<code>cat <<EOF |
U   Project/branches/11.4.11.001/LIB1/com/some/other/directory/some_java_class.java
U   Project/branches/11.4.11.001/LIB2/com/some/other/directory/another_thingy.java
U   Project/branches/11.4.11.001/new/directories/LIB1/com/something/some_java_class.java
U   Project/branches/11.4.11.001/PRJ1/com/directory/some_java_class.java
EOF
# remove the U<space><space>
sed 's/^U  //' |
# replace `/` with a newline
tr '/' '\n' |
# grep only lines with PRJ and LIB
grep -e 'PRJ\|LIB' |
# sort unique
sort -u |
# join elements with a comma
paste -sd,
</code>```

outputs:

```<code>LIB1,LIB2,PRJ1
</code>```

So you want:

```<code>"$SVNLOOK" changed -r "$REVISION" "$REPOS" |
sed 's/^U  //' | tr '/' '\n' | grep -e 'PRJ\|LIB' | sort -u | paste -sd,
</code>```

Note: remember to quote variable expansions. Don't touch $tempfile do touch "$tempfile".

Body:
I'm really new to bash scripting and I am trying to write a bash script to use with subversion hooks.

The goal is to get a list of the java projects that were comitted, then write that list to a file (so I can create a change log from it and display it inside an application) along some other information gathered using svnlook that I've already worked out.

Since subversion itself doesn't really care for projects that I commit in eclipse and instead works with directories, I have to use the "svnlook changed" command which spits out each and every file with its full path that was included in the commit.

Here's an example of what "svnlook changed" returns:

U   Project/branches/11.4.11.001/LIB1/com/some/other/directory/some_java_class.java
U   Project/branches/11.4.11.001/LIB2/com/some/other/directory/another_thingy.java
U   Project/branches/11.4.11.001/new/directories/LIB1/com/something/some_java_class.java
U   Project/branches/11.4.11.001/PRJ1/com/directory/some_java_class.java

Now I can't guarantee that this directory structure will always be the same, so what I want to do is to find the java project names by filtering for "PRJ" and "LIB", since they will always begin with those letters and I can be sure this will not change.

So what I am trying to do in the script:

Step 1: Put the output of "svnlook changed" into a file:

tempfile=/data/svn/scratch.txt
input=/data/svn/scratch2.txt
touch $tempfile
touch $input

$SVNLOOK changed -r "$REVISION" "$REPOS" >> $input

This works.

Step 2: iterate over every line of the file, get the substring that represents the project by looking for "LIB" or "PRJ" in the path. Write these into a file. For now I am just assuming there are no more than 9 child directories and I am looping over the path 10 times to look at each:

for i in {1..10}
do
        cat $input | cut -d "/" -f $i | grep -i -s -e PRJ -e LIB | tr [:lower:]äöü [:upper:]ÄÖÜ >> $tempfile
done

This doesn't work in the script. The file at /data/svn/scratch.txt is always empty. When I run the command from the command line and replace $input and $i, it works and all of the following commands work, too.

Step 3: Set all the other variables. I iterate over the temporary file, filtering out the duplicates and putting commas to seperate them:

DATE=$(date '+%d-%m-%Y')
REVISION=$($SVNLOOK youngest "$REPOS")
CHANGEDPRJ=$(cat $tempfile | sort -u |  xargs | sed -e 's/ /, /g')
COMMENT=$($SVNLOOK log -t "$TXN" "$REPOS")

Step 4:Output this variable along other stuff into the file in which I'd like to store it all:

echo "$DATE" , "$REVISION" , "$CHANGEDPRJ" , "$COMMENT" >> /data/svn/commit.log

So right now I am getting:

17-02-2020 , 571 ,  , Cleanup of outdated comments

Instead of:

17-02-2020 , 571 , LIB1,LIB2,PRJ1 , Cleanup of outdated comments

I'm pretty sure there is a very obvious and easy solution to get this working, but I'm bash scripting for the very first time today and I can't seem to google for the right thing to find out what I'm doing wrong.... If someone could point me into the right direction that'd be amazing!

Body:
The following:

cat <<EOF |
U   Project/branches/11.4.11.001/LIB1/com/some/other/directory/some_java_class.java
U   Project/branches/11.4.11.001/LIB2/com/some/other/directory/another_thingy.java
U   Project/branches/11.4.11.001/new/directories/LIB1/com/something/some_java_class.java
U   Project/branches/11.4.11.001/PRJ1/com/directory/some_java_class.java
EOF
# remove the U<space><space>
sed 's/^U  //' |
# replace `/` with a newline
tr '/' '\n' |
# grep only lines with PRJ and LIB
grep -e 'PRJ\|LIB' |
# sort unique
sort -u |
# join elements with a comma
paste -sd,

outputs:

LIB1,LIB2,PRJ1

So you want:

"$SVNLOOK" changed -r "$REVISION" "$REPOS" |
sed 's/^U  //' | tr '/' '\n' | grep -e 'PRJ\|LIB' | sort -u | paste -sd,

Note: remember to quote variable expansions. Don't touch $tempfile do touch "$tempfile".


问:
CustomBinding for this BasicHttpBinding?
I am having hard time converting a BasicHttpBinding to custom binding. Specifically I need to convert the security element-

```<code><basicHttpBinding>
 <binding name="MySecureBasicHttpBinding">
  <security mode="TransportWithMessageCredential">
   <transport clientCredentialType="None" proxyCredentialType="None" />
   <message clientCredentialType="UserName" algorithmSuite="Default" />
  </security>
 </binding>
</basicHttpBinding>
</code>```

Can anyone help write the same in custom binding?
Please also refer to post\doc, from where I can find out the correspondence between the security mode & values as in basicHttpBinding and those in custom bindings.

Thanks

答:
Try this:</p>

```<code><customBinding>
  <binding name="UsernamePasswordOverHttps">
    <security
      authenticationMode="UserNameOverTransport"
      messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" />
    <textMessageEncoding messageVersion="Soap11" />
    <httpsTransport />
  </binding>
</customBinding>
</code>```

Body:
I am having hard time converting a BasicHttpBinding to custom binding. Specifically I need to convert the security element-

<basicHttpBinding>
 <binding name="MySecureBasicHttpBinding">
  <security mode="TransportWithMessageCredential">
   <transport clientCredentialType="None" proxyCredentialType="None" />
   <message clientCredentialType="UserName" algorithmSuite="Default" />
  </security>
 </binding>
</basicHttpBinding>

Can anyone help write the same in custom binding?
Please also refer to post\doc, from where I can find out the correspondence between the security mode & values as in basicHttpBinding and those in custom bindings.

Thanks

Body:
Try this:

<customBinding>
  <binding name="UsernamePasswordOverHttps">
    <security
      authenticationMode="UserNameOverTransport"
      messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" />
    <textMessageEncoding messageVersion="Soap11" />
    <httpsTransport />
  </binding>
</customBinding>


问:
Understanding the "where" and how to use it in Ruby on Rails
I have a table named product_variations, and this table has_many products.

When I go to Rails console, I can do this:

```<code>2.6.3 :036 > var = ProductVariation.first
  ProductVariation Load (0.2ms)  SELECT `product_variations`.* FROM `product_variations` ORDER BY `product_variations`.`id` ASC LIMIT 1
 => #<ProductVariation id: 16, product_id: 1024, color_id: 19, quantity: 1, size: "GG", sub_sku: 10, created_at: "2020-02-18 14:41:46", updated_at: "2020-02-18 14:41:46">
2.6.3 :037 > var.size
 => "GG"
</code>```

So, that's working. But when I try to find something there using where, I got this intead:

```<code>2.6.3 :038 > var = ProductVariation.where(product_id: 1024, sub_sku: 10)
  ProductVariation Load (0.4ms)  SELECT `product_variations`.* FROM `product_variations` WHERE `product_variations`.`product_id` = 1024 AND `product_variations`.`sub_sku` = 10 LIMIT 11
 => #<ActiveRecord::Relation [#<ProductVariation id: 16, product_id: 1024, color_id: 19, quantity: 1, size: "GG", sub_sku: 10, created_at: "2020-02-18 14:41:46", updated_at: "2020-02-18 14:41:46">]>
2.6.3 :039 > var.size
   (0.2ms)  SELECT COUNT(*) FROM `product_variations` WHERE `product_variations`.`product_id` = 1024 AND `product_variations`.`sub_sku` = 10
 => 1
</code>```

Note that when I try to use var.size, the console do another search at the database, but now using SELECT COUNT(*) instead of just SELECT, and the output is 1 (while should be GG, why?). For what I understood until now, where can return many results. Thats why it uses COUNT? But how can I use the result? In this app I'm working at, on the product_variations table I'll have only one single match with product_id and sub_sku so I want it to return this line, but can't figure out how to use where to do this.

答:
you can use .first after the where

```<code>var = ProductVariation.where(product_id: 1024, sub_sku: 10).first
</code>```

or use the find_by method

```<code>var = ProductVariation.find_by(product_id: 1024, sub_sku: 10)
</code>```

which will do the same thing

Body:
I have a table named product_variations, and this table has_many products.

When I go to Rails console, I can do this:

2.6.3 :036 > var = ProductVariation.first
  ProductVariation Load (0.2ms)  SELECT `product_variations`.* FROM `product_variations` ORDER BY `product_variations`.`id` ASC LIMIT 1
 => #<ProductVariation id: 16, product_id: 1024, color_id: 19, quantity: 1, size: "GG", sub_sku: 10, created_at: "2020-02-18 14:41:46", updated_at: "2020-02-18 14:41:46">
2.6.3 :037 > var.size
 => "GG"

So, that's working. But when I try to find something there using where, I got this intead:

2.6.3 :038 > var = ProductVariation.where(product_id: 1024, sub_sku: 10)
  ProductVariation Load (0.4ms)  SELECT `product_variations`.* FROM `product_variations` WHERE `product_variations`.`product_id` = 1024 AND `product_variations`.`sub_sku` = 10 LIMIT 11
 => #<ActiveRecord::Relation [#<ProductVariation id: 16, product_id: 1024, color_id: 19, quantity: 1, size: "GG", sub_sku: 10, created_at: "2020-02-18 14:41:46", updated_at: "2020-02-18 14:41:46">]>
2.6.3 :039 > var.size
   (0.2ms)  SELECT COUNT(*) FROM `product_variations` WHERE `product_variations`.`product_id` = 1024 AND `product_variations`.`sub_sku` = 10
 => 1

Note that when I try to use var.size, the console do another search at the database, but now using SELECT COUNT(*) instead of just SELECT, and the output is 1 (while should be GG, why?). For what I understood until now, where can return many results. Thats why it uses COUNT? But how can I use the result? In this app I'm working at, on the product_variations table I'll have only one single match with product_id and sub_sku so I want it to return this line, but can't figure out how to use where to do this.

Body:
you can use .first after the where

var = ProductVariation.where(product_id: 1024, sub_sku: 10).first

or use the find_by method

var = ProductVariation.find_by(product_id: 1024, sub_sku: 10)

which will do the same thing


答: Perhaps you are missing a declaration b=0, b=b+a...</p>

Title: Sum of a series using for loop in C


问:
Python Subprocess Invalid Syntax when passing variable to function
I have a python script and want to call a subprocess from it.
The following example works completely fine:

Script1:

```<code>from subprocess import Popen

p = Popen('python Script2.py', shell=True)
</code>```

Script2:

```<code>def execute():
    print('works!')

execute()
</code>```

However as soon as I want to pass a variable to the function, I get the following error:

```<code>def execute(random_variable: str):

SyntaxError: invalid syntax
</code>```

Script1:

```<code>from subprocess import Popen

p = Popen('python Script2.py', shell=True)
</code>```

Script2:

```<code>def execute(random_variable: str):
    print(random_variable)

execute(random_variable='does not work')
</code>```

Does anyone have an idea why that could be the case? Couldn't find anything about it online :(

答:
ok guys, found the solution: just use 'python3' instead of 'python' if you are on mac...:

p = Popen('python3 Script2.py', shell=True)

Thank you for your helpfulness! :)

Body:
I have a python script and want to call a subprocess from it.
The following example works completely fine:

Script1:

from subprocess import Popen

p = Popen('python Script2.py', shell=True)

Script2:

def execute():
    print('works!')

execute()

However as soon as I want to pass a variable to the function, I get the following error:

def execute(random_variable: str):

SyntaxError: invalid syntax

Script1:

from subprocess import Popen

p = Popen('python Script2.py', shell=True)

Script2:

def execute(random_variable: str):
    print(random_variable)

execute(random_variable='does not work')

Does anyone have an idea why that could be the case? Couldn't find anything about it online :(


问:
How to use withLatestFrom with a selector in ngrx?
I have ngrx application, and I can't get the value from a selector in the effect, by the payload I sent in the component.

I write an example code of what I deal with:

This is my state, a simple docs array in it.

```<code>export const initialState = {
  docs: [{ id: 1, name: "doc1" }, { id: 2, name: "doc2" }]
};

export const reducer = createReducer(
  initialState,
);
</code>```

I dont handle any action for this questions, this is not the issue.

In my component I get the array using a selector:

```<code>docs$ = this.store.pipe(select(fromStore.getAllDocs));

{{docs$ | async | json}}
</code>```

the reducer:

```<code>export const selectDocsState = createFeatureSelector("docs");

export const selectDocsStatusState = createSelector(
  selectDocsState,
  state => state["docs"]
);

export const getAllDocs = createSelector(
  selectDocsStatusState,
  getDocs
)
</code>```

I also have a selector to get by id:

```<code>{{docsById$ | async | json }}

docsById$ = this.store.pipe(select(fromStore.getById, { id: 1 }));
</code>```

in the reducer:

```<code>export const getById = createSelector(
  selectDocsStatusState,
  getDocs,
  (state, docs, props) => {
    console.log({ props });
    return docs.docs.docs.filter(d => d.id === props.id);
  }
)
</code>```

So far everything good. I get the docs array and display it.

Now, in my component I dispatch some action and catch by effect:

```<code>this.store.dispatch({ type: 'GET_DOC', payload: { id: 2 } });
</code>```

And in the effect I want to know if this id is in the store or not.

So I use withLatestFrom from rxjs with the getById selector.

```<code>withLatestFrom((a: any) =>
  this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
),
</code>```

The problem is i'm not getting the value from the selector instend I get the store instance.

```<code>tap(v => {
  console.log({ v });
}),
</code>```

The full effect:

```<code>getDoc$ = createEffect(() =>
    this.actions$.pipe(
      ofType("GET_DOC"),
      map(a => a),
      tap(a => {
        console.log({ a });
      }),
      withLatestFrom((a: any) =>
        this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
      ),
      tap(v => {
        console.log({ v }); // <--------------- HERE SHOULD BE THE DOC AND THE ACTION.PAYLOAD, v[0].a.payload, v[1].id
      }),
      exhaustMap(payload => {
        return of({ type: "SOME_ACTION", payload: null });
      })
    )
  );
</code>```

Here is my full example in stackbliz.

What do I missing here?

答:
Warning - I’d use concatLatestFrom as per ngrx docs and Vincent’s answer. I don’t think this should be upvoted / accepted answer but can’t delete.

Original post:

This is covered in the NgRx Docs - Incorporating State but I found Brandon Roberts github comment more useful:

There are two predominant things you do when listening to an action after using the ofType operator:

```<code>actions.pipe(
 ofType('SOME_ACTION')
 someMap(action => doSomething(action))
)
</code>```

and

```<code>actions.pipe(
 ofType('SOME_ACTION'),
 withLatestFrom(store.select(someThing)),
 someMap(([action, latest]) => doSomething(action, latest))
)
</code>```

These have two different behaviors as far as effects are concerned. The first one doesn't do anything until the action is dispatched, which is what it should do.

The second one immediately subscribes to the withLatestFrom whether the action is dispatched yet or not. If that state used by the selector is not initialized yet, you could get an error you're not expecting. In order to make it "lazy" you end up having to nest it within a flattening observable operator.

```<code>actions.pipe(
 ofType('SOME_ACTION'),
 someMap(action =>
  of(action).pipe(
    withLatestFrom(store.select(someThing)),
    someMap(([action, latest]) => doSomething(action, latest))
   )
)
</code>```

Applying this gives the following:

```<code>  getDoc$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(fromDocs.getDocument),
      switchMap(action =>
        of(action).pipe(
          withLatestFrom(
            this.store.select(fromDocs.getById, { id: action.payload.id })
          ),
          map(([action, latest]) => {
            return fromDocs.someAction();
          })
        )
      )
    );
  });
</code>```

Stackblitz

Body:
I have ngrx application, and I can't get the value from a selector in the effect, by the payload I sent in the component.

I write an example code of what I deal with:

This is my state, a simple docs array in it.

export const initialState = {
  docs: [{ id: 1, name: "doc1" }, { id: 2, name: "doc2" }]
};

export const reducer = createReducer(
  initialState,
);

I dont handle any action for this questions, this is not the issue.

In my component I get the array using a selector:

docs$ = this.store.pipe(select(fromStore.getAllDocs));

{{docs$ | async | json}}

the reducer:

export const selectDocsState = createFeatureSelector("docs");

export const selectDocsStatusState = createSelector(
  selectDocsState,
  state => state["docs"]
);

export const getAllDocs = createSelector(
  selectDocsStatusState,
  getDocs
)

I also have a selector to get by id:

{{docsById$ | async | json }}

docsById$ = this.store.pipe(select(fromStore.getById, { id: 1 }));

in the reducer:

export const getById = createSelector(
  selectDocsStatusState,
  getDocs,
  (state, docs, props) => {
    console.log({ props });
    return docs.docs.docs.filter(d => d.id === props.id);
  }
)

So far everything good. I get the docs array and display it.

Now, in my component I dispatch some action and catch by effect:

this.store.dispatch({ type: 'GET_DOC', payload: { id: 2 } });

And in the effect I want to know if this id is in the store or not.

So I use withLatestFrom from rxjs with the getById selector.

withLatestFrom((a: any) =>
  this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
),

The problem is i'm not getting the value from the selector instend I get the store instance.

tap(v => {
  console.log({ v });
}),

The full effect:

getDoc$ = createEffect(() =>
    this.actions$.pipe(
      ofType("GET_DOC"),
      map(a => a),
      tap(a => {
        console.log({ a });
      }),
      withLatestFrom((a: any) =>
        this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
      ),
      tap(v => {
        console.log({ v }); // <--------------- HERE SHOULD BE THE DOC AND THE ACTION.PAYLOAD, v[0].a.payload, v[1].id
      }),
      exhaustMap(payload => {
        return of({ type: "SOME_ACTION", payload: null });
      })
    )
  );

Here is my full example in stackbliz.

What do I missing here?

Body:
Warning - I’d use concatLatestFrom as per ngrx docs and Vincent’s answer. I don’t think this should be upvoted / accepted answer but can’t delete.

Original post:

This is covered in the NgRx Docs - Incorporating State but I found Brandon Roberts github comment more useful:

There are two predominant things you do when listening to an action after using the ofType operator:

actions.pipe(
 ofType('SOME_ACTION')
 someMap(action => doSomething(action))
)

and

actions.pipe(
 ofType('SOME_ACTION'),
 withLatestFrom(store.select(someThing)),
 someMap(([action, latest]) => doSomething(action, latest))
)

These have two different behaviors as far as effects are concerned. The first one doesn't do anything until the action is dispatched, which is what it should do.

The second one immediately subscribes to the withLatestFrom whether the action is dispatched yet or not. If that state used by the selector is not initialized yet, you could get an error you're not expecting. In order to make it "lazy" you end up having to nest it within a flattening observable operator.

actions.pipe(
 ofType('SOME_ACTION'),
 someMap(action =>
  of(action).pipe(
    withLatestFrom(store.select(someThing)),
    someMap(([action, latest]) => doSomething(action, latest))
   )
)

Applying this gives the following:

  getDoc$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(fromDocs.getDocument),
      switchMap(action =>
        of(action).pipe(
          withLatestFrom(
            this.store.select(fromDocs.getById, { id: action.payload.id })
          ),
          map(([action, latest]) => {
            return fromDocs.someAction();
          })
        )
      )
    );
  });

Stackblitz


问:
Are Erlang behaviours really kind of the same as class inheritance?
Currently I am working on a data pipeline project utilizing Apache Kafka and Erlang as a stream processor language (I have actually no previous experience with erlang except learning the language and the concepts since the beginning of the year). To write Kafka consumers we rely on the rock solid brod module.

I understand, that I have to write a supervisor callback module which is responsible for starting my brod_client and my group_consumer module.

```<code>my_app
  +-- my_sup
        +-- brod_client
        +-- my_group_consumer
</code>```

this group_consumer module I wrote is a callback module for the brod_group_subsriber_v2 behaviour which in itself is a callback module for gen_server.

```<code>my_group_consumer > brod_group_subscriber > gen_server
</code>```

When I run my application, my supervisor is starting the brod_client, but not my consumer erlang:whereis(my_group_consumer). returns undefined. Only after a message reaches in, the brod_group_consumer_v2 itself seems to intitalizes my_group_consumer and calls its message handler function. This "lazy" init makes sense for me, but differs from what I would expect as I configured the supervisor to explicitely take care of my_group_consumer (not its base behaviour).

So after all this I am not sure if I understand behaviours exactly and therefore if I am using the brod modules correctly, as I try to inherit from them as I would with Java class inheritance and polymorphism.

Its very hard to find examples where brod is used in a supervisor and not just on the shell for demo purposes.

EDIT: I am using brod as an example of a situation/use case here, where I expected the implementation of most specialised module to "inherit" from the mst generic one, which doesn't seem to be the case and therefore I am not able to use a module like brod correctly.

Would somebody please explain me the differences of the concepts? If you like to explain it according to my example it would be great, if you can explain it with another example or no example at all...also fine, thanks in advance.

答:
The same module can be a callback module for a behavior and define
    another. If an existing behavior takes you half the way there, you can
    just build your new behavior on top of it, like OTP does ;)"

... I´d wish there would be an Third Article covering exactly that ;)

The following example works for me--it implements a my_server behaviour on top of gen_server:

my_server.erl:

```<code>-module(my_server).
-compile(export_all).

-behaviour(gen_server).
-callback go( integer() ) -> atom().  %% Specifies that this module is a behaviour
                                      %% which has one required callback function go/1

%%%   required gen_server callback functions

init(_Args) ->
    {ok, []}.

handle_call(Msg, _From, State) ->
    io:format("In handle_call(), Msg= ~w~n", [Msg]),
    {reply, hello_from_handle_call, State}.

handle_cast(Msg, State) ->
    io:format("In handle_cast(), Msg= ~w~n", [Msg]),
    {noreply, State}.

handle_info(Msg, State) ->
    io:format("In handle_info(), Msg= ~w~n", [Msg]),
    {noreply, State}.
</code>```

b.erl:

```<code>-module(b).
-compile(export_all).

-behaviour(my_server).

%%  my_server callback functions

go(_Count) ->
    ?MODULE ! hi_from_go,  %% handle_info() gets this message
    hi.

%% client functions

start() ->
    gen_server:start_link( %% Calls the init() gen_server callback function.
      {local, ?MODULE},    %% Registers the gen_server using this name.
      my_server,           %% Looks for the gen_server callback functions in this module.
      [],
      []
    ).

do_call() ->
    spawn(
      fun() -> gen_server:call(?MODULE, hello) end  %% handle_call() gets this message
    ).

do_go() ->
    spawn(
      fun() -> go(20) end
    ).
</code>```

In the shell:

```<code>1> c(my_server).
my_server.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my_server}

2> c(b).
b.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,b}

3> b:start().
{ok,<0.76.0>}

4> b:do_call().
In handle_call(), Msg= hello
<0.78.0>

5> b:do_go().
In handle_info(), Msg= hi_from_go
<0.80.0>
</code>```

Body:
Currently I am working on a data pipeline project utilizing Apache Kafka and Erlang as a stream processor language (I have actually no previous experience with erlang except learning the language and the concepts since the beginning of the year). To write Kafka consumers we rely on the rock solid brod module.

I understand, that I have to write a supervisor callback module which is responsible for starting my brod_client and my group_consumer module.

my_app
  +-- my_sup
        +-- brod_client
        +-- my_group_consumer

this group_consumer module I wrote is a callback module for the brod_group_subsriber_v2 behaviour which in itself is a callback module for gen_server.

my_group_consumer > brod_group_subscriber > gen_server

When I run my application, my supervisor is starting the brod_client, but not my consumer erlang:whereis(my_group_consumer). returns undefined. Only after a message reaches in, the brod_group_consumer_v2 itself seems to intitalizes my_group_consumer and calls its message handler function. This "lazy" init makes sense for me, but differs from what I would expect as I configured the supervisor to explicitely take care of my_group_consumer (not its base behaviour).

So after all this I am not sure if I understand behaviours exactly and therefore if I am using the brod modules correctly, as I try to inherit from them as I would with Java class inheritance and polymorphism.

Its very hard to find examples where brod is used in a supervisor and not just on the shell for demo purposes.

EDIT: I am using brod as an example of a situation/use case here, where I expected the implementation of most specialised module to "inherit" from the mst generic one, which doesn't seem to be the case and therefore I am not able to use a module like brod correctly.

Would somebody please explain me the differences of the concepts? If you like to explain it according to my example it would be great, if you can explain it with another example or no example at all...also fine, thanks in advance.

Body:
The same module can be a callback module for a behavior and define
    another. If an existing behavior takes you half the way there, you can
    just build your new behavior on top of it, like OTP does ;)"

... I´d wish there would be an Third Article covering exactly that ;)

The following example works for me--it implements a my_server behaviour on top of gen_server:

my_server.erl:

-module(my_server).
-compile(export_all).

-behaviour(gen_server).
-callback go( integer() ) -> atom().  %% Specifies that this module is a behaviour
                                      %% which has one required callback function go/1

%%%   required gen_server callback functions

init(_Args) ->
    {ok, []}.

handle_call(Msg, _From, State) ->
    io:format("In handle_call(), Msg= ~w~n", [Msg]),
    {reply, hello_from_handle_call, State}.

handle_cast(Msg, State) ->
    io:format("In handle_cast(), Msg= ~w~n", [Msg]),
    {noreply, State}.

handle_info(Msg, State) ->
    io:format("In handle_info(), Msg= ~w~n", [Msg]),
    {noreply, State}.

b.erl:

-module(b).
-compile(export_all).

-behaviour(my_server).

%%  my_server callback functions

go(_Count) ->
    ?MODULE ! hi_from_go,  %% handle_info() gets this message
    hi.

%% client functions

start() ->
    gen_server:start_link( %% Calls the init() gen_server callback function.
      {local, ?MODULE},    %% Registers the gen_server using this name.
      my_server,           %% Looks for the gen_server callback functions in this module.
      [],
      []
    ).

do_call() ->
    spawn(
      fun() -> gen_server:call(?MODULE, hello) end  %% handle_call() gets this message
    ).

do_go() ->
    spawn(
      fun() -> go(20) end
    ).

In the shell:

1> c(my_server).
my_server.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my_server}

2> c(b).
b.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,b}

3> b:start().
{ok,<0.76.0>}

4> b:do_call().
In handle_call(), Msg= hello
<0.78.0>

5> b:do_go().
In handle_info(), Msg= hi_from_go
<0.80.0>


问:
Vue + Vuex: input value not set by store if no store change
```<code><template>
  <input
    @input="formatValue"
    type="text"
    :value="formattedValue"
  />
</template>

<script type="text/javascript">
  import {formatPhoneNumber} from '~/utils/string';

  export default {
    computed: {
      formattedValue: function(){
        return formatPhoneNumber(this.value)
      },
    },
    methods: {
      formatValue(e) {
        this.$emit('input', formatPhoneNumber(e.target.value))
      }
    },
    props: ['value']
  }
</script>
</code>```

As long as the formatPhoneNumber(value) produces a different value, every thing works fine, but once the max length is reached (Since formatPhoneNumber('xx xx xx xx xx whatever') == 'xx xx xx xx xx'), the emitted value is the same as the current store one.

It is totally fine, except that as a consequence, state is not mutated and component is not re-rendered, hence formattedValue() is not called.

So I end up with xx xx xx xx xx in the store, but the input displays xx xx xx xx xx whatever as local input value varies from the store one.

How can I avoid this unexpected behavior? Moving formatPhoneNumber() to the store would not solve my issue since it would still prevent mutation, and only using formatPhoneNumber() in formattedValue() would make me end up with an un-formatted value in the store which is not what I want either.

How come Vue's input with dynamic value set still manages a local state?

答:
I think the easiest approach is a simple one-line modification to the parent's @input event, that clears the prop value before it updates it.

You still only need to emit the one value, but before working with the emitted value, clear the prop.

I've provided a snippet below (but note the additional differences in the snippet):

Instead of specifying the input field value, I opted to use v-model to bind it to a computed property that has a get and set method. This allowed me to use different logic when accessing vs modifying the data (quite handy in many situations).

By separating this logic, I was able to move the functionality from inside the input event to the set method, and eliminate the input event entirely.

new Vue({
  el: "#app",
  // props: ['valueProp'],
  data: {
    valueProp: "" //simulate prop data
  },

  computed: {
    // --Value input element is binded to--
    inputValue:{
      get(){ //when getting the value, return the prop
        return this.valueProp;
      },
      set(val){ //when the value is set, emit value
        this.formatValue(val);
      }
    }
  },

  methods: {

    // --Emit the value to the parent--
    formatValue(val) {
      this.parentFunction(this.formatPhoneNumber(val)); //simulate emitting the value
      // this.$emit('input', formatPhoneNumber(val));
    },

    // --Simulate parent receiving emit event--
    parentFunction(emittedValue){
      console.log("emitted:" + emittedValue);
      this.valueProp = null;         //first clear it (updates the input field)
      this.valueProp = emittedValue; //then assign it the emitted value
    },

    // --Simulate your format method--
    // THIS LOGIC CAN BE IGNORED. It is just a quick implementation of a naive formatter.
    // The "important" thing is it limits the length, to demonstrate exceeding the limit doesn't get reflected in the input field
    formatPhoneNumber(val){
      var phoneSpaces = [2,4,6,8];  //specify space formatting (space locations)
      var maxLength = 10;           //specify the max length
      val = val.replace(/ /g,'');   //remove existing formatting
      if(val.length > maxLength)    //limits the length to the max length
        val = val.substring(0, maxLength);

      // for the number of desired spaces, check each space location (working backwards) ... if value is longer than space location and space location is not a space ... add a space at the location.
      for(var i = phoneSpaces.length-1; i >= 0; i--){
        if(val.length > phoneSpaces[i] && val[phoneSpaces[i]] != " "){
          val = val.substring(0, phoneSpaces[i]) + " " + val.substring(phoneSpaces[i], val.length);
        }
      }
      return val
    }

  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="text" v-model="inputValue"/>

  <label style="float: right;">
    Prop Value: <span>{{valueProp}}</span>
  </label>

  <br>

  <label >format (xx xx xx xx xx)</label>
</div></code>```

Body:
<template>
  <input
    @input="formatValue"
    type="text"
    :value="formattedValue"
  />
</template>

As long as the formatPhoneNumber(value) produces a different value, every thing works fine, but once the max length is reached (Since formatPhoneNumber('xx xx xx xx xx whatever') == 'xx xx xx xx xx'), the emitted value is the same as the current store one.

It is totally fine, except that as a consequence, state is not mutated and component is not re-rendered, hence formattedValue() is not called.

So I end up with xx xx xx xx xx in the store, but the input displays xx xx xx xx xx whatever as local input value varies from the store one.

How can I avoid this unexpected behavior? Moving formatPhoneNumber() to the store would not solve my issue since it would still prevent mutation, and only using formatPhoneNumber() in formattedValue() would make me end up with an un-formatted value in the store which is not what I want either.

How come Vue's input with dynamic value set still manages a local state?

Body:
I think the easiest approach is a simple one-line modification to the parent's @input event, that clears the prop value before it updates it.

You still only need to emit the one value, but before working with the emitted value, clear the prop.

I've provided a snippet below (but note the additional differences in the snippet):

Instead of specifying the input field value, I opted to use v-model to bind it to a computed property that has a get and set method. This allowed me to use different logic when accessing vs modifying the data (quite handy in many situations).

By separating this logic, I was able to move the functionality from inside the input event to the set method, and eliminate the input event entirely.

new Vue({
  el: "#app",
  // props: ['valueProp'],
  data: {
    valueProp: "" //simulate prop data
  },

  computed: {
    // --Value input element is binded to--
    inputValue:{
      get(){ //when getting the value, return the prop
        return this.valueProp;
      },
      set(val){ //when the value is set, emit value
        this.formatValue(val);
      }
    }
  },

  methods: {

    // --Emit the value to the parent--
    formatValue(val) {
      this.parentFunction(this.formatPhoneNumber(val)); //simulate emitting the value
      // this.$emit('input', formatPhoneNumber(val));
    },

    // --Simulate parent receiving emit event--
    parentFunction(emittedValue){
      console.log("emitted:" + emittedValue);
      this.valueProp = null;         //first clear it (updates the input field)
      this.valueProp = emittedValue; //then assign it the emitted value
    },

    // --Simulate your format method--
    // THIS LOGIC CAN BE IGNORED. It is just a quick implementation of a naive formatter.
    // The "important" thing is it limits the length, to demonstrate exceeding the limit doesn't get reflected in the input field
    formatPhoneNumber(val){
      var phoneSpaces = [2,4,6,8];  //specify space formatting (space locations)
      var maxLength = 10;           //specify the max length
      val = val.replace(/ /g,'');   //remove existing formatting
      if(val.length > maxLength)    //limits the length to the max length
        val = val.substring(0, maxLength);

      // for the number of desired spaces, check each space location (working backwards) ... if value is longer than space location and space location is not a space ... add a space at the location.
      for(var i = phoneSpaces.length-1; i >= 0; i--){
        if(val.length > phoneSpaces[i] && val[phoneSpaces[i]] != " "){
          val = val.substring(0, phoneSpaces[i]) + " " + val.substring(phoneSpaces[i], val.length);
        }
      }
      return val
    }

  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="text" v-model="inputValue"/>

  <label style="float: right;">
    Prop Value: <span>{{valueProp}}</span>
  </label>

  <br>

  <label >format (xx xx xx xx xx)</label>
</div>


问:
problem in laravel route on tackling the response of payment gateway
I'm using laravel and integrate the payment gateway.when i send the post request then after success or cancellation ,it redirect the referece id like this
http://localhost/multi_vendor/user/paypal/return?flwref=FLW-MOCK-d4f7572650fbe61ecff7fb17a7129859&txref=rave-bxw7c98dymo8so0kwosco0wwscs8ogc
so how can tackle it in laravel?

I made route for this

```<code>Route::get('/paypal/return', 'User\PaypalController@payreturn')->name('user.payment.return');
</code>```

答:
I also didn't understand well your question, but let me try.

Possible appointments:

if your route is like localhost/multi_vendor/user/paypal/return, you must represent all steps in route file, something like Route::get('/multi_vendor/{user}/paypal/return,[...]). If you are already using somethink like it or a group with prefix, ignore it;

if you wish to redirect, you could use return redirect('yourCompleteUrl') in your controller or in route file;

if you wish to retrieave the parameters Tim Lewis anserwed what you need:

```<code>    public function payreturn(Request $request)
    {
        $flref = $request->input('flref');
        $txref = $request->input('txref');
    }
</code>```

Body:
I'm using laravel and integrate the payment gateway.when i send the post request then after success or cancellation ,it redirect the referece id like this
http://localhost/multi_vendor/user/paypal/return?flwref=FLW-MOCK-d4f7572650fbe61ecff7fb17a7129859&txref=rave-bxw7c98dymo8so0kwosco0wwscs8ogc
so how can tackle it in laravel?

I made route for this

Route::get('/paypal/return', 'User\PaypalController@payreturn')->name('user.payment.return');

Body:
I also didn't understand well your question, but let me try.

Possible appointments:

if your route is like localhost/multi_vendor/user/paypal/return, you must represent all steps in route file, something like Route::get('/multi_vendor/{user}/paypal/return,[...]). If you are already using somethink like it or a group with prefix, ignore it;

if you wish to redirect, you could use return redirect('yourCompleteUrl') in your controller or in route file;

if you wish to retrieave the parameters Tim Lewis anserwed what you need:

    public function payreturn(Request $request)
    {
        $flref = $request->input('flref');
        $txref = $request->input('txref');
    }


问:
Power Bi DAX: Cumulative Sum not Showing Correct Data
I am having trouble making a cumulative sum.

It is showing data from the previous column instead of being a cumulative.

I have tested it out on a test file and it works fine but using the same format of the formula:

QuoteValue running total in ClosedDate =

```<code>Sales running total in Date =
CALCULATE(
    SUM('Sheet1'[Sales]),
    FILTER(
        ALLSELECTED('Sheet1'[Date]),
        ISONORAFTER('Sheet1'[Date], MAX('Sheet1'[Date]), DESC)
    )
)
</code>```

Im not sure what i am doing wrong, ive used ALLSELECTED, FILTER(ALL, ALL

The Quotevalue and Date are both in the same table and all other fields im using in the visual are all in the same table.

Im stumped.

Here is a dummy sheet i have put together.

Dummy Sheet

答:
```<code>Sales running total in Date =
var person = 'Sheet1'[Person]
var toDate = 'Sheet1'[Date]
return CALCULATE(
    SUM('Sheet1'[Sales]),
        FILTER('Sheet1', 'Sheet1'[Person] = Person && 'Sheet1'[Date] <= toDate)
)
</code>```

What we do here is that for each row, we get the other rows where persons are same and date is lower or equal. From this we calculate the sum.

Body:
I am having trouble making a cumulative sum.

It is showing data from the previous column instead of being a cumulative.

I have tested it out on a test file and it works fine but using the same format of the formula:

QuoteValue running total in ClosedDate =

Sales running total in Date =
CALCULATE(
    SUM('Sheet1'[Sales]),
    FILTER(
        ALLSELECTED('Sheet1'[Date]),
        ISONORAFTER('Sheet1'[Date], MAX('Sheet1'[Date]), DESC)
    )
)

Im not sure what i am doing wrong, ive used ALLSELECTED, FILTER(ALL, ALL

The Quotevalue and Date are both in the same table and all other fields im using in the visual are all in the same table.

Im stumped.

Here is a dummy sheet i have put together.

Dummy Sheet

Body:
Sales running total in Date =
var person = 'Sheet1'[Person]
var toDate = 'Sheet1'[Date]
return CALCULATE(
    SUM('Sheet1'[Sales]),
        FILTER('Sheet1', 'Sheet1'[Person] = Person && 'Sheet1'[Date] <= toDate)
)

What we do here is that for each row, we get the other rows where persons are same and date is lower or equal. From this we calculate the sum.


问:
Use the sum() on a result set returned by a subquery
This query returns the two lowests grades {9,10}

```<code>select TOP 2 grades.grade
from grades
where grades.studentno = 1
order by grade ASC
</code>```

And I want to sum the result of grades with the sum() function and set the result of the sum() function to the variable @sumLowerGrades

I have attempted with this query

```<code>set @sumLowerGrades = sum(select TOP 2 grades.grade from grades
        where grades.studentno = 1 order by grade ASC)
</code>```

But it fails with the following message:

Incorrect syntax near the keyword 'select'.

  Incorrect syntax near ')'.

答:
Also can do as the following:

```<code>SET @sumLowerGrades = (SELECT sum(grade)
from (select TOP 2 grades.grade
      from grades
      where grades.studentno = 1
      order by grade ASC
     ) g);
</code>```

A FROM clause requires table name/Names, so when you see

```<code>from (select TOP 2 grades.grade
      from grades
      where grades.studentno = 1
      order by grade ASC
     ) g
</code>```

Is making this query/dataset as table and here g is the name given to the subquery within the brackets.

Body:
This query returns the two lowests grades {9,10}

select TOP 2 grades.grade
from grades
where grades.studentno = 1
order by grade ASC

And I want to sum the result of grades with the sum() function and set the result of the sum() function to the variable @sumLowerGrades

I have attempted with this query

set @sumLowerGrades = sum(select TOP 2 grades.grade from grades
        where grades.studentno = 1 order by grade ASC)

But it fails with the following message:

Incorrect syntax near the keyword 'select'.

  Incorrect syntax near ')'.

Body:
Also can do as the following:

SET @sumLowerGrades = (SELECT sum(grade)
from (select TOP 2 grades.grade
      from grades
      where grades.studentno = 1
      order by grade ASC
     ) g);

A FROM clause requires table name/Names, so when you see

from (select TOP 2 grades.grade
      from grades
      where grades.studentno = 1
      order by grade ASC
     ) g

Is making this query/dataset as table and here g is the name given to the subquery within the brackets.