问:
Slider Control (Trackbar) receiving messages in dialog box procedure
I'm designing a dialog box in Visual Studio resource editor, and the problem is that I don't know how to listen for messages sent by slider control, below the image is a dialog procedure.

I know I need to listen for WM_NOTIFY message but I don't know what code does a control send me... I added 2 comments in WM_NOTIFY part of the procedure below to show where is the problem...

here is an image how I arranged this dialog box:

And here is dialog box procedure:

```<code>INT_PTR CALLBACK SettingsSoundProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    static MainWindow* main_win = nullptr;

    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        main_win = reinterpret_cast<MainWindow*>(lParam);

        SetWindowText(GetDlgItem(hDlg, IDC_VOLUME_LABEL), TEXT("Music"));
        SendMessage(GetDlgItem(hDlg, IDC_VOLUME_SLIDER), TBM_SETRANGE, (WPARAM)FALSE, MAKELPARAM(0, 100));
        SendMessage(GetDlgItem(hDlg, IDC_VOLUME_SLIDER), TBM_SETPOS, (WPARAM)TRUE, (LPARAM)20);

        return TRUE;
    }
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDOK:

            EndDialog(hDlg, 0);
            return TRUE;

        case IDCANCEL:
            EndDialog(hDlg, 0);
            return TRUE;

        default:
            break;
        }

    case WM_NOTIFY:
    {
        LPNMHDR nmhdr = (LPNMHDR)lParam;

        if (nmhdr->idFrom == IDC_VOLUME_SLIDER)
        {
            switch (nmhdr->code)
            {
            // what message do I listen for here?
            case TB_THUMBTRACK:
            case WM_HSCROLL:
            case WM_VSCROLL:
            case TRBN_THUMBPOSCHANGING:
            case TB_PAGEUP:
            case TB_PAGEDOWN:
            case TB_THUMBPOSITION:
            case TB_TOP:
            case TB_BOTTOM:
            case TB_ENDTRACK:

                // this is never hit
                MessageBox(nullptr, TEXT("Message"), TEXT("Info"), MB_OK);
                break;

            default:
                // this is hit!
                abort();
            }
        }

        return TRUE;
    }
    case WM_DESTROY:
        EndDialog(hDlg, 0);
        return TRUE;

    default:
        break;
    }

    return FALSE;
}
</code>```

As you can see WM_HSCROLL nor TRBN_THUMBPOSCHANGING is being hit, what message do I need to listen for here?

答:
WM_HSCROLL and WM_VSCROLL are their own messages, they are not wrapped in WM_NOTIFY.

The TB_... values are not WM_NOTIFY notification codes, either. They are reason codes reported in the NMTRBTHUMBPOSCHANGING struct of the TRBN_THUMBPOSCHANGING notification.

Per the documentation, the only WM_NOTIFY notifications that a Trackbar sends are:

NM_CUSTOMDRAW

NM_RELEASEDCAPTURE

TRBN_THUMBPOSCHANGING

Try this:

INT_PTR CALLBACK SettingsSoundProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    static MainWindow* main_win = nullptr;
    static HWND hSlider = nullptr;

    switch (uMsg)
    {
        case WM_INITDIALOG:
        {
            main_win = reinterpret_cast<MainWindow*>(lParam);
            hSlider = GetDlgItem(hDlg, IDC_VOLUME_SLIDER);
            SetWindowText(GetDlgItem(hDlg, IDC_VOLUME_LABEL), TEXT("Music"));
            SendMessage(hSlider, TBM_SETRANGE, FALSE, MAKELPARAM(0, 100));
            SendMessage(hSlider, TBM_SETPOS, TRUE, 20);
            return TRUE;
        }

        case WM_DESTROY:
        {
            EndDialog(hDlg, 0);
            return TRUE;
        }

        case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
                case IDOK:
                    EndDialog(hDlg, 0);
                    return TRUE;

                case IDCANCEL:
                    EndDialog(hDlg, 0);
                    return TRUE;
            }
            break;
        }

        case WM_NOTIFY:
        {
            LPNMHDR nmhdr = reinterpret_cast<LPNMHDR>(lParam);
            if ((nmhdr->code == TRBN_THUMBPOSCHANGING) &&
                (nmhdr->hwndFrom == hSlider))
            {
                NMTRBTHUMBPOSCHANGING *nmtrb = reinterpret_cast<NMTRBTHUMBPOSCHANGING*>(lParam);
                switch (nmtrb->nReason)
                {
                    case TB_THUMBTRACK:
                    case TB_PAGEUP:
                    case TB_PAGEDOWN:
                    case TB_THUMBPOSITION:
                    case TB_TOP:
                    case TB_BOTTOM:
                    case TB_ENDTRACK:
                        MessageBox(nullptr, TEXT("Thumb Pos Changing"), TEXT("Info"), MB_OK);
                        break;
                }
            }
            break;
        }

        case WM_HSCROLL:
        {
            if ((lParam != 0) &&
                (reinterpret_cast<HWND>(lParam) == hSlider))
            {
                switch (LOWORD(wParam))
                {
                    case SB_ENDSCROLL:
                    case SB_LEFT:
                    case SB_RIGHT:
                    case SB_LINELEFT:
                    case SB_LINERIGHT:
                    case SB_PAGELEFT:
                    case SB_PAGERIGHT:
                    case SB_THUMBPOSITION:
                    case SB_THUMBTRACK:
                        MessageBox(nullptr, TEXT("Horz Scroll"), TEXT("Info"), MB_OK);
                        break;
                }
            }
            break;
        }

        case WM_VSCROLL:
        {
            if ((lParam != 0) &&
                (reinterpret_cast<HWND>(lParam) == hSlider))
            {
                switch (LOWORD(wParam))
                {
                    case SB_BOTTOM:
                    case SB_ENDSCROLL:
                    case SB_LINEDOWN:
                    case SB_LINEUP:
                    case SB_PAGEDOWN:
                    case SB_PAGEUP:
                    case SB_THUMBPOSITION:
                    case SB_THUMBTRACK:
                    case SB_TOP:
                        MessageBox(nullptr, TEXT("Vert Scroll"), TEXT("Info"), MB_OK);
                        break;
                }
            }
            break;
        }
    }

    return FALSE;
}
```

Body:
I'm designing a dialog box in Visual Studio resource editor, and the problem is that I don't know how to listen for messages sent by slider control, below the image is a dialog procedure.

I know I need to listen for WM_NOTIFY message but I don't know what code does a control send me... I added 2 comments in WM_NOTIFY part of the procedure below to show where is the problem...

here is an image how I arranged this dialog box:

And here is dialog box procedure:

INT_PTR CALLBACK SettingsSoundProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    static MainWindow* main_win = nullptr;

    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        main_win = reinterpret_cast<MainWindow*>(lParam);

        SetWindowText(GetDlgItem(hDlg, IDC_VOLUME_LABEL), TEXT("Music"));
        SendMessage(GetDlgItem(hDlg, IDC_VOLUME_SLIDER), TBM_SETRANGE, (WPARAM)FALSE, MAKELPARAM(0, 100));
        SendMessage(GetDlgItem(hDlg, IDC_VOLUME_SLIDER), TBM_SETPOS, (WPARAM)TRUE, (LPARAM)20);

        return TRUE;
    }
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDOK:

            EndDialog(hDlg, 0);
            return TRUE;

        case IDCANCEL:
            EndDialog(hDlg, 0);
            return TRUE;

        default:
            break;
        }

    case WM_NOTIFY:
    {
        LPNMHDR nmhdr = (LPNMHDR)lParam;

        if (nmhdr->idFrom == IDC_VOLUME_SLIDER)
        {
            switch (nmhdr->code)
            {
            // what message do I listen for here?
            case TB_THUMBTRACK:
            case WM_HSCROLL:
            case WM_VSCROLL:
            case TRBN_THUMBPOSCHANGING:
            case TB_PAGEUP:
            case TB_PAGEDOWN:
            case TB_THUMBPOSITION:
            case TB_TOP:
            case TB_BOTTOM:
            case TB_ENDTRACK:

                // this is never hit
                MessageBox(nullptr, TEXT("Message"), TEXT("Info"), MB_OK);
                break;

            default:
                // this is hit!
                abort();
            }
        }

        return TRUE;
    }
    case WM_DESTROY:
        EndDialog(hDlg, 0);
        return TRUE;

    default:
        break;
    }

    return FALSE;
}

As you can see WM_HSCROLL nor TRBN_THUMBPOSCHANGING is being hit, what message do I need to listen for here?


来源: stackexchange

问:
Change Navigation Bar Item Dynamically - Swift
I am creating a NavigationBar with UIBarButtonItem which located on right side of screen. As default I set that setRightBarButton with UIBarButtonItem(image: UIImage(named: "edit"), style: .plain, target: self, action: #selector(editProfile)) and when I clicked on that it should change that rightBarButton to other title but it doesn't work.

Here is I tried to change with I clicked on it

```<code>@objc
func editProfile() {
    self.navigationItem.setRightBarButton(cancelActionBar, animated: true)

}
</code>```

This is object of cancelActionBar

```<code>let cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelEdit))
</code>```

And this is its action which change it back to default.

```<code>@objc
func cancelEdit() {
    self.navigationItem.setRightBarButton(editActionBar, animated: true)
}
</code>```

I also tried to use main thread as well but it is not working as I expected.

答:
When you create a UIBarButtonItem as instance property the target self won't be initialized yet. So setting the target self won't work.

```<code>class ViewController: UIViewController {
    let editActionBar = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editBtnAction(_:)))
    override func viewDidLoad() {
        super.viewDidLoad()
        print(editActionBar.target)//nil
    }
}
</code>```

The target self will be assigned properly when you initialize the button in viewDidLoad

```<code>class ViewController: UIViewController {
    var editActionBar: UIBarButtonItem?
    override func viewDidLoad() {
        super.viewDidLoad()
        editActionBar = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editBtnAction(_:)))
        print(editActionBar?.target)//self
    }
}
</code>```

Declare the buttons as optional and initialize the buttons in viewDidLoad.

```<code>class ViewController: UIViewController {

    var editActionBar: UIBarButtonItem?
    var cancelActionBar: UIBarButtonItem?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.editActionBar = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editBtnAction(_:)))
        self.cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelBtnAction(_:)))
        self.navigationItem.setRightBarButton(editActionBar, animated: true)
    }
    @objc func editBtnAction(_ sender: UIBarButtonItem) {
        self.navigationItem.setRightBarButton(cancelActionBar, animated: true)
    }
    @objc func cancelBtnAction(_ sender: UIBarButtonItem) {
        self.navigationItem.setRightBarButton(editActionBar, animated: true)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating a NavigationBar with UIBarButtonItem which located on right side of screen. As default I set that setRightBarButton with UIBarButtonItem(image: UIImage(named: "edit"), style: .plain, target: self, action: #selector(editProfile)) and when I clicked on that it should change that rightBarButton to other title but it doesn't work.

Here is I tried to change with I clicked on it

@objc
func editProfile() {
    self.navigationItem.setRightBarButton(cancelActionBar, animated: true)

}

This is object of cancelActionBar

let cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelEdit))

And this is its action which change it back to default.

@objc
func cancelEdit() {
    self.navigationItem.setRightBarButton(editActionBar, animated: true)
}

I also tried to use main thread as well but it is not working as I expected.

Body:
When you create a UIBarButtonItem as instance property the target self won't be initialized yet. So setting the target self won't work.

class ViewController: UIViewController {
    let editActionBar = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editBtnAction(_:)))
    override func viewDidLoad() {
        super.viewDidLoad()
        print(editActionBar.target)//nil
    }
}

The target self will be assigned properly when you initialize the button in viewDidLoad

class ViewController: UIViewController {
    var editActionBar: UIBarButtonItem?
    override func viewDidLoad() {
        super.viewDidLoad()
        editActionBar = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editBtnAction(_:)))
        print(editActionBar?.target)//self
    }
}

Declare the buttons as optional and initialize the buttons in viewDidLoad.

class ViewController: UIViewController {

    var editActionBar: UIBarButtonItem?
    var cancelActionBar: UIBarButtonItem?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.editActionBar = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editBtnAction(_:)))
        self.cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelBtnAction(_:)))
        self.navigationItem.setRightBarButton(editActionBar, animated: true)
    }
    @objc func editBtnAction(_ sender: UIBarButtonItem) {
        self.navigationItem.setRightBarButton(cancelActionBar, animated: true)
    }
    @objc func cancelBtnAction(_ sender: UIBarButtonItem) {
        self.navigationItem.setRightBarButton(editActionBar, animated: true)
    }
}


问:
Replace all 0's with 5's in a given number using sprintf and sscanf
I am trying to replace all the 0's present in a given integer with 5's.

To do that i am using sprintf to convert integer to string and do the operations on the string and finally convert back the string into an integer

Below is the code:

```<code>#include<stdio.h>

int main() {

    int num=0, i=0;
    char str[10];

    printf("Enter the number: ");
    scanf("%d",&num);

    sprintf(str,"%d",num);
    printf("string str:%s",str);
    while(str[i]!='\0')
    {
        if(str[i]==0)
            str[i]=5;
        i++;
    }

    sscanf(str,"%d",&num);

    printf("\nBefore replacement: %s", str);
    printf("\nAfter replacement: %d", num);

}
</code>```

I am getting wrong output

Could someone identify and correct what is wrong here. Thanks :)

答:
```<code>    if(str[i]==0)
        str[i]=5;
</code>```

must be

```<code>    if(str[i]=='0')
        str[i]='5';
</code>```

I also encourage you to check the initial scanf returns 1 to know if the user enter or not a valid input

and in

```<code>printf("\nBefore replacement: %s", str);
printf("\nAfter replacement: %d", num);
</code>```

to produce the \n at the end to have

```<code>printf("Before replacement: %s\n", str);
printf("After replacement: %d\n", num);
</code>```

but note you write the string after the replacements rather than before, you have to move the case before before the while or to just remove it because you already written the string before the replacements

Example :

```<code>#include<stdio.h>

int main() {

    int num=0, i=0;
    char str[10];

    printf("Enter the number: ");
    if (scanf("%d",&num) != 1)
      puts("invalid input");
    else {
      sprintf(str,"%d",num);
      printf("string str:%s\n",str);
      while(str[i]!='\0')
      {
        if(str[i]=='0')
          str[i]='5';
        i++;
      }

      sscanf(str,"%d",&num);

      printf("After replacement: %d\n", num);
    }

    return 0;
}
</code>```

Compilation and executions :

```<code>pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Enter the number: aze
invalid input
pi@raspberrypi:/tmp $ ./a.out
Enter the number: 10204
string str:10204
After replacement: 15254
pi@raspberrypi:/tmp $
</code>```

Body:
I am trying to replace all the 0's present in a given integer with 5's.

To do that i am using sprintf to convert integer to string and do the operations on the string and finally convert back the string into an integer

Below is the code:

#include<stdio.h>

int main() {

    int num=0, i=0;
    char str[10];

    printf("Enter the number: ");
    scanf("%d",&num);

    sprintf(str,"%d",num);
    printf("string str:%s",str);
    while(str[i]!='\0')
    {
        if(str[i]==0)
            str[i]=5;
        i++;
    }

    sscanf(str,"%d",&num);

    printf("\nBefore replacement: %s", str);
    printf("\nAfter replacement: %d", num);

}

I am getting wrong output

Could someone identify and correct what is wrong here. Thanks :)

Body:
    if(str[i]==0)
        str[i]=5;

must be

    if(str[i]=='0')
        str[i]='5';

I also encourage you to check the initial scanf returns 1 to know if the user enter or not a valid input

and in

printf("\nBefore replacement: %s", str);
printf("\nAfter replacement: %d", num);

to produce the \n at the end to have

printf("Before replacement: %s\n", str);
printf("After replacement: %d\n", num);

but note you write the string after the replacements rather than before, you have to move the case before before the while or to just remove it because you already written the string before the replacements

Example :

#include<stdio.h>

int main() {

    int num=0, i=0;
    char str[10];

    printf("Enter the number: ");
    if (scanf("%d",&num) != 1)
      puts("invalid input");
    else {
      sprintf(str,"%d",num);
      printf("string str:%s\n",str);
      while(str[i]!='\0')
      {
        if(str[i]=='0')
          str[i]='5';
        i++;
      }

      sscanf(str,"%d",&num);

      printf("After replacement: %d\n", num);
    }

    return 0;
}

Compilation and executions :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Enter the number: aze
invalid input
pi@raspberrypi:/tmp $ ./a.out
Enter the number: 10204
string str:10204
After replacement: 15254
pi@raspberrypi:/tmp $


问:
How to make dropdown to be closed only on click-outside?
I have multi-select dropdown, problem is cus when user select one item - dropdown is closed.

How to make that dropdown is closed only on outside click?

Dropdown is made by html ul > li:

```<code>// Here we loop trough list of filters and render options as <li> tags
 <ul name="filters" className="dropdown">
    {subFilters.map((filter, i) => (
      <li
        defaultChecked={filter.name}
        onClick={() => handleSelect(filter)}
        className={`option`}>
        <span>{filter.name}</span>
      </li>
    ))}
  </ul>
</code>```

Css part - Classes used are:

dropdown for  tag

option for

```<code>.dropdown {
  display: flex;
  flex-direction: column;
  min-width: 11rem;
  position: absolute;
  z-index: 1;
  font-size: 16px;
  border-radius: 3px;
  border: solid 1px #dee1e5;
  box-shadow: 0 9px 8px rgba(0, 0, 0, 0.05);
  background-color: white;
  outline: none;
  cursor: pointer;
}

.option {
  list-style-type: none;
  padding: 10px 10px 10px 0;
  margin-left: 2.6rem;
}
</code>```

This is how that dropdown looks:

答:
You can handle this by onBlur event.

Suppose you have snippet like this :

 this.handleBlur('myModal')}>Some content

Now this.handleBlur

```<code>handleBlur = modalName => {
    this.setState({ [modalName]: false });
};
</code>```

Body:
I have multi-select dropdown, problem is cus when user select one item - dropdown is closed.

How to make that dropdown is closed only on outside click?

Dropdown is made by html ul > li:

// Here we loop trough list of filters and render options as
 tags

    {subFilters.map((filter, i) => (

 handleSelect(filter)}
        className={`option`}>
        {filter.name}

    ))}

Css part - Classes used are:

dropdown for  tag

option for

.dropdown {
  display: flex;
  flex-direction: column;
  min-width: 11rem;
  position: absolute;
  z-index: 1;
  font-size: 16px;
  border-radius: 3px;
  border: solid 1px #dee1e5;
  box-shadow: 0 9px 8px rgba(0, 0, 0, 0.05);
  background-color: white;
  outline: none;
  cursor: pointer;
}

.option {
  list-style-type: none;
  padding: 10px 10px 10px 0;
  margin-left: 2.6rem;
}

This is how that dropdown looks:

Body:
You can handle this by onBlur event.

Suppose you have snippet like this :
<div class="dropdown" onBlur={() => this.handleBlur('myModal')}>Some content</div>

Now this.handleBlur

handleBlur = modalName => {
    this.setState({ [modalName]: false });
};


问:
how to insert a new empty line on selected index number in an array using \n. while we loop through it using v-for and create a list
want to insert a new empty line before a selected array element while we loop through it using v-for to create a list..trying to do this using \n isn't working</p>

```<code><!-- this is the template part -->
<ul>
    <li v-for = "ninja in ninjas" > {{ninja}}</li>
</ul>

/* this is the script part notice index no 2 in the array*/

data() {
    return {
        ninjas: [
            'mati kahe kumhaar sey, tu kya ronday mohey',
            ' Ik din aisa aayega mai rondungi tohe',
            '\n aaye hain toh jaayengay Raja, Rank, fkeer',
            ' Ik sinhaasan chodi chale, Ik baandhay zanjeer'
        ]
    };
},
</code>```

答:
This is pretty easy to do using the ```</code> tag which forces it to preserve white space, new lines, etc. This is often used for preserving formatting in code examples. </p>

```

```{{ninja}}```

```

<p>working example: https://jsfiddle.net/skribe/10yL6va8/8/ </p>

<p>You will probably want to use css to style the text surrounded by <code>``` since most browsers automatically format it differently.

Body:
want to insert a new empty line before a selected array element while we loop through it using v-for to create a list..trying to do this using \n isn't working

 {{ninja}}

/* this is the script part notice index no 2 in the array*/

data() {
    return {
        ninjas: [
            'mati kahe kumhaar sey, tu kya ronday mohey',
            ' Ik din aisa aayega mai rondungi tohe',
            '\n aaye hain toh jaayengay Raja, Rank, fkeer',
            ' Ik sinhaasan chodi chale, Ik baandhay zanjeer'
        ]
    };
},

Body:
This is pretty easy to do using the <pre> tag which forces it to preserve white space, new lines, etc. This is often used for preserving formatting in code examples.

 <div id="app">
   <ul>
     <li v-for = "ninja in ninjas" ><pre>{{ninja}}</pre></li>
   </ul>
</div>

working example: https://jsfiddle.net/skribe/10yL6va8/8/

You will probably want to use css to style the text surrounded by <pre> since most browsers automatically format it differently.


答:
scanf("%d", num); should be scanf("%d", &num);.

Also, this here

```<code>if (str[i] == 0)
    str[i] = 5;
</code>```

should be

```<code>if (str[i] == '0')
    str[i] = '5';
</code>```

Because 0 is just the same as '\0', but you want to replace the character representing 0.

Also, in your output, you got before and after mixed up.

Title: Replace all 0's with 5's in a given number using sprintf and sscanf

Body:
scanf("%d", num); should be scanf("%d", &num);.

Also, this here

if (str[i] == 0)
    str[i] = 5;

should be

if (str[i] == '0')
    str[i] = '5';

Because 0 is just the same as '\0', but you want to replace the character representing 0.

Also, in your output, you got before and after mixed up.


问:
Need help in accessing each row of an Int column using scala
I'm trying to access each row of a specific Int column "numbers" to trace the previous row and next row in the numbers column. As a newbie, tried few samples as below, but I'm not able to solve it. I checked multiple sources online but couldn't rectify it. I do think list/collections might work, but I don't know how to implement it. Could someone help me in this.

I tried the below, but I'm getting error as "Int does not take parameters"

```<code>    import org.apache.spark.sql.functions._
    import org.apache.spark.sql.expressions.Window
    import org.apache.spark.broadcast.Broadcast
    import org.apache.spark.rdd.RDD
    import org.apache.spark.sql.Row

    val df = df_new.select($"tin", $"year",$"mnth",
   struct($"date_begin", $"date_end",$"start",$"end",$"usage",$"numbers")
    as "data").rdd.groupBy(x => (x.getString(0),x.getInt(1),x.getInt(2)))
    .map( x => {

        val tin = x(0).getString(0)
        val year = x(0).getInt(1)
        val month = x(0).getInt(2)
        val use = x(0).getStruct(3).getFloat(4)
        var sum:Float = 0.0F
        val nums = x(0).getStruct(3).getInt(5)

        for (i <- x.indices)
                 {
                      val v = x(i).getStruct(3)
                      val n = x(i).getStruct(3).getInt(5)
                      var next = n(i+1)
                      var prev = n(i-1)

                      if(nums == next || nums == prev)
                      {
                         sum  =  sum + v.getFloat(4)
                      }
                      else
                      {
                          sum
                      }
                      }
                      (tin,year,nums)
                }
            )
</code>```

I need to get data as below

```<code> numbers            next             prev
   0                  1              null
   1                  0              0
   0                  1              1
   1                  1              0
   1                  0              1
   0                  1              1
   1                  1              0
   1                  1              1
   1                  1              1
   1                  0              1
   0                null             1
</code>```

答:
Here is an answer to compare two rows (as I have no Spark setup I use general Scala features).

If l is a IterableLike, e.g. a Seqor a List you have a function sliding.

So here is an example:

```<code>val l = Seq(1,2,3,4,5)

l.sliding(2) // gives you Seq(List(1,2),List(2,1)..)
 .map{case x::y::_ => //here you can compare these two values
</code>```

In your case x and y is maybe a more complex type.

Body:
I'm trying to access each row of a specific Int column "numbers" to trace the previous row and next row in the numbers column. As a newbie, tried few samples as below, but I'm not able to solve it. I checked multiple sources online but couldn't rectify it. I do think list/collections might work, but I don't know how to implement it. Could someone help me in this.

I tried the below, but I'm getting error as "Int does not take parameters"

    import org.apache.spark.sql.functions._
    import org.apache.spark.sql.expressions.Window
    import org.apache.spark.broadcast.Broadcast
    import org.apache.spark.rdd.RDD
    import org.apache.spark.sql.Row

    val df = df_new.select($"tin", $"year",$"mnth",
   struct($"date_begin", $"date_end",$"start",$"end",$"usage",$"numbers")
    as "data").rdd.groupBy(x => (x.getString(0),x.getInt(1),x.getInt(2)))
    .map( x => {

        val tin = x(0).getString(0)
        val year = x(0).getInt(1)
        val month = x(0).getInt(2)
        val use = x(0).getStruct(3).getFloat(4)
        var sum:Float = 0.0F
        val nums = x(0).getStruct(3).getInt(5)

        for (i <- x.indices)
                 {
                      val v = x(i).getStruct(3)
                      val n = x(i).getStruct(3).getInt(5)
                      var next = n(i+1)
                      var prev = n(i-1)

                      if(nums == next || nums == prev)
                      {
                         sum  =  sum + v.getFloat(4)
                      }
                      else
                      {
                          sum
                      }
                      }
                      (tin,year,nums)
                }
            )

I need to get data as below

 numbers            next             prev
   0                  1              null
   1                  0              0
   0                  1              1
   1                  1              0
   1                  0              1
   0                  1              1
   1                  1              0
   1                  1              1
   1                  1              1
   1                  0              1
   0                null             1

Body:
Here is an answer to compare two rows (as I have no Spark setup I use general Scala features).

If l is a IterableLike, e.g. a Seqor a List you have a function sliding.

So here is an example:

val l = Seq(1,2,3,4,5)

l.sliding(2) // gives you Seq(List(1,2),List(2,1)..)
 .map{case x::y::_ => //here you can compare these two values

In your case x and y is maybe a more complex type.


问:
how to filter all string sequence in array using javascript
I have a large array, and I want to filter it based on a string I pass it. This string could be one or two characters, up to an entire string.

Here's an example array:

```<code>var data = ["bourbon", "beer", "electric"]
</code>```

If I pass e, I want the result ["electric", "beer"].

How can I achieve this functionality?

答:
```<code>var data = ["bourbon","beer", "electric"]
var result = data.filter(c => /e/i.test(c))
console.log('data',result);
</code>```

Body:
I have a large array, and I want to filter it based on a string I pass it. This string could be one or two characters, up to an entire string.

Here's an example array:

var data = ["bourbon", "beer", "electric"]

If I pass e, I want the result ["electric", "beer"].

How can I achieve this functionality?


问:
PHP 5 second countdown (CLI, not JavaScript)
I am writing a PHP CLI (command line) script that will do some irreversible damage if it is run by accident. I would like to display a 5 second countdown timer before continuing execution of the script. How can I do this with PHP?</p>

答:
To add my two cents, here's how you can add a confirmation prompt.

```<code><?php

echo "Continue? (Y/N) - ";

$stdin = fopen('php://stdin', 'r');
$response = fgetc($stdin);
if ($response != 'Y') {
   echo "Aborted.\n";
   exit;
}

$seconds = 5;

for ($i = $seconds; $i > 0; --$i) {
   echo $i;
   usleep(250000);
   echo '.';
   usleep(250000);
   echo '.';
   usleep(250000);
   echo '.';
   usleep(250000);
}

echo " Running NOW\n";
// run command here
</code>```

(You have to type 'Y' then hit Enter.)

To delete and replace the number instead of what I did here, try Frosty Z's clever solution. Alternatively, you can get fancy using ncurses. See this tutorial.

ContentLicense: CC BY-SA 3.0

Body:
To add my two cents, here's how you can add a confirmation prompt.

<?php

echo "Continue? (Y/N) - ";

$stdin = fopen('php://stdin', 'r');
$response = fgetc($stdin);
if ($response != 'Y') {
   echo "Aborted.\n";
   exit;
}

$seconds = 5;

for ($i = $seconds; $i > 0; --$i) {
   echo $i;
   usleep(250000);
   echo '.';
   usleep(250000);
   echo '.';
   usleep(250000);
   echo '.';
   usleep(250000);
}

echo " Running NOW\n";
// run command here

(You have to type 'Y' then hit Enter.)

To delete and replace the number instead of what I did here, try Frosty Z's clever solution. Alternatively, you can get fancy using ncurses. See this tutorial.


问:
Object of ‘NoneType’ has no len() - error
```<code>z=[]
while len(z)<8:
       z=z.append(1)
</code>```

This programmes says error in the line where the while loop is. The error is mentioned in the title. What should I do ?

答:
You should not use z = z.append(1) but z.append(1) as z.append() returns None.

After the first loop z will not be a list anymore, hence the error.

Body:
z=[]
while len(z)<8:
       z=z.append(1)

This programmes says error in the line where the while loop is. The error is mentioned in the title. What should I do ?


答:
For an O(N) solution instead of O(N^2), use a Set instead (Set.has is O(1), whereas String.prototype.includes is O(N)):

const data = ["bourbon", "beer", "electric"];
const setByData = data.reduce((a, str) => {
  a[str] = new Set(str);
  return a;
}, {});
console.log(
  Object.entries(setByData)
    .filter(([, set]) => set.has('e'))
    .map(([str]) => str)
);```

Title: how to filter all string sequence in array using javascript


问:
How to get next n days date from the given date
I am able to next 15 days date from current date, but when i tried to give custom date instead of current date, it not working.

```<code> let date = sharedAppDelegate.dueDate
 let givenDate = Utility.convertStringToDate(format: "yyyy-MM-dd",
dateString: date)

let futureDate = (givenDate as NSCalendar).date(byAdding: dateComponents, to: Date()) ?? Date()
</code>```

Third line gives error like Date? is not convertible to NSCalendar.
Expected result:- futureDate should be next 15 date from givenDate

答:
You can extend Date class like this.

```<code>extension Date {
   func dateByAddingDays(dateNum:Int) -> Date {
       return Calendar.gregorian.date(byAdding: .day, value: dateNum, to: self)!
   }
}
</code>```

Now create date object

```<code>let today = Date()
let dayAfterTomorrow = today.dateByAddingDays(dateNum:2)
debugPrint(dayAfterTomorrow)
</code>```

Body:
I am able to next 15 days date from current date, but when i tried to give custom date instead of current date, it not working.

 let date = sharedAppDelegate.dueDate
 let givenDate = Utility.convertStringToDate(format: "yyyy-MM-dd",
dateString: date)

let futureDate = (givenDate as NSCalendar).date(byAdding: dateComponents, to: Date()) ?? Date()

Third line gives error like Date? is not convertible to NSCalendar.
Expected result:- futureDate should be next 15 date from givenDate

Body:
You can extend Date class like this.

extension Date {
   func dateByAddingDays(dateNum:Int) -> Date {
       return Calendar.gregorian.date(byAdding: .day, value: dateNum, to: self)!
   }
}

Now create date object

let today = Date()
let dayAfterTomorrow = today.dateByAddingDays(dateNum:2)
debugPrint(dayAfterTomorrow)


问:
Hide the outside element on click of parent div
This is my HTML code:

```<code><html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <body>
     <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
       <div class="price-box price-final_price">
           <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display:
           inline;">From</span>100</span>

          </div>
     </div>

   <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
     <div class="price-box price-final_price">
          <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>200</span>

        </div>
    </div>

    <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
     <div class="price-box price-final_price">
          <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>300</span>

          </div>
  </div>
 <script>
  $(document).ready(function($){
     $('.product-item-details .swatch-option').live("click",function(){
        $(this).next('.price-final_price .price-container .price-label').hide();

    });
  });
  <script>

 </body>
</head>
</html>
</code>```

I need to hide "From" label of the span element "price-label" when a particular div is clicked.

The above jQuery code is not working for me,

Any help would be greatly appreciated. Thanks

答:
Well first of all As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

Also, your '.next' is taking just next sibling, but what you need is to take,
".price-container .price-label" of '.price-final_price'
So the correct way is :

```<code>$(document).ready(function() {
    $('.swatch-option').on("click", function() {
        $(this).next('.price-final_price').find(".price-container .price-label").hide();
  });
});
</code>```

Also, some suggestions :

You are using jquery/3.2.1/

I suggest using 3.4.1 "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js

You included everything inside your 'head' tag.
I suggest to limit it with only scripts, like so :

```<code><head>
  <script deffer src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" type="text/javascript"></script>
  <script deffer src="yourjQueryFile.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="yourCssFile.css">
</head>
<body>
  {Your code here}
</body>
</code>```

You can read about it here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML

Separate JS HTML and CSS files, and then include them into the  tag, as shown above. The modular way is always better and cleaner.

JSFiddle DEMO

Body:
This is my HTML code:

Large

            From100

Large

            From200

Large

            From300

Body:
Well first of all As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

Also, your '.next' is taking just next sibling, but what you need is to take,
".price-container .price-label" of '.price-final_price'
So the correct way is :

$(document).ready(function() {
    $('.swatch-option').on("click", function() {
        $(this).next('.price-final_price').find(".price-container .price-label").hide();
  });
});

Also, some suggestions :

You are using jquery/3.2.1/

I suggest using 3.4.1 "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js

You included everything inside your 'head' tag.
I suggest to limit it with only scripts, like so :

<head>
  <script deffer src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" type="text/javascript"></script>
  <script deffer src="yourjQueryFile.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="yourCssFile.css">
</head>
<body>
  {Your code here}
</body>

You can read about it here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML

Separate JS HTML and CSS files, and then include them into the  tag, as shown above. The modular way is always better and cleaner.

JSFiddle DEMO


问:
Is HAML a Better Tool for Experienced Ruby/Rails Developers?
One of the joys of being a new Ruby on Rails student/developer is the constant discovery of new Gems to make my life more fun or easier. Recently, I "discovered" HAML, which appears to be a fantastic tool for making ERB code even more readable than it already is. However, I wonder if it is a good idea for newer developers, like myself, to embrace a tool like HAML early on, or if it would be smarter to hold off until my expertise in plain Ruby / Rails code has matured. My worry, I suppose, is that embracing a tool like HAML too early might impede my full understanding of Ruby through the coding "shortcuts" it offers. What do you experienced coders say? </p>

答: Haml is a great tool and I think you shouldn't worry about using it whatsoever.  It makes your HTML so much more readable.  It doesn't take anything away from the core ruby on rails learning.  Use it and love it.</p>


问:
Why is Touch Ui FileUpload is rendered as button?
I need to migrate from Classic UI's html5smartfile xtype to Touch UI's fileupload resource type (/libs/granite/ui/components/coral/foundation/form/fileupload). But there are only a button after conversion ("Drop an asset" area is missing).

What should I do for granite component looked as it was before in Classic UI?

Classic UI:

```<code><file
    jcr:primaryType="cq:Widget"
    allowUpload="{Boolean}false"
    autoUploadDelay="1"
    ddAccept="application/pdf"
    ddGroups="[media]"
    fieldLabel="File"
    fileNameParameter="./fileName"
    fileReferenceParameter="./fileReference"
    mimeTypes="application/pdf"
    name="./file"
    sizeLimit="25"
    xtype="html5smartfile"/>
</code>```

Touch UI:

```<code><file
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/fileupload"
    fieldLabel="File"
    fileNameParameter="./fileName"
    fileReferenceParameter="./fileReference"
    mimeTypes="[application/pdf]"
    multiple="{Boolean}false"
    name="./file"
    sizeLimit="{Long}25"/>
</code>```

Classic UI render
Touch UI render

答:
In your cq:dialog:

```<code><file
    jcr:primaryType="nt:unstructured"
    sling:resourceType="cq/gui/components/authoring/dialog/fileupload"
    autoStart="{Boolean}false"
    class="cq-droptarget"
    fileNameParameter="./fileName"
    fileReferenceParameter="./fileReference"
    mimeTypes="[image/gif,image/jpeg,image/png,image/webp,image/tiff,image/svg+xml]"
    multiple="{Boolean}false"
    name="./file"
    title="Upload Image Asset"
    uploadUrl="${suffix.path}"
    useHTML5="{Boolean}true"/>
</code>```

In your cq:editConfig:

```<code><cq:dropTargets jcr:primaryType="nt:unstructured">
    <image
        jcr:primaryType="cq:DropTargetConfig"
        accept="[image/gif,image/jpeg,image/png,image/webp,image/tiff,image/svg+xml]"
        groups="[media]"
        propertyName="./fileReference">
        <parameters
            jcr:primaryType="nt:unstructured"
            imageCrop=""
            imageMap=""
            imageRotate=""/>
    </image>
</cq:dropTargets>
</code>```

This is based on the Core Components Image v2, which you probably should use:

http://opensource.adobe.com/aem-core-wcm-components/library/image.html

https://github.com/adobe/aem-core-wcm-components/tree/master/content/src/content/jcr_root/apps/core/wcm/components/image/v2/image

Body:
I need to migrate from Classic UI's html5smartfile xtype to Touch UI's fileupload resource type (/libs/granite/ui/components/coral/foundation/form/fileupload). But there are only a button after conversion ("Drop an asset" area is missing).

What should I do for granite component looked as it was before in Classic UI?

Classic UI:

<file
    jcr:primaryType="cq:Widget"
    allowUpload="{Boolean}false"
    autoUploadDelay="1"
    ddAccept="application/pdf"
    ddGroups="[media]"
    fieldLabel="File"
    fileNameParameter="./fileName"
    fileReferenceParameter="./fileReference"
    mimeTypes="application/pdf"
    name="./file"
    sizeLimit="25"
    xtype="html5smartfile"/>

Touch UI:

<file
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/fileupload"
    fieldLabel="File"
    fileNameParameter="./fileName"
    fileReferenceParameter="./fileReference"
    mimeTypes="[application/pdf]"
    multiple="{Boolean}false"
    name="./file"
    sizeLimit="{Long}25"/>

Classic UI render
Touch UI render

Body:
In your cq:dialog:

<file
    jcr:primaryType="nt:unstructured"
    sling:resourceType="cq/gui/components/authoring/dialog/fileupload"
    autoStart="{Boolean}false"
    class="cq-droptarget"
    fileNameParameter="./fileName"
    fileReferenceParameter="./fileReference"
    mimeTypes="[image/gif,image/jpeg,image/png,image/webp,image/tiff,image/svg+xml]"
    multiple="{Boolean}false"
    name="./file"
    title="Upload Image Asset"
    uploadUrl="${suffix.path}"
    useHTML5="{Boolean}true"/>

In your cq:editConfig:

<cq:dropTargets jcr:primaryType="nt:unstructured">
    <image
        jcr:primaryType="cq:DropTargetConfig"
        accept="[image/gif,image/jpeg,image/png,image/webp,image/tiff,image/svg+xml]"
        groups="[media]"
        propertyName="./fileReference">
        <parameters
            jcr:primaryType="nt:unstructured"
            imageCrop=""
            imageMap=""
            imageRotate=""/>
    </image>
</cq:dropTargets>

This is based on the Core Components Image v2, which you probably should use:

http://opensource.adobe.com/aem-core-wcm-components/library/image.html

https://github.com/adobe/aem-core-wcm-components/tree/master/content/src/content/jcr_root/apps/core/wcm/components/image/v2/image


问:
How to solve a respawn problem for a character in FPS view?
I have this script that respawns my character at the coordinate of the cube when I press the R key. It works, but as soon as I release the key, the character returns to where he was before.

This script works on a character in the third person but not in view at first. So I think there must be some element in the basic script of the FPS view that prevents to work, but I can not find which one, and I'm novice at Unity so it's difficult to identify what all the functions are for.

I do not know if I can post the character code in FPS view as it is quite long, otherwise it can be found on asset store.

```<code>{
    public Transform spawnPoint;

    void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {

            player.transform.position = spawnPoint.position;
        }

    }
}
</code>```

答:
This script is not the problem. Check the rest of scripts where you update the position. I guess you are assigning a vector saved on another script when you move the player.
Maybe with more info about other scripts I could be more accurate in the answer.</p>

Body:
I have this script that respawns my character at the coordinate of the cube when I press the R key. It works, but as soon as I release the key, the character returns to where he was before.

This script works on a character in the third person but not in view at first. So I think there must be some element in the basic script of the FPS view that prevents to work, but I can not find which one, and I'm novice at Unity so it's difficult to identify what all the functions are for.

I do not know if I can post the character code in FPS view as it is quite long, otherwise it can be found on asset store.

{
    public Transform spawnPoint;

    void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {

            player.transform.position = spawnPoint.position;
        }

    }
}


问:
Add empty document to collection
I am trying to add a new document and collection to my database. I know I can just add a document and if the collection where it is supposed to be will be added if doe not exist.
My question is: how can I add an empty document to a new collection in my database?

I have tried this code, from the android developers site:

```<code>ApiFuture<WriteResult> future = db.collection("cities").document("LA");
// ...
// future.get() blocks on response
System.out.println("Update time : " + future.get().getUpdateTime());
</code>```

But it gives me error in the ApiFuture part that I can't resolve.
So I tried this:

```<code>db.collection(mail).document("tarefa");
</code>```

(mail is a string)
But it does not work.
Does anyone know what I should do?

答:
So I adapted the answer from Frank van Puffelen and it solved my problem. Here is how I did it:</p>

```<code>db.collection(mail).document("tarefa").set(new HashMap<String, Object>());
</code>```

Title: Add empty document to collection

Body:
I am trying to add a new document and collection to my database. I know I can just add a document and if the collection where it is supposed to be will be added if doe not exist.
My question is: how can I add an empty document to a new collection in my database?

I have tried this code, from the android developers site:

ApiFuture<WriteResult> future = db.collection("cities").document("LA");
// ...
// future.get() blocks on response
System.out.println("Update time : " + future.get().getUpdateTime());

But it gives me error in the ApiFuture part that I can't resolve.
So I tried this:

db.collection(mail).document("tarefa");

(mail is a string)
But it does not work.
Does anyone know what I should do?

Body:
So I adapted the answer from Frank van Puffelen and it solved my problem. Here is how I did it:

db.collection(mail).document("tarefa").set(new HashMap<String, Object>());


问:
localStorage vs sessionStorage vs cookies
I am working in an app where I need to keep some data during the user is logged in and I have that question, what is the difference among
localStorage, sessionStorage, cookies ???

I was asking what can I use in order to persist some data in the DOM, even if the user refresh the page, some people says: use sessionStorage, or localStorage, then, someone came up with the idea of use ngCookies because it works in every browser, but, which should I use ?

答:
LocalStorage - Stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data. Storage limit is the maximum amongst the three

SessionStorage - The sessionStorage object stores data only for a session, meaning that the data is stored until the browser (or tab) is closed. Data is never transferred to the server. Storage limit is larger than a cookie (at least 5MB).

Cookie - Stores data that has to be sent back to the server with subsequent requests. Its expiration varies based on the type and the expiration duration can be set from either server-side or client-side (normally from server-side). Cookies are primarily for server-side reading (can also be read on client-side), localStorage and sessionStorage can only be read on client-side. Size must be less than 4KB. Cookies can be made secure by setting the httpOnly flag as true for that cookie. This prevents client-side access to that cookie.


问:
Import javascript library into React Native
I have a javascript library in my project.
This library need external jquery libraries like this:

```<code><script src="jquery.min.js"></script>
<script src="jquery.signalR.js"></script>
<script src="myLibrary.min.js"></script>
</code>```

Is there a way to use this library on my React Native project?
Can I import jquery into my project?
Thanks

答:
You can't use jQuery with react-native.

JQuery heavily relies on HTML DOM and CSS where react-native has their
  own DOM-like native view hierarchy with their own style implementation
  which is similar to subset of CSS (flex-box) but it is implemented
  differently.

Just to put it in perspective - React-Native app is NOT an HTML/Hybrid
  app - it's a native app with logic controlled by Javascript and using
  react patterns with virtual view hierarchy representation. The only
  common part with web apps is Javascript engine (no CSS/HTML). Phonegap
  apps are Hybrid HTML apps using web views so they can use
  frameworks/plugins that are not pure javascript but tied to HTML/CSS.
  source : stackoverflow

Body:
I have a javascript library in my project.
This library need external jquery libraries like this:

Is there a way to use this library on my React Native project?
Can I import jquery into my project?
Thanks


问:
Az / AzureRM / Legacy Azure Powershell Conflicts
I'm trying to upgrade from AzureRM to the new Az module for powershell. We still have multiple usages of "legacy" service management API resources, such as classic Azure Cloud Services, and these (as far as I know) still require the use of the old Azure powershell module.

I've uninstalled all AzureRM modules and then installed the new Az modules. But doing this appears to break the legacy Azure module. It seems that there is a dependency between the Azure module and AzureRM. Running any service management command, such as "Get-AzureService" results in the following:

```<code>PS C:\WINDOWS\system32> Get-AzureService
Get-AzureService : Exception has been thrown by the target of an invocation.
At line:1 char:1
+ Get-AzureService
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzureService], TargetInvocationException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.HostedServices.GetAzureServiceCommand
</code>```

I tried updating to the latest Azure powershell module (Update-Module Azure). This appears to also install AzureRM.profile.

Since that module can't be installed/used at the same time as the Az module, I'm at a loss as how to continue.

Is it the case that there is no way to use the legacy service management APIs via powershell if you also want to use the new Az module?

答:
The Az module has a compatibility mode to help you use existing scripts while you update to the new syntax. Try to run Enable-AzureRmAlias cmdlet enables a compatibility mode before you want to run AzureRM commands in a new Az session.

You could get more details from migrating existing scripts to Az

Body:
I'm trying to upgrade from AzureRM to the new Az module for powershell. We still have multiple usages of "legacy" service management API resources, such as classic Azure Cloud Services, and these (as far as I know) still require the use of the old Azure powershell module.

I've uninstalled all AzureRM modules and then installed the new Az modules. But doing this appears to break the legacy Azure module. It seems that there is a dependency between the Azure module and AzureRM. Running any service management command, such as "Get-AzureService" results in the following:

PS C:\WINDOWS\system32> Get-AzureService
Get-AzureService : Exception has been thrown by the target of an invocation.
At line:1 char:1
+ Get-AzureService
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzureService], TargetInvocationException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.HostedServices.GetAzureServiceCommand

I tried updating to the latest Azure powershell module (Update-Module Azure). This appears to also install AzureRM.profile.

Since that module can't be installed/used at the same time as the Az module, I'm at a loss as how to continue.

Is it the case that there is no way to use the legacy service management APIs via powershell if you also want to use the new Az module?


问:
Parse Complex JSON -- Map
I need to parse the complex JSON (below) IN SCALA to get the values of "expression" and "value" in "measure" key i.e I need List (COUNT, COUNT_DISTINCT ...) and List (1,tbl1.USER_ID ...).

I tried multiple options, but it is not working. Any help is appreciated

```<code>{
  "uuid": "uuidddd",
  "last_modified": 1559080222953,
  "version": "2.6.1.0",
  "name": "FULL_DAY_2_mand_date",
  "is_draft": false,
  "model_name": "FULL_DAY_1_may05",
  "description": "",
  "null_string": null,
  "dimensions": [
    {
      "name": "PLATFORM",
      "table": "tbl1",
      "column": "PLATFORM",
      "derived": null
    },
    {
      "name": "OS_VERSION",
      "table": "tbl1",
      "column": "OS_VERSION",
      "derived": null
    }
  ],
  "measures": [
    {
      "name": "_COUNT_",
      "function": {
        "expression": "COUNT",
        "parameter": {
          "type": "constant",
          "value": "1"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "UU",
      "function": {
        "expression": "COUNT_DISTINCT",
        "parameter": {
          "type": "column",
          "value": "tbl1.USER_ID"
        },
        "returntype": "hllc(12)"
      }
    },
    {
      "name": "CONT_SIZE",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.SIZE"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "CONT_COUNT",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.COUNT"
        },
        "returntype": "bigint"
      }
    }
  ],
  "dictionaries": [],
  "rowkey": {
    "rowkey_columns": [
      {
        "column": "tbl1.OS_VERSION",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.PLATFORM",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.DEVICE_FAMILY",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      }
    ]
  },
  "hbase_mapping": {
    "column_family": [
      {
        "name": "F1",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "_COUNT_",
              "CONT_SIZE",
              "CONT_COUNT"
            ]
          }
        ]
      },
      {
        "name": "F2",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "UU"
            ]
          }
        ]
      }
    ]
  },
  "aggregation_groups": [
    {
      "includes": [
        "tbl1.PLATFORM",
        "tbl1.OS_VERSION"
      ],
      "select_rule": {
        "hierarchy_dims": [],
        "mandatory_dims": [
          "tbl1.DATE_HR"
        ],
        "joint_dims": []
      }
    }
  ],
  "signature": "ttrrs==",
  "notify_list": [],
  "status_need_notify": [
    "ERROR",
    "DISCARDED",
    "SUCCEED"
  ],
  "partition_date_start": 0,
  "partition_date_end": 3153600000000,
  "auto_merge_time_ranges": [
    604800000,
    2419200000
  ],
  "volatile_range": 0,
  "retention_range": 0,
  "engine_type": 4,
  "storage_type": 2,
  "override_kylin_properties": {
    "job.queuename": "root.production.P0",
    "is-mandatory-only-valid": "true"
  },
  "cuboid_black_list": [],
  "parent_forward": 3,
  "mandatory_dimension_set_list": [],
  "snapshot_table_desc_list": []
}
</code>```

This is a snippet of the code I tried, and it is giving a null list

```<code>import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = org.json4s.DefaultFormats

case class Function (
                      expression: String,
                      parameter: Parameter,
                      returntype: String
                    )

case class Parameter (
                       `type`: String,
                       value: String
                     )

case class Measures (
                      name: String,
                      function: Function
                    )

case class AllMeasuresData(uuid: String, measure: List[Measures])

val data = parse(tmp).extract[AllMeasuresData]
val names = data.measure.map(_.name)

println(names)

case class AllMeasuresData(uuid: String, measure: List[Measures])

val data = parse(tmp).extract[AllMeasuresData]
val names = data.measure.map(_.name)

println(names)
</code>```

答:
Your Parameter class does not match the JSON because you have used type1 rather than type as the field name. Use backticks to use "type" as a field name even though it is a reserved word:

```<code>case class Parameter (
    `type`: String,
    value: String
  )
</code>```

You also need to change the Function class as it has returntype1 rather than returntype:

```<code>case class Function (
    expression: String,
    parameter: Parameter,
    returntype: String
  )
</code>```

The names of the fields in Scala must exactly match the names of the fields in the JSON. Extra fields in the JSON are ignored, but all the fields in the Scala must have matching fields in the JSON. If there are optional fields in the JSON then the Scala field type should be Option[...].

Title: Parse Complex JSON -- Map

Body:
I need to parse the complex JSON (below) IN SCALA to get the values of "expression" and "value" in "measure" key i.e I need List (COUNT, COUNT_DISTINCT ...) and List (1,tbl1.USER_ID ...).

I tried multiple options, but it is not working. Any help is appreciated

{
  "uuid": "uuidddd",
  "last_modified": 1559080222953,
  "version": "2.6.1.0",
  "name": "FULL_DAY_2_mand_date",
  "is_draft": false,
  "model_name": "FULL_DAY_1_may05",
  "description": "",
  "null_string": null,
  "dimensions": [
    {
      "name": "PLATFORM",
      "table": "tbl1",
      "column": "PLATFORM",
      "derived": null
    },
    {
      "name": "OS_VERSION",
      "table": "tbl1",
      "column": "OS_VERSION",
      "derived": null
    }
  ],
  "measures": [
    {
      "name": "_COUNT_",
      "function": {
        "expression": "COUNT",
        "parameter": {
          "type": "constant",
          "value": "1"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "UU",
      "function": {
        "expression": "COUNT_DISTINCT",
        "parameter": {
          "type": "column",
          "value": "tbl1.USER_ID"
        },
        "returntype": "hllc(12)"
      }
    },
    {
      "name": "CONT_SIZE",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.SIZE"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "CONT_COUNT",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.COUNT"
        },
        "returntype": "bigint"
      }
    }
  ],
  "dictionaries": [],
  "rowkey": {
    "rowkey_columns": [
      {
        "column": "tbl1.OS_VERSION",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.PLATFORM",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.DEVICE_FAMILY",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      }
    ]
  },
  "hbase_mapping": {
    "column_family": [
      {
        "name": "F1",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "_COUNT_",
              "CONT_SIZE",
              "CONT_COUNT"
            ]
          }
        ]
      },
      {
        "name": "F2",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "UU"
            ]
          }
        ]
      }
    ]
  },
  "aggregation_groups": [
    {
      "includes": [
        "tbl1.PLATFORM",
        "tbl1.OS_VERSION"
      ],
      "select_rule": {
        "hierarchy_dims": [],
        "mandatory_dims": [
          "tbl1.DATE_HR"
        ],
        "joint_dims": []
      }
    }
  ],
  "signature": "ttrrs==",
  "notify_list": [],
  "status_need_notify": [
    "ERROR",
    "DISCARDED",
    "SUCCEED"
  ],
  "partition_date_start": 0,
  "partition_date_end": 3153600000000,
  "auto_merge_time_ranges": [
    604800000,
    2419200000
  ],
  "volatile_range": 0,
  "retention_range": 0,
  "engine_type": 4,
  "storage_type": 2,
  "override_kylin_properties": {
    "job.queuename": "root.production.P0",
    "is-mandatory-only-valid": "true"
  },
  "cuboid_black_list": [],
  "parent_forward": 3,
  "mandatory_dimension_set_list": [],
  "snapshot_table_desc_list": []
}

This is a snippet of the code I tried, and it is giving a null list

import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = org.json4s.DefaultFormats

case class Function (
                      expression: String,
                      parameter: Parameter,
                      returntype: String
                    )

case class Parameter (
                       `type`: String,
                       value: String
                     )

case class Measures (
                      name: String,
                      function: Function
                    )

case class AllMeasuresData(uuid: String, measure: List[Measures])

val data = parse(tmp).extract[AllMeasuresData]
val names = data.measure.map(_.name)

println(names)

case class AllMeasuresData(uuid: String, measure: List[Measures])

val data = parse(tmp).extract[AllMeasuresData]
val names = data.measure.map(_.name)

println(names)

Body:
Your Parameter class does not match the JSON because you have used type1 rather than type as the field name. Use backticks to use "type" as a field name even though it is a reserved word:

case class Parameter (
    `type`: String,
    value: String
  )

You also need to change the Function class as it has returntype1 rather than returntype:

case class Function (
    expression: String,
    parameter: Parameter,
    returntype: String
  )

The names of the fields in Scala must exactly match the names of the fields in the JSON. Extra fields in the JSON are ignored, but all the fields in the Scala must have matching fields in the JSON. If there are optional fields in the JSON then the Scala field type should be Option[...].


问:
Azure Function App Container Failing to Start at Minikube Container Error: The listener for function 'EventHubCSharpFunc' was unable to start
I created a very simple Azure functionApp using visual Studio Code which does nothing fancy but logs the received message(Function App listen to Eventhub message in Azure). This works and get hosted well when i debug the function app locally. However, when I publish this into minikube as container, it throws below error:

```<code>The listener for function 'EventHubCSharpFunc' was unable to start.
Microsoft.Azure.WebJobs.Host.Listeners.FunctionListenerException: The listener for function 'EventHubCSharpFunc' was unable to start. ---> Microsoft.Azure.EventHubs.Processor.EventProcessorConfigurationException: Encountered error while fetching the list of EventHub PartitionIds ---> System.Net.Sockets.SocketException: Resource temporarily unavailable
   at Microsoft.Azure.EventHubs.Amqp.AmqpEventHubClient.CreateConnectionAsync(TimeSpan timeout)
   at Microsoft.Azure.Amqp.FaultTolerantAmqpObject`1.OnCreateAsync(TimeSpan timeout)
   at Microsoft.Azure.Amqp.Singleton`1.CreateValue(TaskCompletionSource`1 tcs, TimeSpan timeout)
   at Microsoft.Azure.Amqp.Singleton`1.GetOrCreateAsync(TimeSpan timeout)
   at Microsoft.Azure.EventHubs.Amqp.Management.AmqpServiceClient.OpenRequestResponseLinkAsync(String type, String address, Nullable`1 entityType, String[] requiredClaims, TimeSpan timeout)
   at Microsoft.Azure.EventHubs.Amqp.Management.AmqpServiceClient.OpenLinkAsync(TimeSpan timeout)
   at Microsoft.Azure.Amqp.FaultTolerantAmqpObject`1.OnCreateAsync(TimeSpan timeout)
   at Microsoft.Azure.Amqp.Singleton`1.CreateValue(TaskCompletionSource`1 tcs, TimeSpan timeout)
   at Microsoft.Azure.Amqp.Singleton`1.GetOrCreateAsync(TimeSpan timeout)
   at Microsoft.Azure.EventHubs.Amqp.Management.AmqpServiceClient.GetRuntimeInformationAsync()
   at Microsoft.Azure.EventHubs.Amqp.AmqpEventHubClient.OnGetRuntimeInformationAsync()
   at Microsoft.Azure.EventHubs.EventHubClient.GetRuntimeInformationAsync()
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.GetPartitionIdsAsync()
   --- End of inner exception stack trace ---
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.GetPartitionIdsAsync()
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.GetPartitionIdsAsync()
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.InitializeStoresAsync()
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.StartAsync()
   at Microsoft.Azure.EventHubs.Processor.EventProcessorHost.RegisterEventProcessorFactoryAsync(IEventProcessorFactory factory, EventProcessorOptions processorOptions)
   at Microsoft.Azure.WebJobs.EventHubs.EventHubListener.StartAsync(CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Extensions.EventHubs\Listeners\EventHubListener.cs:line 46
   at Microsoft.Azure.WebJobs.Host.Listeners.FunctionListener.StartAsync(CancellationToken cancellationToken, Boolean allowRetry) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Listeners\FunctionListener.cs:line 68
</code>```

I tried to check if my cluster is having internet access, but I am successfully able to ping internet IP from other containers in minikube.

```<code>public static class EventHubCSharpFunc
    {
        [FunctionName("EventHubCSharpFunc")]
        public static async Task Run([EventHubTrigger("containertestevthub", Connection = "EventGridPerfEventHun_RootManageSharedAccessKey_EVENTHUB")] EventData[] events, ILogger log)
        {
            var exceptions = new List<Exception>();

            foreach (EventData eventData in events)
            {
                try
                {
                    string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);

                    // Replace these two lines with your processing logic.
                    log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
                    await Task.Yield();
                }
                catch (Exception e)
                {
                    // We need to keep processing the rest of the batch - capture this exception and continue.
                    // Also, consider capturing details of the message that failed processing so it can be processed again later.
                    exceptions.Add(e);
                }
            }

            // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

            if (exceptions.Count > 1)
                throw new AggregateException(exceptions);

            if (exceptions.Count == 1)
                throw exceptions.Single();
        }
    }
</code>```

答:
looking into "EventHubCSharpFunc was unable to start" and "Resource temporarily unavailable", please try to connect from Your APP POD to Eventhub.

Please verify if your connection and credentials are working inside Your APP POD.
You can find more about how to pass credentials as Secrets into your POD or Create a Secret based on existing Docker credentials here and here.

For troubleshooting purposes please use those below commands to get more information from your cluster:

```<code>kubectl log <your_pod_with_application>
kubectl describe <your_pod_with_application>
kubectl get events
kubectl get all --all-namespaces
</code>```

Body:
I created a very simple Azure functionApp using visual Studio Code which does nothing fancy but logs the received message(Function App listen to Eventhub message in Azure). This works and get hosted well when i debug the function app locally. However, when I publish this into minikube as container, it throws below error:

The listener for function 'EventHubCSharpFunc' was unable to start.
Microsoft.Azure.WebJobs.Host.Listeners.FunctionListenerException: The listener for function 'EventHubCSharpFunc' was unable to start. ---> Microsoft.Azure.EventHubs.Processor.EventProcessorConfigurationException: Encountered error while fetching the list of EventHub PartitionIds ---> System.Net.Sockets.SocketException: Resource temporarily unavailable
   at Microsoft.Azure.EventHubs.Amqp.AmqpEventHubClient.CreateConnectionAsync(TimeSpan timeout)
   at Microsoft.Azure.Amqp.FaultTolerantAmqpObject`1.OnCreateAsync(TimeSpan timeout)
   at Microsoft.Azure.Amqp.Singleton`1.CreateValue(TaskCompletionSource`1 tcs, TimeSpan timeout)
   at Microsoft.Azure.Amqp.Singleton`1.GetOrCreateAsync(TimeSpan timeout)
   at Microsoft.Azure.EventHubs.Amqp.Management.AmqpServiceClient.OpenRequestResponseLinkAsync(String type, String address, Nullable`1 entityType, String[] requiredClaims, TimeSpan timeout)
   at Microsoft.Azure.EventHubs.Amqp.Management.AmqpServiceClient.OpenLinkAsync(TimeSpan timeout)
   at Microsoft.Azure.Amqp.FaultTolerantAmqpObject`1.OnCreateAsync(TimeSpan timeout)
   at Microsoft.Azure.Amqp.Singleton`1.CreateValue(TaskCompletionSource`1 tcs, TimeSpan timeout)
   at Microsoft.Azure.Amqp.Singleton`1.GetOrCreateAsync(TimeSpan timeout)
   at Microsoft.Azure.EventHubs.Amqp.Management.AmqpServiceClient.GetRuntimeInformationAsync()
   at Microsoft.Azure.EventHubs.Amqp.AmqpEventHubClient.OnGetRuntimeInformationAsync()
   at Microsoft.Azure.EventHubs.EventHubClient.GetRuntimeInformationAsync()
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.GetPartitionIdsAsync()
   --- End of inner exception stack trace ---
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.GetPartitionIdsAsync()
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.GetPartitionIdsAsync()
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.InitializeStoresAsync()
   at Microsoft.Azure.EventHubs.Processor.PartitionManager.StartAsync()
   at Microsoft.Azure.EventHubs.Processor.EventProcessorHost.RegisterEventProcessorFactoryAsync(IEventProcessorFactory factory, EventProcessorOptions processorOptions)
   at Microsoft.Azure.WebJobs.EventHubs.EventHubListener.StartAsync(CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Extensions.EventHubs\Listeners\EventHubListener.cs:line 46
   at Microsoft.Azure.WebJobs.Host.Listeners.FunctionListener.StartAsync(CancellationToken cancellationToken, Boolean allowRetry) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Listeners\FunctionListener.cs:line 68

I tried to check if my cluster is having internet access, but I am successfully able to ping internet IP from other containers in minikube.

public static class EventHubCSharpFunc
    {
        [FunctionName("EventHubCSharpFunc")]
        public static async Task Run([EventHubTrigger("containertestevthub", Connection = "EventGridPerfEventHun_RootManageSharedAccessKey_EVENTHUB")] EventData[] events, ILogger log)
        {
            var exceptions = new List<Exception>();

            foreach (EventData eventData in events)
            {
                try
                {
                    string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);

                    // Replace these two lines with your processing logic.
                    log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
                    await Task.Yield();
                }
                catch (Exception e)
                {
                    // We need to keep processing the rest of the batch - capture this exception and continue.
                    // Also, consider capturing details of the message that failed processing so it can be processed again later.
                    exceptions.Add(e);
                }
            }

            // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

            if (exceptions.Count > 1)
                throw new AggregateException(exceptions);

            if (exceptions.Count == 1)
                throw exceptions.Single();
        }
    }

Body:
looking into "EventHubCSharpFunc was unable to start" and "Resource temporarily unavailable", please try to connect from Your APP POD to Eventhub.

Please verify if your connection and credentials are working inside Your APP POD.
You can find more about how to pass credentials as Secrets into your POD or Create a Secret based on existing Docker credentials here and here.

For troubleshooting purposes please use those below commands to get more information from your cluster:

kubectl log <your_pod_with_application>
kubectl describe <your_pod_with_application>
kubectl get events
kubectl get all --all-namespaces


问:
How to add values together from a database in windows form application
I'm trying to add all of a students course values together to get the average. The values are saved into a database but when I try add the values together and insert them into a text box it inserts both values into the text box instead of adding the values together.</p>

```<code>            string output = "";
            output += (dr["Course 1"].ToString());
            output += (dr["Course 2"].ToString());
            txtbxaverage.Text = output;

        }
</code>```

答:
I would do it like this

```<code>txtbaverage.Text = $"{decimal.Parse(dr["Course 1"])+decimal.Parse(dr["Course 2"])}";
</code>```

a string + string is equivalent to

```<code>"1" + "1" == "11"
</code>```

a decimal + decimal equivalent to

```<code>1 + 1 == 2
</code>```

so you need to convert for example

```<code>decimal.Parse("1") + decimal.Parse("1") == 2
</code>```

doing a direct cast (decimal)dr["Course 1"] if the dr["Course 1"] is an object will convert it to a decimal then it can be added

Body:
I'm trying to add all of a students course values together to get the average. The values are saved into a database but when I try add the values together and insert them into a text box it inserts both values into the text box instead of adding the values together.

            string output = "";
            output += (dr["Course 1"].ToString());
            output += (dr["Course 2"].ToString());
            txtbxaverage.Text = output;

        }

Body:
I would do it like this

txtbaverage.Text = $"{decimal.Parse(dr["Course 1"])+decimal.Parse(dr["Course 2"])}";

a string + string is equivalent to

"1" + "1" == "11"

a decimal + decimal equivalent to

1 + 1 == 2

so you need to convert for example

decimal.Parse("1") + decimal.Parse("1") == 2

doing a direct cast (decimal)dr["Course 1"] if the dr["Course 1"] is an object will convert it to a decimal then it can be added


问:
Can I Sync Pocket Access on Windows 7?
I have to sync a Pocket Access database with Access on the PC.  WMDC won't let me do that and ActiveSync won't run on Vista so I can't do it.  Works great on XP.

Windows 7 has an XP mode.  It runs XP in a virtual machine or something like that.

Question: Can I Sync Pocket Access on Windows Mobile 5.0 with Access on Windows 7 if I'm running in XP mode?

答:
Yes, you absolutely can.

It does run in a VM and that VM can access the USB ports.

Open XP mode and log in.  Make sure
ActiveSync is running in XP.

Attach the device to your physical
machine.

In XP mode, choose 'USB' in the top
menu.  You'll see a connected device
that won't necessarily be identified
properly but you'll be able to tell
which is it.

Works great.

ContentLicense: CC BY-SA 2.5

Title: Can I Sync Pocket Access on Windows 7?


问:
How to unflatten properties, ignored in other map?
Sources for my destination are spitted in root dto and its child property:

```<code>public class Source {
    public AccountSource {get;set;}
    public string AccountKey {get;set;}
    public string AccountPassword {get;set;}
}

public class AccountSource {
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class Dest
{
    public Account Account { get; set; }

    public class Account
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string Key { get; set; }
    }
}
</code>```

At now I have such mapping:

```<code>CreateMap<Source, Dest>()
    .ForPath(x => x.Account.Id, o => o.MapFrom(x => x.Account.Id))
    .ForPath(x => x.Account.Name, o => o.MapFrom(x => x.Account.Name))
    .ForPath(x => x.Account.Key, o => o.MapFrom(x => x.AccountKey))
    .ForPath(x => x.Account.Password, o => o.MapFrom(x => x.AccountPassword));
CreateMap<AccountSource, Dest.Account>()
    .ForAllMembers(x => x.Ignore());
</code>```

but it have one issue: new members added to Dest.Account will be not validated.

If remove ForPath and just leave

```<code>CreateMap<Source, Dest>();
CreateMap<AccountSource, Dest.Account>();
</code>```

than Password and Key are Unmapped, so I have to Ignore() them in such way CreateMap<AccountSource, Dest.Account>().ForMember(x => x.Password, x=> x.Ignore()).ForMember(x => x.Key, x=> x.Ignore()).

But then unflattening not working (props ignored absolutely, not only when account→account mapping occurred).

答:
Found another solution:</p>

```<code>CreateMap<Source, Dest>()
    .ForMember(x => x.Account, o => o.MapFrom(x => x));
CreateMap<Source, Dest.Account>()
    .ForMember(x => x.Id, o => o.MapFrom(x => x.AccountSource.Id))
    .ForMember(x => x.Name, o => o.MapFrom(x => x.AccountSource.Name))
    .ForMember(x => x.Password, o => o.MapFrom(x => x.AccountPassword))
    .ForMember(x => x.Key, o => o.MapFrom(x => x.AccountKey));
</code>```

Body:
Sources for my destination are spitted in root dto and its child property:

public class Source {
    public AccountSource {get;set;}
    public string AccountKey {get;set;}
    public string AccountPassword {get;set;}
}

public class AccountSource {
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class Dest
{
    public Account Account { get; set; }

    public class Account
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string Key { get; set; }
    }
}

At now I have such mapping:

CreateMap<Source, Dest>()
    .ForPath(x => x.Account.Id, o => o.MapFrom(x => x.Account.Id))
    .ForPath(x => x.Account.Name, o => o.MapFrom(x => x.Account.Name))
    .ForPath(x => x.Account.Key, o => o.MapFrom(x => x.AccountKey))
    .ForPath(x => x.Account.Password, o => o.MapFrom(x => x.AccountPassword));
CreateMap<AccountSource, Dest.Account>()
    .ForAllMembers(x => x.Ignore());

but it have one issue: new members added to Dest.Account will be not validated.

If remove ForPath and just leave

CreateMap<Source, Dest>();
CreateMap<AccountSource, Dest.Account>();

than Password and Key are Unmapped, so I have to Ignore() them in such way CreateMap<AccountSource, Dest.Account>().ForMember(x => x.Password, x=> x.Ignore()).ForMember(x => x.Key, x=> x.Ignore()).

But then unflattening not working (props ignored absolutely, not only when account→account mapping occurred).

Body:
Found another solution:

CreateMap<Source, Dest>()
    .ForMember(x => x.Account, o => o.MapFrom(x => x));
CreateMap<Source, Dest.Account>()
    .ForMember(x => x.Id, o => o.MapFrom(x => x.AccountSource.Id))
    .ForMember(x => x.Name, o => o.MapFrom(x => x.AccountSource.Name))
    .ForMember(x => x.Password, o => o.MapFrom(x => x.AccountPassword))
    .ForMember(x => x.Key, o => o.MapFrom(x => x.AccountKey));


问:
Problem adding values stored as variables to a java list
I am going to create a list that I want to add elements to.  I have obtained the elements from clients via them completing 3 dialogue boxes indicating their preferences for a new car, and now I want to add these entries to the list.

I have declared my instance variables and here is the constructor for my list:

```<code> public Car(String aMaker, String aModel, int aYearBuilt);
    {
        super();
        this.maker = aMaker;
        this.model = aModel;
        this.year = aYearBuilt;
    }
</code>```

I have successfully put the return from my first client's dialogue boxes into 3 variables, created thus:

```<code> String inputMaker;
 String inputModel;
 int inputYear;
</code>```

(I remembered to use Integer.parseInt to convert the dialogue input string to an int).

Now I want to put the values in a list:

```<code>List<Car> newCarDetails = new ArrayList<Car>();
</code>```

This is where I start to go wrong:

```<code> newCarDetails.add(new Car(inputMaker, inputModel, inputYear));
    return newCarDetails;
</code>```

Only I have clearly underestimated the task, because it doesn't work.  I just get a hashCode back.  Any help greatly appreciated.

答:
I don't know what your output media is, but you could iterate over the list to format the output:

```<code>for (Car newCar : newCarDetails) {
  System.out.println("Make: " + newCar.getAMaker());
  System.out.println("Model: " + newCar.getAModel());
  System.out.println("Year: " + newCar.getAYearBuilt());
}
</code>```

Alternatively, you could override Car's toString() method to regulate the formatting

```<code>class Car {
...

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append(this.aMaker);
    sb.append(",");
    sb.append(this.aModel);
    sb.append(",");
    sb.append(this.aYearBuilt);
    sb.append(",");

    return sb.toString();
  }
}

...

for (Car newCar : newCarDetails) {
  System.out.println(newCar.toString());
}
</code>```

Body:
I am going to create a list that I want to add elements to.  I have obtained the elements from clients via them completing 3 dialogue boxes indicating their preferences for a new car, and now I want to add these entries to the list.

I have declared my instance variables and here is the constructor for my list:

 public Car(String aMaker, String aModel, int aYearBuilt);
    {
        super();
        this.maker = aMaker;
        this.model = aModel;
        this.year = aYearBuilt;
    }

I have successfully put the return from my first client's dialogue boxes into 3 variables, created thus:

 String inputMaker;
 String inputModel;
 int inputYear;

(I remembered to use Integer.parseInt to convert the dialogue input string to an int).

Now I want to put the values in a list:

List<Car> newCarDetails = new ArrayList<Car>();

This is where I start to go wrong:

 newCarDetails.add(new Car(inputMaker, inputModel, inputYear));
    return newCarDetails;

Only I have clearly underestimated the task, because it doesn't work.  I just get a hashCode back.  Any help greatly appreciated.

Body:
I don't know what your output media is, but you could iterate over the list to format the output:

for (Car newCar : newCarDetails) {
  System.out.println("Make: " + newCar.getAMaker());
  System.out.println("Model: " + newCar.getAModel());
  System.out.println("Year: " + newCar.getAYearBuilt());
}

Alternatively, you could override Car's toString() method to regulate the formatting

class Car {
...

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append(this.aMaker);
    sb.append(",");
    sb.append(this.aModel);
    sb.append(",");
    sb.append(this.aYearBuilt);
    sb.append(",");

    return sb.toString();
  }
}

...

for (Car newCar : newCarDetails) {
  System.out.println(newCar.toString());
}


问:
How to print all the button texts within the url using Selenium through Java
Steps:

Go to the site > https://www.toolsqa.com/automation-practice-switch-windows/

Get a list of buttons from that page

Print the name of the buttons that are displayed on the page.

Code trial:

```<code>package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }}}}
</code>```

答:
If you want to print the list of button names that are displayed on the page.

Ans.Remove if condition block and change the print statement. Refer below Code:

```<code>List <WebElement> buttons = driver.findElements(By.tagName("button"));

    for ( int i=0; i<buttons.size();i++)
    {
        WebElement button = buttons.get(i);

        System.out.println(button.getText());//It prints all the buttons name displayed on the page

    }
</code>```

If you want to print the list of button names which are enabled on the page.

A. Keep the if condition block, just change the print statement. Refer below code:

```<code>List <WebElement> buttons = driver.findElements(By.tagName("button"));

        for ( int i=0; i<buttons.size();i++)
        {
            WebElement button = buttons.get(i);

            //System.out.println(button.getText());  //It prints all the buttons name displayed on the page

     if(button.isEnabled())
            {
                System.out.println(button.getText()); //It prints all the buttons name which are enabled on the page

            }
        }
</code>```

Body:
Steps:

Go to the site > https://www.toolsqa.com/automation-practice-switch-windows/

Get a list of buttons from that page

Print the name of the buttons that are displayed on the page.

Code trial:

package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }}}}

Body:
If you want to print the list of button names that are displayed on the page.

Ans.Remove if condition block and change the print statement. Refer below Code:

List <WebElement> buttons = driver.findElements(By.tagName("button"));

    for ( int i=0; i<buttons.size();i++)
    {
        WebElement button = buttons.get(i);

        System.out.println(button.getText());//It prints all the buttons name displayed on the page

    }

If you want to print the list of button names which are enabled on the page.

A. Keep the if condition block, just change the print statement. Refer below code:

List <WebElement> buttons = driver.findElements(By.tagName("button"));

        for ( int i=0; i<buttons.size();i++)
        {
            WebElement button = buttons.get(i);

            //System.out.println(button.getText());  //It prints all the buttons name displayed on the page

     if(button.isEnabled())
            {
                System.out.println(button.getText()); //It prints all the buttons name which are enabled on the page

            }
        }


问:
One to many relationship using SQFlite (Flutter)
I was hoping someone could write or show me an example of a "One to Many" relationship in Flutter using SQFlite.

Any help would be greatly appreciated, thanks!

答:
I don't see why you should use plugins if the concept is not clear.

Each POJO can be an abstract object, for this, when you create your models, making a practical example:
User -> Stationery stores.
In this case we assume that a user can have more stationery but it cannot be the other way around.
In your user, you can enter a list of stationery stores.

When you go to make a query, like a simple SELECT, you'll already find the bookstores in the User table.
This is a simple example ...


问:
Merging Multiple Worksheets To Single Worksheet In Different Workbook
I want to copy all the rows and columns in multiple worksheets in a one workbook to a single worksheet in a different workbook. In addition, I just want to copy the header once, even though it is in all of the worksheets I'll copy.

I can open the workbook containing all of the worksheets I want to copy to my destination worksheet/workbook however, I don't know how to copy the header only once and often get a Paste Special error.

```<code>Sub Raw_Report_Import()

'Define variables'
Dim ws As Worksheet
Dim wsDest As Worksheet

'Set target destination'
Set wsDest = Sheets("Touchdown")

'For loop to copy all data except headers'
For Each ws In ActiveWorkbook.Sheets
    'Ensure worksheet name and destination tab do not have same name'
    If ws.Name <> wsDest.Name Then
        ws.Range("A2", ws.Range("A2").End(xlToRight).End(xlDown)).Copy
        wsDest.Cells(Rows.Count, "A").End(xlUp).Offset(1).PasteSpecial xlPasteValues
    End If
Next ws

End Sub
</code>```

Expected: All of the target worksheets from second workbook are copied and pasted to destination worksheet "Touchdown" in first workbook and the header is copied only once.

Actual: Some values are paste but the formatting is wrong from what they were and it is not lining up correctly.

答:
There are a number of things wrong with your code. Please find below code (not tested). Please note the differences so you can improve.

Note, when setting the destination worksheet, I would include the workbook object (if in a different workbook). This will prevent errors from occurring. Also note that this code should be run in the OLD workbook. Additionally, I assume your headers are in Row 1 in each sheet, as such I have included headerCnt to take this into consideration and only copy the headers once.

```<code>Option Explicit

Sub Raw_Report_Import()

    Dim ws As Worksheet
    Dim wsDest As Worksheet
    Dim lCol As Long, lRow As Long, lRowTarget As Long
    Dim headerCnt As Long

    'i would include the workbook object here
    Set wsDest = Workbooks("NewWorkbook.xlsx").Sheets("Touchdown")

    For Each ws In ThisWorkbook.Worksheets
        'this loops through ALL other sheets that do not have touch down name
        If ws.Name <> wsDest.Name Then
            'need to include counter to not include the header
            'establish the last row & column to copy
            lCol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column
            lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

            'establish the last row in target sheet
            lRowTarget = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).Row + 1

            If headerCnt = 0 Then
                'copy from Row 1
                ws.Range(ws.Cells(1, 1), ws.Cells(lRow, lCol)).Copy
            Else
                'copy from row 2
                ws.Range(ws.Cells(2, 1), ws.Cells(lRow, lCol)).Copy
            End If

            wsDest.Range("A" & lRowTarget).PasteSpecial xlPasteValues

            'clear clipboard
            Application.CutCopyMode = False
            'header cnt
            headerCnt = 1
        End If
   Next ws

End Sub
</code>```

Body:
I want to copy all the rows and columns in multiple worksheets in a one workbook to a single worksheet in a different workbook. In addition, I just want to copy the header once, even though it is in all of the worksheets I'll copy.

I can open the workbook containing all of the worksheets I want to copy to my destination worksheet/workbook however, I don't know how to copy the header only once and often get a Paste Special error.

Sub Raw_Report_Import()

'Define variables'
Dim ws As Worksheet
Dim wsDest As Worksheet

'Set target destination'
Set wsDest = Sheets("Touchdown")

'For loop to copy all data except headers'
For Each ws In ActiveWorkbook.Sheets
    'Ensure worksheet name and destination tab do not have same name'
    If ws.Name <> wsDest.Name Then
        ws.Range("A2", ws.Range("A2").End(xlToRight).End(xlDown)).Copy
        wsDest.Cells(Rows.Count, "A").End(xlUp).Offset(1).PasteSpecial xlPasteValues
    End If
Next ws

End Sub

Expected: All of the target worksheets from second workbook are copied and pasted to destination worksheet "Touchdown" in first workbook and the header is copied only once.

Actual: Some values are paste but the formatting is wrong from what they were and it is not lining up correctly.

Body:
There are a number of things wrong with your code. Please find below code (not tested). Please note the differences so you can improve.

Note, when setting the destination worksheet, I would include the workbook object (if in a different workbook). This will prevent errors from occurring. Also note that this code should be run in the OLD workbook. Additionally, I assume your headers are in Row 1 in each sheet, as such I have included headerCnt to take this into consideration and only copy the headers once.

Option Explicit

Sub Raw_Report_Import()

    Dim ws As Worksheet
    Dim wsDest As Worksheet
    Dim lCol As Long, lRow As Long, lRowTarget As Long
    Dim headerCnt As Long

    'i would include the workbook object here
    Set wsDest = Workbooks("NewWorkbook.xlsx").Sheets("Touchdown")

    For Each ws In ThisWorkbook.Worksheets
        'this loops through ALL other sheets that do not have touch down name
        If ws.Name <> wsDest.Name Then
            'need to include counter to not include the header
            'establish the last row & column to copy
            lCol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column
            lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

            'establish the last row in target sheet
            lRowTarget = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).Row + 1

            If headerCnt = 0 Then
                'copy from Row 1
                ws.Range(ws.Cells(1, 1), ws.Cells(lRow, lCol)).Copy
            Else
                'copy from row 2
                ws.Range(ws.Cells(2, 1), ws.Cells(lRow, lCol)).Copy
            End If

            wsDest.Range("A" & lRowTarget).PasteSpecial xlPasteValues

            'clear clipboard
            Application.CutCopyMode = False
            'header cnt
            headerCnt = 1
        End If
   Next ws

End Sub


问:
Xcode autocomplete: <<error type>> while project compiles

Suddenly, Xcode Autocomplete stopped working completely and the only thing I see is <<error type>> autocomplete suggestions.

The project compiles and runs on the simulator without any issues.

I tried cleaning the project, manually deleting all the derived data, restarting the computer and making a clean build with no success.

How to fix this issue?

答:
The issue in my case was due to the fact that some files were added to both, the app and the test target at the same time.

Making all files to belong only to either an app or a test target solved the problem.


问:
Ember : debounce called multiple times on scroll event listener
I added a debounce method inside a scroll event listener. Something like this.

```<code>$group.on("scroll.topFix",() => {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called);
   },1000);
});
</code>```

When I do the scroll on $group the debounce is also called the same number of times the scroll event called. I don't know where is the loophole in this thing.

For example, if 5 times the scroll event printed then debounce called is also called 5 times.

This is the link for ember debounce documentation.

答:
```<code><script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.0.min.js"></script>
$(window).scroll(function() {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called');
   },1000);
})
</code>```

Body:
I added a debounce method inside a scroll event listener. Something like this.

$group.on("scroll.topFix",() => {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called);
   },1000);
});

When I do the scroll on $group the debounce is also called the same number of times the scroll event called. I don't know where is the loophole in this thing.

For example, if 5 times the scroll event printed then debounce called is also called 5 times.

This is the link for ember debounce documentation.