问:
getting output from a file using python
i have a file which consists of data, am trying to get particular output from the file. When i am using the "return" [using return for segregating the output further ] statement in loop it is printing only first line of the output.

I have defined all the variables correctly:

```<code>def show_command(filename, startline, endline):
      with open(filename) as input_data:
            for line in input_data:
                  if line.strip() == startline:
                       break
            for line in input_data:
                  if line.strip() == endline:
                       break
                  output = line
                  return output
  show_command(filename, startline, endline)
</code>```

#

it is printing only first line of the total output.

Current Boot Variables:

### Actual output is

Current Boot Variables:

sup-1
NXOS variable = bootflash:/nxos.7.0.3.I4.6.bin
No module boot variable set

Boot Variables on next reload:

sup-1
NXOS variable = bootflash:/nxos.7.0.3.I4.6.bin
No module boot variable set

#

答:
Well, you're returning only that captured line, you need to collect all the lines instead before returning them, for example:

```<code>def show_command(filename, startline, endline):
    with open(filename, "r") as input_data:
        output = None  # hold our contents
        for line in input_data:
            if line.strip() == startline:
                output = ""  # start collecting lines
            elif line.strip() == endline:  # end of our area of interest
                break  # end the loop
            elif output is not None:  # if we started collecting lines...
                output += line  # collect the current line
        return output  # return the collected lines
</code>```

Or if you want to do it with your approach:

```<code>def show_command(filename, startline, endline):
    with open(filename, "r") as input_data:
        for line in input_data:
            if line.strip() == startline:
                break
        output = ""
        for line in input_data:
            if line.strip() == endline:
                break
            output += line
        return output
</code>```

Title: getting output from a file using python

Body:
i have a file which consists of data, am trying to get particular output from the file. When i am using the "return" [using return for segregating the output further ] statement in loop it is printing only first line of the output.

I have defined all the variables correctly:

def show_command(filename, startline, endline):
      with open(filename) as input_data:
            for line in input_data:
                  if line.strip() == startline:
                       break
            for line in input_data:
                  if line.strip() == endline:
                       break
                  output = line
                  return output
  show_command(filename, startline, endline)

#

it is printing only first line of the total output.

Current Boot Variables:

### Actual output is

Current Boot Variables:

sup-1
NXOS variable = bootflash:/nxos.7.0.3.I4.6.bin
No module boot variable set

Boot Variables on next reload:

sup-1
NXOS variable = bootflash:/nxos.7.0.3.I4.6.bin
No module boot variable set

#

Body:
Well, you're returning only that captured line, you need to collect all the lines instead before returning them, for example:

def show_command(filename, startline, endline):
    with open(filename, "r") as input_data:
        output = None  # hold our contents
        for line in input_data:
            if line.strip() == startline:
                output = ""  # start collecting lines
            elif line.strip() == endline:  # end of our area of interest
                break  # end the loop
            elif output is not None:  # if we started collecting lines...
                output += line  # collect the current line
        return output  # return the collected lines

Or if you want to do it with your approach:

def show_command(filename, startline, endline):
    with open(filename, "r") as input_data:
        for line in input_data:
            if line.strip() == startline:
                break
        output = ""
        for line in input_data:
            if line.strip() == endline:
                break
            output += line
        return output


来源: stackexchange

问:
fopen does not return
I used 'fopen' in a C program to open a file in readonly mode (r). But in my case I observed that fopen call does not return. It does not return NULL or valid pointer - execution gets blocked at fopen call. The patch of file is absolutely correct (I have already verified that) and there is no permission related issues. Can anybody please tell what could be the reason for this kind if behavior. Any kind of help is really appreciable. Is there anything related to gcc or glibc?

EDIT

Here is the sample code

```<code>printf("%s %d\n",__FUNCTION__,__LINE__);
if ((fp = fopen(argv[1], "r")) == NULL) {
   printf("%s %d\n",__FUNCTION__,__LINE__);
   return;
}
printf("%s %d\n",__FUNCTION__,__LINE__);
</code>```

When I run this code, I only get the first print (before calling fopen) and after that program just halts. So fopen does not complete it's operation. The file is a simple configuration file with '.conf' extension and this file can be opened by all other means like vi, cat etc. There should not be any NFS related issue. Filesystem is ext3.

Thanks in advance,
Souvik

答:
Is it possible that you've redefined a symbol in the reserved namespace: either something beginning with two underscores, an underscore and a capital letter, or any of the standard C library functions? If so, that results in undefined behavior, and  it's possible that fopen somehow ends up calling part of your code instead of the correct code in the standard library.

This question has a major "missing information" smell to it. I seriously doubt the code snippet in the question has the behavior OP has described when it appears by itself in main, and I wonder if OP hasn't done some bogus stuff he's not telling us about...

ContentLicense: CC BY-SA 2.5

Title: fopen does not return

Body:
I used 'fopen' in a C program to open a file in readonly mode (r). But in my case I observed that fopen call does not return. It does not return NULL or valid pointer - execution gets blocked at fopen call. The patch of file is absolutely correct (I have already verified that) and there is no permission related issues. Can anybody please tell what could be the reason for this kind if behavior. Any kind of help is really appreciable. Is there anything related to gcc or glibc?

EDIT

Here is the sample code

printf("%s %d\n",__FUNCTION__,__LINE__);
if ((fp = fopen(argv[1], "r")) == NULL) {
   printf("%s %d\n",__FUNCTION__,__LINE__);
   return;
}
printf("%s %d\n",__FUNCTION__,__LINE__);

When I run this code, I only get the first print (before calling fopen) and after that program just halts. So fopen does not complete it's operation. The file is a simple configuration file with '.conf' extension and this file can be opened by all other means like vi, cat etc. There should not be any NFS related issue. Filesystem is ext3.

Thanks in advance,
Souvik


问:
flutter make raised button change after future return value
I have a raised button that kicks off my fingerprint authentication, when the Future returns I want to be able to change the Raised Button to new text and new onPressed method to complete the required authentication. I have given the Raised Button a key but can not find how to act upon that button to change it.  Is it possible?  Anyone have examples of it?

I tried to create new Raised Button with same key based on if the user is authenticated, but it did not change anything.

Any help would be great.

答:
I would recommend reviewing the Flutter Interactivity Tutorial.

Once the Future completes you can call setState to tell Flutter to rebuild your StatefulWidget. And in your build() method, you can use the authenticated status of the user to construct a different RaisedButton.

Here's some example code that does this:

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Local Auth Demo',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _authenticated = false;

  Future<Null> _authenticate() async {
    final LocalAuthentication auth = new LocalAuthentication();
    bool authenticated = false;
    try {
      authenticated = await auth.authenticateWithBiometrics(
        localizedReason: 'Scan your fingerprint to authenticate',
        useErrorDialogs: true);
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;
    setState(() {
      _authenticated = authenticated;
    });
  }

  Widget _buildAuthButton() {
    assert(!_authenticated);
    return new RaisedButton(
      child: new Text('Authenticate'),
      onPressed: _authenticate,
    );
  }

  Widget _buildContinueButton() {
    assert(_authenticated);
    return new RaisedButton(
      child: new Text('Continue'),
      onPressed: () {
        // Do something now that the user is authenticated
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Interactivity Tutoral'),
      ),
      body: new Center(
        child: _authenticated ? _buildContinueButton() : _buildAuthButton(),
      ),
    );
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would recommend reviewing the Flutter Interactivity Tutorial.

Once the Future completes you can call setState to tell Flutter to rebuild your StatefulWidget. And in your build() method, you can use the authenticated status of the user to construct a different RaisedButton.

Here's some example code that does this:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Local Auth Demo',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _authenticated = false;

  Future<Null> _authenticate() async {
    final LocalAuthentication auth = new LocalAuthentication();
    bool authenticated = false;
    try {
      authenticated = await auth.authenticateWithBiometrics(
        localizedReason: 'Scan your fingerprint to authenticate',
        useErrorDialogs: true);
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;
    setState(() {
      _authenticated = authenticated;
    });
  }

  Widget _buildAuthButton() {
    assert(!_authenticated);
    return new RaisedButton(
      child: new Text('Authenticate'),
      onPressed: _authenticate,
    );
  }

  Widget _buildContinueButton() {
    assert(_authenticated);
    return new RaisedButton(
      child: new Text('Continue'),
      onPressed: () {
        // Do something now that the user is authenticated
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Interactivity Tutoral'),
      ),
      body: new Center(
        child: _authenticated ? _buildContinueButton() : _buildAuthButton(),
      ),
    );
  }
}


问:
404 error when I click a link while I'm under a tag page
first of all sorry for my English.

And my problem is: If I'm on a "tag" page and click a link which refers to another page in my site I got 404 error. Links are working when I'm in category page or main page.

What should I do?

答:
In addition, I can explain the situation like this;

wordpress gives an extra label to the link at the footer which is "/tag", how can I disable this I don't know...

I'm telling again, it's only a problem when I click that link while I'm under the "/tag"


问:
How to check if the dictionary has only one key with value "1"
I have a dictionary with 2 keys. Only one key can have value 1. If both keys have value 1, it should give the error message.

Here is the working code which I tried, but want to know if there is any way to optimize the same?

```<code>>>> trmode_data = {'continuous': 1, 'fixed': 1}

>>> new = []
>>> for k, v in trmode_data.items():
...  if v == 1:
...   new.append(k)

>>> if len(new) > 1:
...  print "unexpected"
...
unexpected
</code>```

Whichever key has value 1, that key is to be used further. So basically above code is needed to verify that the dictionary has expected values for the keys or not.

答:
```<code>if trmode_data.values().count(1) == 2:
    print "unexpected"
</code>```

Body:
I have a dictionary with 2 keys. Only one key can have value 1. If both keys have value 1, it should give the error message.

Here is the working code which I tried, but want to know if there is any way to optimize the same?

>>> trmode_data = {'continuous': 1, 'fixed': 1}

>>> new = []
>>> for k, v in trmode_data.items():
...  if v == 1:
...   new.append(k)

>>> if len(new) > 1:
...  print "unexpected"
...
unexpected

Whichever key has value 1, that key is to be used further. So basically above code is needed to verify that the dictionary has expected values for the keys or not.


问:
Arm64 Linux Page Table Walk
Currently I'm developing some research-related programs and I need to find the pte of some specific addresses. My development environment is Juno r1 board (CPUs are A53 and A57 ) and it's running arm64 Linux kernel.

I use some typical page table walk codes like this:

```<code>int find_physical_pte(void *addr)
{
    pgd_t *pgd;
    pud_t *pud;
    pmd_t *pmd;
    pte_t *ptep;
    unsigned long long address;

    address = (unsigned long long)addr;

    pgd = pgd_offset(current->mm, address);
    printk(KERN_INFO "\npgd is: %p\n", (void *)pgd);
    printk(KERN_INFO "pgd value: %llx\n", *pgd);
    if (pgd_none(*pgd) || pgd_bad(*pgd))
        return -1;

    pud = pud_offset(pgd, address);
    printk(KERN_INFO "\npud is: %p\n", (void *)pud);
    printk(KERN_INFO "pud value: %llx\n", (*pud).pgd);
    if (pud_none(*pud) || pud_bad(*pud))
        return -2;

    pmd = pmd_offset(pud, address);
    printk(KERN_INFO "\npmd is: %p\n", (void *)pmd);
    printk(KERN_INFO "pmd value: %llx\n",*pmd);
    if (pmd_none(*pmd) || pmd_bad(*pmd))
        return -3;

    ptep = pte_offset_kernel(pmd, address);
    printk(KERN_INFO "\npte is: %p\n", (void *)ptep);
    printk(KERN_INFO "pte value: %llx\n",*ptep);
    if (!ptep)
        return -4;

    return 1;
}
</code>```

However, when the program checks the pte for the address(0xffffffc0008b2000), it always returns an empty pmd.

My guess is that I got the wrong pgd in the first step. I saw Tims Notes said that using current->mm only could get the pgd of TTBR0 (user space pgd) while the address I checked is a kernel space address so I should try to get the pgd of TTBR1.

So my question is: If I want to get the pte of a kernel space address, can I use current->mm to get the pgd?

If I can't, is there anything else I could try instead?

Any suggestion is welcome! Thank you.

Simon

答:
I finally solved the problem.

Actually, my code is correct. The only part I missed is a page table entry check.

According to the page table design of ARMv8, ARM uses 4 levels page table for 4kb granule case. Each level (level 0-3 defined in the link) is implemented as pgd, pud, pmd, and ptep in Linux code.

In the ARM architecture, each level can be either block entry or the table entry (see the AArch64 Descriptor Format Section in the link).

If the memory address belongs to a 4kb table entry, then it needs to be traced down till level 3 entry (ptep). However, for the address belongs to a larger chunk, the corresponding table entry may save in the pgd, pud, or pmd level.

By checking the last 2 bits of the entry in each level, you know it's block entry or not and you only keep tracing down for the block entry.

Here is how to improve my code above:

Retrieving the descriptor based on the page table pointer desc = *pgd and then checking the last 2 bits of the descriptor.

If the descriptor is a block entry (0x01) then you need to extract the lower level entry as my code shows above.
If you already get the table entry (0x11) at any level, then you can stop there and translate the VA to PA based on the descriptor desc you just get.

```<code>int find_physical_pte(void *addr)
{
    pgd_t *pgd;
    pud_t *pud;
    pmd_t *pmd;
    pte_t *ptep;
    unsigned long long address;

    address = (unsigned long long)addr;

    pgd = pgd_offset(current->mm, address);
    printk(KERN_INFO "\npgd is: %p\n", (void *)pgd);
    printk(KERN_INFO "pgd value: %llx\n", *pgd);
    if (pgd_none(*pgd) || pgd_bad(*pgd))
        return -1;
    //check if (*pgd) is a table entry. Exit here if you get the table entry.

    pud = pud_offset(pgd, address);
    printk(KERN_INFO "\npud is: %p\n", (void *)pud);
    printk(KERN_INFO "pud value: %llx\n", (*pud).pgd);
    if (pud_none(*pud) || pud_bad(*pud))
        return -2;
    //check if (*pud) is a table entry. Exit here if you get the table entry.

    pmd = pmd_offset(pud, address);
    printk(KERN_INFO "\npmd is: %p\n", (void *)pmd);
    printk(KERN_INFO "pmd value: %llx\n",*pmd);
    if (pmd_none(*pmd) || pmd_bad(*pmd))
        return -3;
    //check if (*pmd) is a table entry. Exit here if you get the table entry.

    ptep = pte_offset_kernel(pmd, address);
    printk(KERN_INFO "\npte is: %p\n", (void *)ptep);
    printk(KERN_INFO "pte value: %llx\n",*ptep);
    if (!ptep)
        return -4;

    return 1;
}
</code>```

Title: Arm64 Linux Page Table Walk

Body:
Currently I'm developing some research-related programs and I need to find the pte of some specific addresses. My development environment is Juno r1 board (CPUs are A53 and A57 ) and it's running arm64 Linux kernel.

I use some typical page table walk codes like this:

int find_physical_pte(void *addr)
{
    pgd_t *pgd;
    pud_t *pud;
    pmd_t *pmd;
    pte_t *ptep;
    unsigned long long address;

    address = (unsigned long long)addr;

    pgd = pgd_offset(current->mm, address);
    printk(KERN_INFO "\npgd is: %p\n", (void *)pgd);
    printk(KERN_INFO "pgd value: %llx\n", *pgd);
    if (pgd_none(*pgd) || pgd_bad(*pgd))
        return -1;

    pud = pud_offset(pgd, address);
    printk(KERN_INFO "\npud is: %p\n", (void *)pud);
    printk(KERN_INFO "pud value: %llx\n", (*pud).pgd);
    if (pud_none(*pud) || pud_bad(*pud))
        return -2;

    pmd = pmd_offset(pud, address);
    printk(KERN_INFO "\npmd is: %p\n", (void *)pmd);
    printk(KERN_INFO "pmd value: %llx\n",*pmd);
    if (pmd_none(*pmd) || pmd_bad(*pmd))
        return -3;

    ptep = pte_offset_kernel(pmd, address);
    printk(KERN_INFO "\npte is: %p\n", (void *)ptep);
    printk(KERN_INFO "pte value: %llx\n",*ptep);
    if (!ptep)
        return -4;

    return 1;
}

However, when the program checks the pte for the address(0xffffffc0008b2000), it always returns an empty pmd.

My guess is that I got the wrong pgd in the first step. I saw Tims Notes said that using current->mm only could get the pgd of TTBR0 (user space pgd) while the address I checked is a kernel space address so I should try to get the pgd of TTBR1.

So my question is: If I want to get the pte of a kernel space address, can I use current->mm to get the pgd?

If I can't, is there anything else I could try instead?

Any suggestion is welcome! Thank you.

Simon

Body:
I finally solved the problem.

Actually, my code is correct. The only part I missed is a page table entry check.

According to the page table design of ARMv8, ARM uses 4 levels page table for 4kb granule case. Each level (level 0-3 defined in the link) is implemented as pgd, pud, pmd, and ptep in Linux code.

In the ARM architecture, each level can be either block entry or the table entry (see the AArch64 Descriptor Format Section in the link).

If the memory address belongs to a 4kb table entry, then it needs to be traced down till level 3 entry (ptep). However, for the address belongs to a larger chunk, the corresponding table entry may save in the pgd, pud, or pmd level.

By checking the last 2 bits of the entry in each level, you know it's block entry or not and you only keep tracing down for the block entry.

Here is how to improve my code above:

Retrieving the descriptor based on the page table pointer desc = *pgd and then checking the last 2 bits of the descriptor.

If the descriptor is a block entry (0x01) then you need to extract the lower level entry as my code shows above.
If you already get the table entry (0x11) at any level, then you can stop there and translate the VA to PA based on the descriptor desc you just get.

int find_physical_pte(void *addr)
{
    pgd_t *pgd;
    pud_t *pud;
    pmd_t *pmd;
    pte_t *ptep;
    unsigned long long address;

    address = (unsigned long long)addr;

    pgd = pgd_offset(current->mm, address);
    printk(KERN_INFO "\npgd is: %p\n", (void *)pgd);
    printk(KERN_INFO "pgd value: %llx\n", *pgd);
    if (pgd_none(*pgd) || pgd_bad(*pgd))
        return -1;
    //check if (*pgd) is a table entry. Exit here if you get the table entry.

    pud = pud_offset(pgd, address);
    printk(KERN_INFO "\npud is: %p\n", (void *)pud);
    printk(KERN_INFO "pud value: %llx\n", (*pud).pgd);
    if (pud_none(*pud) || pud_bad(*pud))
        return -2;
    //check if (*pud) is a table entry. Exit here if you get the table entry.

    pmd = pmd_offset(pud, address);
    printk(KERN_INFO "\npmd is: %p\n", (void *)pmd);
    printk(KERN_INFO "pmd value: %llx\n",*pmd);
    if (pmd_none(*pmd) || pmd_bad(*pmd))
        return -3;
    //check if (*pmd) is a table entry. Exit here if you get the table entry.

    ptep = pte_offset_kernel(pmd, address);
    printk(KERN_INFO "\npte is: %p\n", (void *)ptep);
    printk(KERN_INFO "pte value: %llx\n",*ptep);
    if (!ptep)
        return -4;

    return 1;
}

ContentLicense: CC BY-SA 4.0


问:
Data changing between functions
After looking at what I could find, a few culprits that i've looked at would be the return being unrolled into a simple String, or other data being in the pipe.

My problem is cmdlets run against the data in the 1st function, do not work on the data by the time it reaches the 2nd function.

```<code>function Get-FileInput() {
    $fileData = Import-Csv $filePath -Delimiter "`t"
    if ($fileData | Get-Member | Where-Object {$_.name -eq "DistinguishedName" -or $_.name -eq "dn" -or $_.name -eq "name"})
    {
        Write-Host -ForegroundColor Green "Confirmed.
        Processing"$fileData.Count"objects."
        $invalidFilePath = $false
        $fileData
        }
    $data = Get-FileInput
    Write-Host $data
}

$data = Get-FileInput
Set-MultipleComputersEnabledStatus -data $data
</code>```

Everything works fine up until this point. Before it gets passed into the 2nd function, it can be used with Format-Table and and Get-Member and everything appears perfectly fine. Inside Set-MultipleComputersEnabledStatus however, I can't perform the exact same checks on the $data object that I had done inside Get-FileInput

It is looking for a property named "DistinguishedName" which it finds in the 1st function, but won't recognize in the data by the time it gets to the 2nd function.

```<code>if ($filterType -eq "DistinguishedName" -and $data | Get-Member | Where-Object {$_.Name -eq 'DistinguishedName'})
{
    Write-Host -ForegroundColor Green "Valid filters. Processing list."
}
</code>```

I assume this means that after being passed in as an argument to the 2nd function, PowerShell changed the data for me somehow, but I can't find anything documenting what it did, or how to prevent it/work around it.

答:
You need to use brackets around the embedded command part so that it is executed first and then the result can be evaluated:</p>

```<code>if ($filterType -eq "DistinguishedName" -and ($data | Get-Member | Where-Object {$_.Name -eq 'DistinguishedName'})) { }
</code>```

Title: Data changing between functions

Body:
After looking at what I could find, a few culprits that i've looked at would be the return being unrolled into a simple String, or other data being in the pipe.

My problem is cmdlets run against the data in the 1st function, do not work on the data by the time it reaches the 2nd function.

function Get-FileInput() {
    $fileData = Import-Csv $filePath -Delimiter "`t"
    if ($fileData | Get-Member | Where-Object {$_.name -eq "DistinguishedName" -or $_.name -eq "dn" -or $_.name -eq "name"})
    {
        Write-Host -ForegroundColor Green "Confirmed.
        Processing"$fileData.Count"objects."
        $invalidFilePath = $false
        $fileData
        }
    $data = Get-FileInput
    Write-Host $data
}

$data = Get-FileInput
Set-MultipleComputersEnabledStatus -data $data

Everything works fine up until this point. Before it gets passed into the 2nd function, it can be used with Format-Table and and Get-Member and everything appears perfectly fine. Inside Set-MultipleComputersEnabledStatus however, I can't perform the exact same checks on the $data object that I had done inside Get-FileInput

It is looking for a property named "DistinguishedName" which it finds in the 1st function, but won't recognize in the data by the time it gets to the 2nd function.

if ($filterType -eq "DistinguishedName" -and $data | Get-Member | Where-Object {$_.Name -eq 'DistinguishedName'})
{
    Write-Host -ForegroundColor Green "Valid filters. Processing list."
}

I assume this means that after being passed in as an argument to the 2nd function, PowerShell changed the data for me somehow, but I can't find anything documenting what it did, or how to prevent it/work around it.

Body:
You need to use brackets around the embedded command part so that it is executed first and then the result can be evaluated:

if ($filterType -eq "DistinguishedName" -and ($data | Get-Member | Where-Object {$_.Name -eq 'DistinguishedName'})) { }


问:
Angular this.path is not a function
I'm getting an error "this.path is not a function"

I don't have "this.path" in code, I assume it's referring to my state, but I'm not running into any luck figuring out what the problem is exactly. The error is:

```<code>stateService.ts:530 TypeError: this.path is not a function
    at LocationHtml5Url.url (angular.js:13744)
    at Object.coreservices_1.services.location.setUrl (services.ts:209)
    at UrlRouter.push (urlRouter.ts:376)
    at updateUrl (url.ts:24)
    at TransitionHook.invokeHook (transitionHook.ts:44)
    at TransitionHook.runSynchronousHooks (transitionHook.ts:108)
    at transitionSuccess (transition.ts:507)
    at processQueue (angular.js:16832)
    at angular.js:16876
    at Scope.$digest (angular.js:17971)
</code>```

Which is firing from some buried angular state routing I assume (since I don't use typescript). This happens when changing routes, after a resolve, but before the controller is loaded.

Also, even though this error appears, the next page does appear to load (console.log fires off in the controller).

If it helps, I think this is the last area the code reaches in my section before the error (this is bound within a very large state resolve for a parent routing system)

```<code>currentProfile: function($rootScope, UserProfileService) {
                    return UserProfileService.fetchClientProfile().then(function(profile) {
                        console.log(profile)
                        $rootScope.user = {
                            name: profile.fullName || profile.firstName
                        };

                        return profile;
                    });
                }
</code>```

答:
The problem ended up being in my interceptor. While it looked like it worked fine, this was due to a resolution of a cookie LATE which is because it resolved randomly sometimes before, sometimes after, the next controller loaded (I didn't have this error all the time).

I normally do not have access to this page, unless you have the cookie. So it was going to the page, THEN the cookie would resolve, causing weird issues. It probably should reject with a different error.

Title: Angular this.path is not a function

Body:
I'm getting an error "this.path is not a function"

I don't have "this.path" in code, I assume it's referring to my state, but I'm not running into any luck figuring out what the problem is exactly. The error is:

stateService.ts:530 TypeError: this.path is not a function
    at LocationHtml5Url.url (angular.js:13744)
    at Object.coreservices_1.services.location.setUrl (services.ts:209)
    at UrlRouter.push (urlRouter.ts:376)
    at updateUrl (url.ts:24)
    at TransitionHook.invokeHook (transitionHook.ts:44)
    at TransitionHook.runSynchronousHooks (transitionHook.ts:108)
    at transitionSuccess (transition.ts:507)
    at processQueue (angular.js:16832)
    at angular.js:16876
    at Scope.$digest (angular.js:17971)

Which is firing from some buried angular state routing I assume (since I don't use typescript). This happens when changing routes, after a resolve, but before the controller is loaded.

Also, even though this error appears, the next page does appear to load (console.log fires off in the controller).

If it helps, I think this is the last area the code reaches in my section before the error (this is bound within a very large state resolve for a parent routing system)

currentProfile: function($rootScope, UserProfileService) {
                    return UserProfileService.fetchClientProfile().then(function(profile) {
                        console.log(profile)
                        $rootScope.user = {
                            name: profile.fullName || profile.firstName
                        };

                        return profile;
                    });
                }


问:
How can I mock up an instance of my main Winform form to test some methods?
I am using Moq (which I am very new too as well as TDD period).  And I wanted to Moq up an instance of my main Winforms form so I could test a few methods on there. Is this possible?  Its constructor takes an object of Assembly().

I was trying the following attempts unsuccessful:

```<code>var mockMainForm = new Mock<MainForm>();
mockMainForm.Setup(x => x.Assembler).Returns(new Assembly());
return mockMainForm.Object;
</code>```

But I can't access any properties or methods on this object once it is returned.  Is this possible to do?

But I get errors that ( failed: System.ArgumentException : Expression is not a method invocation: x => x.Assembler
    at Moq.ExpressionExtensions.ToMethodCall(LambdaExpression expression))

答:
I've never used (or, indeed, heard of) Moq, but I am going to guess that mockMainForm.Object is of type Form, and that you can cast to get at it:

```<code>object moqObject = MakeMoqOfMyMainForm();
Form mainForm = (Form)moqObject;
</code>```

(If I am wrong, let me know and I will delete this answer)

Body:
I am using Moq (which I am very new too as well as TDD period).  And I wanted to Moq up an instance of my main Winforms form so I could test a few methods on there. Is this possible?  Its constructor takes an object of Assembly().

I was trying the following attempts unsuccessful:

var mockMainForm = new Mock<MainForm>();
mockMainForm.Setup(x => x.Assembler).Returns(new Assembly());
return mockMainForm.Object;

But I can't access any properties or methods on this object once it is returned.  Is this possible to do?

But I get errors that ( failed: System.ArgumentException : Expression is not a method invocation: x => x.Assembler
    at Moq.ExpressionExtensions.ToMethodCall(LambdaExpression expression))

Body:
I've never used (or, indeed, heard of) Moq, but I am going to guess that mockMainForm.Object is of type Form, and that you can cast to get at it:

object moqObject = MakeMoqOfMyMainForm();
Form mainForm = (Form)moqObject;

(If I am wrong, let me know and I will delete this answer)


问:
Why is font not displaying on my live website?
I'm hosting my portfolio on goDaddy and I've encountered this error:

'GET http://benjaminthomasgibbs.co.uk/JosefinSans-light.ttf 404 (Not Found)'

Or

'GET http://benjaminthomasgibbs.co.uk/JosefinSans-light.ttf main.html:63'

I haven't made any folders except for JavaScript. All my other fonts seem to be working and they're in the same root directory. I'm quite nooby when it comes to file paths - it's something I'm planning to research, so it could be an obvious error that I just can't see.

It's a 'TTF' file and I added the 'format('truetype')'.

Link to my portfolio: http://benjaminthomasgibbs.co.uk/

The font in question is for the main page where it says 'Junior Web Designer'.

Any help would be greatly appreciated.

```<code>@font-face {

font-family: main;
src: url("JosefinSans-light.ttf") format("truetype");

}
</code>```

答:
This is not enough information to solve your problem, but with the amount of information available, your files are not being hosted where you think they are being hosted.

This may be because you did not setup the webserver (nginx/apache) to host the font assets. Or if you are using rails and want rails to serve it, then you need to enable this in your environmental/production file, setting rails to be the one that serves static files. Or whatever it relevant for your situation beyond that.

Body:
I'm hosting my portfolio on goDaddy and I've encountered this error:

'GET http://benjaminthomasgibbs.co.uk/JosefinSans-light.ttf 404 (Not Found)'

Or

'GET http://benjaminthomasgibbs.co.uk/JosefinSans-light.ttf main.html:63'

I haven't made any folders except for JavaScript. All my other fonts seem to be working and they're in the same root directory. I'm quite nooby when it comes to file paths - it's something I'm planning to research, so it could be an obvious error that I just can't see.

It's a 'TTF' file and I added the 'format('truetype')'.

Link to my portfolio: http://benjaminthomasgibbs.co.uk/

The font in question is for the main page where it says 'Junior Web Designer'.

Any help would be greatly appreciated.

@font-face {

font-family: main;
src: url("JosefinSans-light.ttf") format("truetype");

}


问:
Authentication user provider is not defined in laravel
Based on this Can anyone explain Laravel 5.2 Multi Auth with example

i will like to implement custom authentication on my app for the admin and users section but the whole concept is confusing maybe it is new to me in laravel 5.2 (my version) but at this stage i can say if i am getting it right or wrong but this is the error that is displaying.

```<code>InvalidArgumentException in CreatesUserProviders.php line 40:
Authentication user provider [] is not defined.
</code>```

so i have done what @imrealashu answered but still i have issues.

答:
I got that error when I tried to change in auth.php:

```<code>'provider' => 'users'
</code>```

to

```<code>'provider' => 'user'
</code>```

because my database table was user, not users.

That's not necessary. I just had to add to the User Eloquent class:

```<code>protected $table = 'user';
</code>```

Body:
Based on this Can anyone explain Laravel 5.2 Multi Auth with example

i will like to implement custom authentication on my app for the admin and users section but the whole concept is confusing maybe it is new to me in laravel 5.2 (my version) but at this stage i can say if i am getting it right or wrong but this is the error that is displaying.

InvalidArgumentException in CreatesUserProviders.php line 40:
Authentication user provider [] is not defined.

so i have done what @imrealashu answered but still i have issues.

Body:
I got that error when I tried to change in auth.php:

'provider' => 'users'

to

'provider' => 'user'

because my database table was user, not users.

That's not necessary. I just had to add to the User Eloquent class:

protected $table = 'user';


问:
How to trigger ngModelChange with a button in Angular 2
I use *ngFor to populate my table.

```<code><tr *ngFor= "stu in students">
<td>{{stu.name}}</td>
<td><input type="checkbox" ngModel="isChecked"
(ngModelChange)="addID(stu.id)</td>
</tr>
</code>```

Then I have a button outside the table.

```<code><button (click)="selectAllID()">select all</button>
</code>```

Then I have my component as:

studentID=[];
isChecked=false;

addID(id:number){
this.student.push (id);
//I do other thing with id
}

selectAllID (){
 If (this.isChecked)
     this isChecked = false;
  else this isChecked = true
}
```

The problem is:

if I check individual checkbox, the addID() function is executed. But if I click on the select all button, the checkboxes get selected. But the addID() function is not called.

How can I trigger the ngModelChange function when I use the select all button so I get all selected id's

答:
You have only one way binding of the input control with ngModelChange directive. But to update the view you should bind the control to ngModel.

```<code><input type="checkbox" [ngModel]="isChecked"
(ngModelChange)="addID(stu.id)">
</code>```

Body:
I use *ngFor to populate my table.

{{stu.name}}
<input type="checkbox" ngModel="isChecked"
(ngModelChange)="addID(stu.id)

Then I have a button outside the table.

<button (click)="selectAllID()">select all</button>

Then I have my component as:

studentID=[];
isChecked=false;

addID(id:number){
this.student.push (id);
//I do other thing with id
}

selectAllID (){
 If (this.isChecked)
     this isChecked = false;
  else this isChecked = true
}

The problem is:

if I check individual checkbox, the addID() function is executed. But if I click on the select all button, the checkboxes get selected. But the addID() function is not called.

How can I trigger the ngModelChange function when I use the select all button so I get all selected id's

Body:
You have only one way binding of the input control with ngModelChange directive. But to update the view you should bind the control to ngModel.

<input type="checkbox" [ngModel]="isChecked"
(ngModelChange)="addID(stu.id)">


问:
how to emit data only to connected socket(client) in loopback API socket.io
I am using loopback API. server.js (server -> server.js) is as below:

```<code>var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();

app.start = function () {
  return app.listen(function () {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));
  });
};

boot(app, __dirname, function (err) {
  if (err) throw err;

  if (require.main === module) {
    //app.start();
    app.io = require('socket.io')(app.start());

    app.io.on('connection', function (socket) {
      console.log('a user connected');
      socket.on('disconnect', function () {
      console.log('user disconnected');
    });
  })
  }
});
</code>```

I have created one model file mock.js (common -> models -> mock.js) which contains one method which send pie chart data periodically.

```<code>module.exports = function (Mock) {

Mock.getPieChartData = function (cb) {
    var appIO = Mock.app.io
    console.log('Inside Mock->getPieChartData')
    var interval = setInterval(function () {
        appIO.emit("pieData", getPieChartData());
    }, 3000)

    cb(null, getPieChartData())
}

function getPieChartData() {
.......
}
}
</code>```

Problem is, appIO.emit sends data to all connected clients. I just want to send data to only connected client. not all. If I do socket.emit in server.js inside connection function then it works fine. But I want to emit data from method inside model (mock.js -> Mock.getPieChartData). I am not getting current socket instance inside this method.

答:
After some research, found an answer to my question above. In server.js, set a variable for current socket Id and export it:

```<code>app.io.on('connection', function (socket) {
  console.log('socket.io - a user connected');
  module.exports = { currentSocketId: socket.id };
  socket.on('disconnect', function () {
    console.log('socket.io - user disconnected');
  });
})
</code>```

Inside mock.js, use this current socket Id to get current socket object and then emit using that.

```<code>    Mock.getPieChartData = function (cb) {

    var sourceFile = require('../pubsub/pubsub.js');

    var appIO = Mock.app.io
    console.log('Inside Mock->getPieChartData')

    var currentsocket = appIO.sockets.clients().sockets[sourceFile.currentSocketId]

    var interval = setInterval(function () {
        currentsocket.emit("pieChartData", getPieChartData()) // this emit data to connected socket
        //appIO.emit("pieChartData", getPieChartData()) // this emit data to all connected sockets(clients)
    }, 3000)

    cb(null, getPieChartData())
};
</code>```

Body:
I am using loopback API. server.js (server -> server.js) is as below:

var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();

app.start = function () {
  return app.listen(function () {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));
  });
};

boot(app, __dirname, function (err) {
  if (err) throw err;

  if (require.main === module) {
    //app.start();
    app.io = require('socket.io')(app.start());

    app.io.on('connection', function (socket) {
      console.log('a user connected');
      socket.on('disconnect', function () {
      console.log('user disconnected');
    });
  })
  }
});

I have created one model file mock.js (common -> models -> mock.js) which contains one method which send pie chart data periodically.

module.exports = function (Mock) {

Mock.getPieChartData = function (cb) {
    var appIO = Mock.app.io
    console.log('Inside Mock->getPieChartData')
    var interval = setInterval(function () {
        appIO.emit("pieData", getPieChartData());
    }, 3000)

    cb(null, getPieChartData())
}

function getPieChartData() {
.......
}
}

Problem is, appIO.emit sends data to all connected clients. I just want to send data to only connected client. not all. If I do socket.emit in server.js inside connection function then it works fine. But I want to emit data from method inside model (mock.js -> Mock.getPieChartData). I am not getting current socket instance inside this method.

Body:
After some research, found an answer to my question above. In server.js, set a variable for current socket Id and export it:

app.io.on('connection', function (socket) {
  console.log('socket.io - a user connected');
  module.exports = { currentSocketId: socket.id };
  socket.on('disconnect', function () {
    console.log('socket.io - user disconnected');
  });
})

Inside mock.js, use this current socket Id to get current socket object and then emit using that.

    Mock.getPieChartData = function (cb) {

    var sourceFile = require('../pubsub/pubsub.js');

    var appIO = Mock.app.io
    console.log('Inside Mock->getPieChartData')

    var currentsocket = appIO.sockets.clients().sockets[sourceFile.currentSocketId]

    var interval = setInterval(function () {
        currentsocket.emit("pieChartData", getPieChartData()) // this emit data to connected socket
        //appIO.emit("pieChartData", getPieChartData()) // this emit data to all connected sockets(clients)
    }, 3000)

    cb(null, getPieChartData())
};


问:
Pass value from child model to parent model in MVVM
I am coding an MVVM C# WPF software with 2 models. I am using Caliburn.Micro FYI.

The parent Model :

```<code>namespace Expense_Manager.Models
{
   public class Receipt: PropertyChangedBase
   {
      public Receipt()
      {
         Items = new List<Item>();
      }
      public List<Item> Items{ get; set; }
      private double _total;
      public double Total
      {
         get { return _total; }
         set
         {
            _total= value;
            NotifyOfPropertyChange(() => Total);
         }
      }
   }
}
</code>```

The second model:

```<code>namespace Expense_Manager.Models
{
   public class Item: PropertyChangedBase
   {
      public Item()
      { }

      private double _amount;
      public double Amount
      {
         get { return _amount; }
         set
         {
            _amount= value;
            NotifyOfPropertyChange(() => Amount
         }
      }
   }
}
</code>```

I have simplified the models for the purpose of posting this question.

So my question is: How can I have the Total amount in the parent model calculate itself either by:

adding each value of the Item model everytime it is added to the parent's items list

calculating the sum of each item value once the full list of items is entered in the items list (this would mean that if an item is added at a later date, it would not recalculate itself which I am not too happy about so 1 would prefer to do option 1 above)

答:
Use an ObservableCollection instead of List<> because:

It has a CollectionChanged event which you can use to recalculate the amount each time a new item is added / removed.

It implements the INotifyCollectionChanged so you will have no problem to bind it to different controls.

This is how you would use you it in your case:

```<code>public Receipt()
{
    Items = new ObservableCollection<Item>();
    Items.CollectionChanged += Items_CollectionChanged;
}

private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    Total = Items.Sum(x => x.Amount);
}

public ObservableCollection<Item> Items { get; set; }
</code>```

Body:
I am coding an MVVM C# WPF software with 2 models. I am using Caliburn.Micro FYI.

The parent Model :

namespace Expense_Manager.Models
{
   public class Receipt: PropertyChangedBase
   {
      public Receipt()
      {
         Items = new List<Item>();
      }
      public List<Item> Items{ get; set; }
      private double _total;
      public double Total
      {
         get { return _total; }
         set
         {
            _total= value;
            NotifyOfPropertyChange(() => Total);
         }
      }
   }
}

The second model:

namespace Expense_Manager.Models
{
   public class Item: PropertyChangedBase
   {
      public Item()
      { }

      private double _amount;
      public double Amount
      {
         get { return _amount; }
         set
         {
            _amount= value;
            NotifyOfPropertyChange(() => Amount
         }
      }
   }
}

I have simplified the models for the purpose of posting this question.

So my question is: How can I have the Total amount in the parent model calculate itself either by:

adding each value of the Item model everytime it is added to the parent's items list

calculating the sum of each item value once the full list of items is entered in the items list (this would mean that if an item is added at a later date, it would not recalculate itself which I am not too happy about so 1 would prefer to do option 1 above)

Body:
Use an ObservableCollection instead of List<> because:

It has a CollectionChanged event which you can use to recalculate the amount each time a new item is added / removed.

It implements the INotifyCollectionChanged so you will have no problem to bind it to different controls.

This is how you would use you it in your case:

public Receipt()
{
    Items = new ObservableCollection<Item>();
    Items.CollectionChanged += Items_CollectionChanged;
}

private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    Total = Items.Sum(x => x.Amount);
}

public ObservableCollection<Item> Items { get; set; }


问:
Changing a node's site in ALV tree
I have an ALV tree and basically what I need to do is to slide (drag) a specific node to the top or bottom or a specific location in the ALV tree.

How could this be accomplished?

For example, here I would like to slide the IF node in place before the AFFECTATIONS node:

Expected node's arrangement:

答:
TL;DR: cl_gui_alv_tree cannot do it like you want it to do it.

Due to the specifics of drag-n-drop implementation in ALV Control Framework, the node in a tree can be either draggable (source) or droppable (target), not both. So dragging a node to another node's place on the same level of hierarchy is not possible, hence it is also not possible to (inter)change nodes with its siblings in runtime.

However, I wanna propose you a helpful piece of code, which shows how one can achieve smth close to the question by dragging the node onto the parent level of hierarchy.

Steps for implementing DND functionality in SAP ALV Framework:

Create event class where handlers of ondrag and ondrop events are implemented.

Create DND storage object lcl_dragdropobj, an empty class through the which you pass grid objects (leaves, nodes) in memory.

Create behavior definition for both source and target objects.

With the help of the above behavior object, assign layout to each node/leaf via is_node_layout parameter. That layout would define node behavior: either it's draggable or droppable.

Here is the sample code, built on spfli/sflight database:

```<code>REPORT  zyyz.

DATA: g_alv_tree         TYPE REF TO cl_gui_alv_tree,
      g_custom_container TYPE REF TO cl_gui_custom_container,
      g_drag_behaviour   TYPE REF TO cl_dragdrop,
      g_drop_behaviour   TYPE REF TO cl_dragdrop.
DATA: gt_sflight      TYPE TABLE OF sflight INITIAL SIZE 0,      "Output-Table
      gt_fieldcatalog TYPE lvc_t_fcat,
      g_top_key       TYPE lvc_nkey,
      ok_code         LIKE sy-ucomm,
      save_ok         LIKE sy-ucomm,           "OK-Code
      g_max           TYPE i VALUE 255.

CLASS lcl_dragdropobj DEFINITION.
  PUBLIC SECTION.
    DATA: cp_sflight_root     TYPE sflight,
          cp_sflights         TYPE TABLE OF sflight,
          cp_node_text_root   TYPE lvc_value,
          cp_node_texts       TYPE salv_t_value,
          lt_selected_carrids TYPE lvc_t_nkey,
          lt_selected_leafs   TYPE lvc_t_nkey.
ENDCLASS.

CLASS lcl_event_receiver DEFINITION.
  PUBLIC SECTION.                .
    METHODS:
      on_drag
      FOR EVENT on_drag
                    OF cl_gui_alv_tree
        IMPORTING sender node_key drag_drop_object,
      on_drop
      FOR EVENT on_drop
                    OF cl_gui_alv_tree
        IMPORTING drag_drop_object.
ENDCLASS.
*---------------------------------------------------------------------*
*       CLASS lcl_toolbar_event_receiver IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_event_receiver IMPLEMENTATION.

  METHOD on_drag.
    DATA: dataobj           TYPE REF TO lcl_dragdropobj,
          l_sflight         TYPE sflight,
          l_node_text       TYPE lvc_value.
* create and fill dataobject for event ON_DROP.
    CREATE OBJECT dataobj.

* Get dragged month
    CALL METHOD sender->get_outtab_line
      EXPORTING
        i_node_key    = node_key
      IMPORTING
        e_outtab_line = dataobj->cp_sflight_root
        e_node_text   = dataobj->cp_node_text_root.

    CALL METHOD g_alv_tree->get_children
      EXPORTING
        i_node_key  = node_key
      IMPORTING
        et_children = dataobj->lt_selected_carrids.

    LOOP AT dataobj->lt_selected_carrids ASSIGNING FIELD-SYMBOL(<carrid>).
      CLEAR: l_sflight, l_node_text.
      CALL METHOD sender->get_outtab_line
        EXPORTING
          i_node_key    = <carrid>
        IMPORTING
          e_outtab_line = l_sflight
          e_node_text   = l_node_text.
      APPEND l_node_text TO dataobj->cp_node_texts.

      CALL METHOD g_alv_tree->get_children
        EXPORTING
          i_node_key  = <carrid>
        IMPORTING
          et_children = dataobj->lt_selected_leafs.

      LOOP AT dataobj->lt_selected_leafs ASSIGNING FIELD-SYMBOL(<node>).
        CLEAR: l_sflight, l_node_text.
        CALL METHOD sender->get_outtab_line
          EXPORTING
            i_node_key    = <node>
          IMPORTING
            e_outtab_line = l_sflight
            e_node_text   = l_node_text.
        APPEND l_sflight TO dataobj->cp_sflights.
      ENDLOOP.

    ENDLOOP.

    drag_drop_object->object = dataobj.

  ENDMETHOD.

  METHOD on_drop.
    DATA: dataobj           TYPE REF TO lcl_dragdropobj,
          l_root_key        TYPE lvc_nkey,
          l_carrid_key      TYPE lvc_nkey,
          l_new_key         TYPE lvc_nkey,
          lt_sflights       TYPE TABLE OF sflight.

    CATCH SYSTEM-EXCEPTIONS move_cast_error = 1.
      dataobj ?= drag_drop_object->object.

      PERFORM add_month USING dataobj->cp_node_text_root
                                                    g_top_key
                                                    cl_gui_column_tree=>relat_first_child
                                  CHANGING l_root_key.
*
      LOOP AT dataobj->lt_selected_carrids ASSIGNING FIELD-SYMBOL(<node>).
        READ TABLE dataobj->cp_node_texts ASSIGNING FIELD-SYMBOL(<text>) INDEX sy-tabix.
        DATA(sflight) = VALUE sflight( carrid = <text> ).
        PERFORM add_carrid_line USING sflight
                                                          l_root_key
                                                          cl_gui_column_tree=>relat_last_child
                              CHANGING l_carrid_key.
        CLEAR lt_sflights.
        INSERT LINES OF dataobj->cp_sflights INTO TABLE lt_sflights.
        DELETE lt_sflights WHERE carrid NE <text>.
        LOOP AT lt_sflights ASSIGNING FIELD-SYMBOL(<flight>).
          PERFORM add_complete_line USING <flight>
                                                                   l_carrid_key
                                                CHANGING l_new_key.
        ENDLOOP.
      ENDLOOP.
      PERFORM delete_node.
    ENDCATCH.
    IF sy-subrc <> 0.
      CALL METHOD drag_drop_object->abort.
    ENDIF.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.

END-OF-SELECTION.
  CALL SCREEN 100.
*&---------------------------------------------------------------------*
*&      Module  PBO  OUTPUT
*&---------------------------------------------------------------------*
MODULE pbo OUTPUT.
  SET PF-STATUS 'MAIN100'.
  SET TITLEBAR 'MAINTITLE'.
  IF g_alv_tree IS INITIAL.
    PERFORM init_tree.
    CALL METHOD cl_gui_cfw=>flush
      EXCEPTIONS
        cntl_system_error = 1
        cntl_error        = 2.
  ENDIF.
ENDMODULE.                             " PBO  OUTPUT
*&---------------------------------------------------------------------*
*&      Module  PAI  INPUT
*&---------------------------------------------------------------------*
*       process after input
*----------------------------------------------------------------------*
MODULE pai INPUT.
  save_ok = ok_code.
  CLEAR ok_code.
  CASE save_ok.
    WHEN 'EXIT' OR 'BACK' OR 'CANC'.
      PERFORM exit_program.
    WHEN OTHERS.
      CALL METHOD cl_gui_cfw=>dispatch.
  ENDCASE.
  CALL METHOD cl_gui_cfw=>flush.
ENDMODULE.                             " PAI  INPUT
*&---------------------------------------------------------------------*
*&      Form  init_tree
*&---------------------------------------------------------------------*
FORM init_tree.
* create container for alv-tree
  DATA: l_tree_container_name(30) TYPE c.
  l_tree_container_name = 'CCONTAINER1'.
  CREATE OBJECT g_custom_container
    EXPORTING
      container_name              = l_tree_container_name.
  IF sy-subrc <> 0.
    MESSAGE x208(00) WITH 'ERROR'(100).
  ENDIF.
* create tree control
  CREATE OBJECT g_alv_tree
    EXPORTING
      parent                      = g_custom_container
      node_selection_mode         = cl_gui_column_tree=>node_sel_mode_single
      item_selection              = ' '
      no_html_header              = 'X'
      no_toolbar                  = ''.
  IF sy-subrc <> 0.
    MESSAGE x208(00) WITH 'ERROR'.                          "#EC NOTEXT
  ENDIF.
  DATA l_hierarchy_header TYPE treev_hhdr.
  l_hierarchy_header-width = 35.
  PERFORM build_fieldcatalog.
  CALL METHOD g_alv_tree->set_table_for_first_display
    EXPORTING
      is_hierarchy_header = l_hierarchy_header
    CHANGING
      it_fieldcatalog     = gt_fieldcatalog
      it_outtab           = gt_sflight.
  PERFORM define_dnd_behaviour.
  PERFORM create_hierarchy.
  PERFORM register_events.
  CALL METHOD g_alv_tree->update_calculations.
  CALL METHOD g_alv_tree->frontend_update.
ENDFORM.                               " init_tree

FORM register_events.
  DATA: lt_events        TYPE cntl_simple_events,
        l_event_receiver TYPE REF TO lcl_event_receiver.
  CALL METHOD g_alv_tree->get_registered_events
    IMPORTING
      events = lt_events.
  CALL METHOD g_alv_tree->set_registered_events
    EXPORTING
      events                    = lt_events.
  IF sy-subrc <> 0.
    MESSAGE x208(00) WITH 'ERROR'.                          "#EC NOTEXT
  ENDIF.
  CREATE OBJECT l_event_receiver.
  SET HANDLER l_event_receiver->on_drop FOR g_alv_tree.
  SET HANDLER l_event_receiver->on_drag FOR g_alv_tree.
ENDFORM.                               " register_events
*&---------------------------------------------------------------------*
*&      Form  exit_program
*&---------------------------------------------------------------------*
*       free object and leave program
*----------------------------------------------------------------------*
FORM exit_program.
  CALL METHOD g_custom_container->free.
  LEAVE PROGRAM.
ENDFORM.                               " exit_program
*--------------------------------------------------------------------
FORM build_fieldcatalog.
  CALL FUNCTION 'LVC_FIELDCATALOG_MERGE'
    EXPORTING
      i_structure_name = 'SFLIGHT'
    CHANGING
      ct_fieldcat      = gt_fieldcatalog.
ENDFORM.                               " build_fieldcatalog
*&---------------------------------------------------------------------*
*&      Form  create_hierarchy
*&---------------------------------------------------------------------*
FORM create_hierarchy.
  DATA: ls_sflight       TYPE sflight,
        lt_sflight       TYPE TABLE OF sflight INITIAL SIZE 0,
        l_yyyymm         TYPE c LENGTH 8,            "year and month of sflight-fldate
        l_yyyymm_last(6) TYPE c,
        l_carrid         LIKE sflight-carrid,
        l_carrid_last    LIKE sflight-carrid.
  DATA: l_month_key   TYPE lvc_nkey,
        l_carrid_key  TYPE lvc_nkey,
        l_last_key    TYPE lvc_nkey,
        l_top_key     TYPE lvc_nkey,
        l_layout_node TYPE lvc_s_layn.
* Select data
  SELECT * FROM sflight INTO TABLE lt_sflight UP TO g_max ROWS.
* sort table according to conceived hierarchy
  SORT lt_sflight BY fldate+0(6) carrid fldate+6(2).

  PERFORM make_drop CHANGING l_layout_node.

  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = ''
      i_relationship   = cl_gui_column_tree=>relat_last_child
      i_node_text      = text-050
      is_node_layout   = l_layout_node
    IMPORTING
      e_new_node_key   = l_top_key.

  g_top_key = l_top_key.

  LOOP AT lt_sflight INTO ls_sflight.
    l_yyyymm = ls_sflight-fldate+0(6).
    l_carrid = ls_sflight-carrid.
    IF l_yyyymm <> l_yyyymm_last.      "on change of l_yyyymm
      l_yyyymm_last = l_yyyymm.
* month nodes
      PERFORM add_month USING l_yyyymm
                                                    l_top_key
                                                    cl_gui_column_tree=>relat_last_child
                             CHANGING l_month_key.
* The month changed, thus, there is no predecessor carrier
      CLEAR l_carrid_last.
    ENDIF.
* Carrier nodes:
    IF l_carrid <> l_carrid_last.      "on change of l_carrid
      l_carrid_last = l_carrid.
      PERFORM add_carrid_line USING    ls_sflight
                                                             l_month_key
                                                             cl_gui_column_tree=>relat_last_child
                              CHANGING l_carrid_key.
    ENDIF.
* Leaf:
    PERFORM add_complete_line USING  ls_sflight
                                     l_carrid_key
                            CHANGING l_last_key.
  ENDLOOP.

  CALL METHOD g_alv_tree->expand_node
    EXPORTING
      i_node_key = l_top_key.
ENDFORM.                               " create_hierarchy
*&---------------------------------------------------------------------*
*&      Form  add_month
*&---------------------------------------------------------------------*
FORM add_month  USING     p_yyyymm TYPE clike
                                             p_relat_key TYPE lvc_nkey
                                             p_relationship TYPE int4
                         CHANGING  p_node_key TYPE lvc_nkey.
  DATA: l_node_text   TYPE lvc_value,
        ls_sflight    TYPE sflight,
        l_month       TYPE c LENGTH 25,
        l_layout_node TYPE lvc_s_layn.
  IF p_yyyymm CO ' 0123456789'.
    p_yyyymm = p_yyyymm && '01'.
    CALL FUNCTION 'CONVERSION_EXIT_LDATE_OUTPUT'
      EXPORTING
        input  = p_yyyymm
      IMPORTING
        output = l_month.
    REPLACE REGEX `(\d\d\.\s)([[:alpha:]]*)(\s\d{4})` IN l_month WITH '$2'.
    l_node_text = p_yyyymm(4) && `/` && l_month.
  ELSE.
    l_node_text = p_yyyymm.
  ENDIF.

  PERFORM make_drag CHANGING l_layout_node.
* add node
  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = p_relat_key
      i_relationship   = p_relationship
      i_node_text      = l_node_text
      is_outtab_line   = ls_sflight
      is_node_layout   = l_layout_node
    IMPORTING
      e_new_node_key   = p_node_key.
ENDFORM.                               " add_month
*-----------------------------------------------------------------------
FORM add_carrid_line USING     ps_sflight TYPE sflight
                                                  p_relat_key TYPE lvc_nkey
                                                  p_relationship TYPE int4
                     CHANGING  p_node_key TYPE lvc_nkey.
  DATA: l_node_text   TYPE lvc_value,
        ls_sflight    TYPE sflight,
        l_layout_node TYPE lvc_s_layn.

  l_node_text =  ps_sflight-carrid.
  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = p_relat_key
      i_relationship   = p_relationship
      i_node_text      = l_node_text
      is_outtab_line   = ls_sflight
      is_node_layout   = l_layout_node
    IMPORTING
      e_new_node_key   = p_node_key.
ENDFORM.                               " add_carrid_line
*&---------------------------------------------------------------------*
*&      Form  add_complete_line
*&---------------------------------------------------------------------*
FORM add_complete_line USING   ps_sflight TYPE sflight
                               p_relat_key TYPE lvc_nkey
                     CHANGING  p_node_key TYPE lvc_nkey.
  DATA: l_node_text   TYPE lvc_value,
        l_layout_node TYPE lvc_s_layn.
  WRITE ps_sflight-fldate TO l_node_text MM/DD/YYYY.
  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = p_relat_key
      i_relationship   = cl_gui_column_tree=>relat_last_child
      is_outtab_line   = ps_sflight
      i_node_text      = l_node_text
      is_node_layout   = l_layout_node
    IMPORTING
      e_new_node_key   = p_node_key.
ENDFORM.                               " add_complete_line

FORM define_dnd_behaviour.
  DATA: effect TYPE i.
  CREATE OBJECT g_drag_behaviour.
  effect = cl_dragdrop=>move.
  CALL METHOD g_drag_behaviour->add
    EXPORTING
      flavor     = 'default'                  "#EC NOTEXT
      dragsrc    = 'X'
      droptarget = ' '
      effect     = effect.
  CREATE OBJECT g_drop_behaviour.
  effect = cl_dragdrop=>move.
  CALL METHOD g_drop_behaviour->add
    EXPORTING
      flavor     = 'default'                  "#EC NOTEXT
      dragsrc    = ' '
      droptarget = 'X'
      effect     = effect.
ENDFORM.                    " DEFINE_DND_BEHAVIOUR

FORM delete_node.
  DATA: lt_selected_nodes TYPE lvc_t_nkey,
        l_selected_node   TYPE lvc_nkey.
  CALL METHOD g_alv_tree->get_selected_nodes
    CHANGING
      ct_selected_nodes = lt_selected_nodes.
  CALL METHOD cl_gui_cfw=>flush.
  READ TABLE lt_selected_nodes INTO l_selected_node INDEX 1.
  IF sy-subrc EQ 0.
    CALL METHOD g_alv_tree->delete_subtree
      EXPORTING
        i_node_key = l_selected_node.
    CALL METHOD g_alv_tree->frontend_update.
  ELSE. "sy-subrc EQ 0
    MESSAGE i000(0k) WITH 'Please select a node.'(900).
  ENDIF.
ENDFORM.

FORM make_drag CHANGING p_layout_node TYPE lvc_s_layn.
  DATA l_handle_line TYPE i.
  CALL METHOD g_drag_behaviour->get_handle
    IMPORTING
      handle = l_handle_line.
  p_layout_node-dragdropid = l_handle_line.
ENDFORM.

FORM make_drop CHANGING p_layout_node TYPE lvc_s_layn.
  DATA l_handle_line TYPE i.
  CALL METHOD g_drop_behaviour->get_handle
    IMPORTING
      handle = l_handle_line.
  p_layout_node-dragdropid = l_handle_line.
ENDFORM.
</code>```

In the above example months are made draggable onto the root Flights node. When they are dragged onto it, the place of the dragged node within hierarchy became first. This is not exactly the behavior you asked, but! Through the set of N draggings you can place any node onto any place within that level of hierarchy.

More useful DND examples can be found via BCALV_TREE_* pattern.

Title: Changing a node's site in ALV tree

Body:
TL;DR: cl_gui_alv_tree cannot do it like you want it to do it.

Due to the specifics of drag-n-drop implementation in ALV Control Framework, the node in a tree can be either draggable (source) or droppable (target), not both. So dragging a node to another node's place on the same level of hierarchy is not possible, hence it is also not possible to (inter)change nodes with its siblings in runtime.

However, I wanna propose you a helpful piece of code, which shows how one can achieve smth close to the question by dragging the node onto the parent level of hierarchy.

Steps for implementing DND functionality in SAP ALV Framework:

Create event class where handlers of ondrag and ondrop events are implemented.

Create DND storage object lcl_dragdropobj, an empty class through the which you pass grid objects (leaves, nodes) in memory.

Create behavior definition for both source and target objects.

With the help of the above behavior object, assign layout to each node/leaf via is_node_layout parameter. That layout would define node behavior: either it's draggable or droppable.

Here is the sample code, built on spfli/sflight database:

REPORT  zyyz.

DATA: g_alv_tree         TYPE REF TO cl_gui_alv_tree,
      g_custom_container TYPE REF TO cl_gui_custom_container,
      g_drag_behaviour   TYPE REF TO cl_dragdrop,
      g_drop_behaviour   TYPE REF TO cl_dragdrop.
DATA: gt_sflight      TYPE TABLE OF sflight INITIAL SIZE 0,      "Output-Table
      gt_fieldcatalog TYPE lvc_t_fcat,
      g_top_key       TYPE lvc_nkey,
      ok_code         LIKE sy-ucomm,
      save_ok         LIKE sy-ucomm,           "OK-Code
      g_max           TYPE i VALUE 255.

CLASS lcl_dragdropobj DEFINITION.
  PUBLIC SECTION.
    DATA: cp_sflight_root     TYPE sflight,
          cp_sflights         TYPE TABLE OF sflight,
          cp_node_text_root   TYPE lvc_value,
          cp_node_texts       TYPE salv_t_value,
          lt_selected_carrids TYPE lvc_t_nkey,
          lt_selected_leafs   TYPE lvc_t_nkey.
ENDCLASS.

CLASS lcl_event_receiver DEFINITION.
  PUBLIC SECTION.                .
    METHODS:
      on_drag
      FOR EVENT on_drag
                    OF cl_gui_alv_tree
        IMPORTING sender node_key drag_drop_object,
      on_drop
      FOR EVENT on_drop
                    OF cl_gui_alv_tree
        IMPORTING drag_drop_object.
ENDCLASS.
*---------------------------------------------------------------------*
*       CLASS lcl_toolbar_event_receiver IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_event_receiver IMPLEMENTATION.

  METHOD on_drag.
    DATA: dataobj           TYPE REF TO lcl_dragdropobj,
          l_sflight         TYPE sflight,
          l_node_text       TYPE lvc_value.
* create and fill dataobject for event ON_DROP.
    CREATE OBJECT dataobj.

* Get dragged month
    CALL METHOD sender->get_outtab_line
      EXPORTING
        i_node_key    = node_key
      IMPORTING
        e_outtab_line = dataobj->cp_sflight_root
        e_node_text   = dataobj->cp_node_text_root.

    CALL METHOD g_alv_tree->get_children
      EXPORTING
        i_node_key  = node_key
      IMPORTING
        et_children = dataobj->lt_selected_carrids.

    LOOP AT dataobj->lt_selected_carrids ASSIGNING FIELD-SYMBOL(<carrid>).
      CLEAR: l_sflight, l_node_text.
      CALL METHOD sender->get_outtab_line
        EXPORTING
          i_node_key    = <carrid>
        IMPORTING
          e_outtab_line = l_sflight
          e_node_text   = l_node_text.
      APPEND l_node_text TO dataobj->cp_node_texts.

      CALL METHOD g_alv_tree->get_children
        EXPORTING
          i_node_key  = <carrid>
        IMPORTING
          et_children = dataobj->lt_selected_leafs.

      LOOP AT dataobj->lt_selected_leafs ASSIGNING FIELD-SYMBOL(<node>).
        CLEAR: l_sflight, l_node_text.
        CALL METHOD sender->get_outtab_line
          EXPORTING
            i_node_key    = <node>
          IMPORTING
            e_outtab_line = l_sflight
            e_node_text   = l_node_text.
        APPEND l_sflight TO dataobj->cp_sflights.
      ENDLOOP.

    ENDLOOP.

    drag_drop_object->object = dataobj.

  ENDMETHOD.

  METHOD on_drop.
    DATA: dataobj           TYPE REF TO lcl_dragdropobj,
          l_root_key        TYPE lvc_nkey,
          l_carrid_key      TYPE lvc_nkey,
          l_new_key         TYPE lvc_nkey,
          lt_sflights       TYPE TABLE OF sflight.

    CATCH SYSTEM-EXCEPTIONS move_cast_error = 1.
      dataobj ?= drag_drop_object->object.

      PERFORM add_month USING dataobj->cp_node_text_root
                                                    g_top_key
                                                    cl_gui_column_tree=>relat_first_child
                                  CHANGING l_root_key.
*
      LOOP AT dataobj->lt_selected_carrids ASSIGNING FIELD-SYMBOL(<node>).
        READ TABLE dataobj->cp_node_texts ASSIGNING FIELD-SYMBOL(<text>) INDEX sy-tabix.
        DATA(sflight) = VALUE sflight( carrid = <text> ).
        PERFORM add_carrid_line USING sflight
                                                          l_root_key
                                                          cl_gui_column_tree=>relat_last_child
                              CHANGING l_carrid_key.
        CLEAR lt_sflights.
        INSERT LINES OF dataobj->cp_sflights INTO TABLE lt_sflights.
        DELETE lt_sflights WHERE carrid NE <text>.
        LOOP AT lt_sflights ASSIGNING FIELD-SYMBOL(<flight>).
          PERFORM add_complete_line USING <flight>
                                                                   l_carrid_key
                                                CHANGING l_new_key.
        ENDLOOP.
      ENDLOOP.
      PERFORM delete_node.
    ENDCATCH.
    IF sy-subrc <> 0.
      CALL METHOD drag_drop_object->abort.
    ENDIF.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.

END-OF-SELECTION.
  CALL SCREEN 100.
*&---------------------------------------------------------------------*
*&      Module  PBO  OUTPUT
*&---------------------------------------------------------------------*
MODULE pbo OUTPUT.
  SET PF-STATUS 'MAIN100'.
  SET TITLEBAR 'MAINTITLE'.
  IF g_alv_tree IS INITIAL.
    PERFORM init_tree.
    CALL METHOD cl_gui_cfw=>flush
      EXCEPTIONS
        cntl_system_error = 1
        cntl_error        = 2.
  ENDIF.
ENDMODULE.                             " PBO  OUTPUT
*&---------------------------------------------------------------------*
*&      Module  PAI  INPUT
*&---------------------------------------------------------------------*
*       process after input
*----------------------------------------------------------------------*
MODULE pai INPUT.
  save_ok = ok_code.
  CLEAR ok_code.
  CASE save_ok.
    WHEN 'EXIT' OR 'BACK' OR 'CANC'.
      PERFORM exit_program.
    WHEN OTHERS.
      CALL METHOD cl_gui_cfw=>dispatch.
  ENDCASE.
  CALL METHOD cl_gui_cfw=>flush.
ENDMODULE.                             " PAI  INPUT
*&---------------------------------------------------------------------*
*&      Form  init_tree
*&---------------------------------------------------------------------*
FORM init_tree.
* create container for alv-tree
  DATA: l_tree_container_name(30) TYPE c.
  l_tree_container_name = 'CCONTAINER1'.
  CREATE OBJECT g_custom_container
    EXPORTING
      container_name              = l_tree_container_name.
  IF sy-subrc <> 0.
    MESSAGE x208(00) WITH 'ERROR'(100).
  ENDIF.
* create tree control
  CREATE OBJECT g_alv_tree
    EXPORTING
      parent                      = g_custom_container
      node_selection_mode         = cl_gui_column_tree=>node_sel_mode_single
      item_selection              = ' '
      no_html_header              = 'X'
      no_toolbar                  = ''.
  IF sy-subrc <> 0.
    MESSAGE x208(00) WITH 'ERROR'.                          "#EC NOTEXT
  ENDIF.
  DATA l_hierarchy_header TYPE treev_hhdr.
  l_hierarchy_header-width = 35.
  PERFORM build_fieldcatalog.
  CALL METHOD g_alv_tree->set_table_for_first_display
    EXPORTING
      is_hierarchy_header = l_hierarchy_header
    CHANGING
      it_fieldcatalog     = gt_fieldcatalog
      it_outtab           = gt_sflight.
  PERFORM define_dnd_behaviour.
  PERFORM create_hierarchy.
  PERFORM register_events.
  CALL METHOD g_alv_tree->update_calculations.
  CALL METHOD g_alv_tree->frontend_update.
ENDFORM.                               " init_tree

FORM register_events.
  DATA: lt_events        TYPE cntl_simple_events,
        l_event_receiver TYPE REF TO lcl_event_receiver.
  CALL METHOD g_alv_tree->get_registered_events
    IMPORTING
      events = lt_events.
  CALL METHOD g_alv_tree->set_registered_events
    EXPORTING
      events                    = lt_events.
  IF sy-subrc <> 0.
    MESSAGE x208(00) WITH 'ERROR'.                          "#EC NOTEXT
  ENDIF.
  CREATE OBJECT l_event_receiver.
  SET HANDLER l_event_receiver->on_drop FOR g_alv_tree.
  SET HANDLER l_event_receiver->on_drag FOR g_alv_tree.
ENDFORM.                               " register_events
*&---------------------------------------------------------------------*
*&      Form  exit_program
*&---------------------------------------------------------------------*
*       free object and leave program
*----------------------------------------------------------------------*
FORM exit_program.
  CALL METHOD g_custom_container->free.
  LEAVE PROGRAM.
ENDFORM.                               " exit_program
*--------------------------------------------------------------------
FORM build_fieldcatalog.
  CALL FUNCTION 'LVC_FIELDCATALOG_MERGE'
    EXPORTING
      i_structure_name = 'SFLIGHT'
    CHANGING
      ct_fieldcat      = gt_fieldcatalog.
ENDFORM.                               " build_fieldcatalog
*&---------------------------------------------------------------------*
*&      Form  create_hierarchy
*&---------------------------------------------------------------------*
FORM create_hierarchy.
  DATA: ls_sflight       TYPE sflight,
        lt_sflight       TYPE TABLE OF sflight INITIAL SIZE 0,
        l_yyyymm         TYPE c LENGTH 8,            "year and month of sflight-fldate
        l_yyyymm_last(6) TYPE c,
        l_carrid         LIKE sflight-carrid,
        l_carrid_last    LIKE sflight-carrid.
  DATA: l_month_key   TYPE lvc_nkey,
        l_carrid_key  TYPE lvc_nkey,
        l_last_key    TYPE lvc_nkey,
        l_top_key     TYPE lvc_nkey,
        l_layout_node TYPE lvc_s_layn.
* Select data
  SELECT * FROM sflight INTO TABLE lt_sflight UP TO g_max ROWS.
* sort table according to conceived hierarchy
  SORT lt_sflight BY fldate+0(6) carrid fldate+6(2).

  PERFORM make_drop CHANGING l_layout_node.

  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = ''
      i_relationship   = cl_gui_column_tree=>relat_last_child
      i_node_text      = text-050
      is_node_layout   = l_layout_node
    IMPORTING
      e_new_node_key   = l_top_key.

  g_top_key = l_top_key.

  LOOP AT lt_sflight INTO ls_sflight.
    l_yyyymm = ls_sflight-fldate+0(6).
    l_carrid = ls_sflight-carrid.
    IF l_yyyymm <> l_yyyymm_last.      "on change of l_yyyymm
      l_yyyymm_last = l_yyyymm.
* month nodes
      PERFORM add_month USING l_yyyymm
                                                    l_top_key
                                                    cl_gui_column_tree=>relat_last_child
                             CHANGING l_month_key.
* The month changed, thus, there is no predecessor carrier
      CLEAR l_carrid_last.
    ENDIF.
* Carrier nodes:
    IF l_carrid <> l_carrid_last.      "on change of l_carrid
      l_carrid_last = l_carrid.
      PERFORM add_carrid_line USING    ls_sflight
                                                             l_month_key
                                                             cl_gui_column_tree=>relat_last_child
                              CHANGING l_carrid_key.
    ENDIF.
* Leaf:
    PERFORM add_complete_line USING  ls_sflight
                                     l_carrid_key
                            CHANGING l_last_key.
  ENDLOOP.

  CALL METHOD g_alv_tree->expand_node
    EXPORTING
      i_node_key = l_top_key.
ENDFORM.                               " create_hierarchy
*&---------------------------------------------------------------------*
*&      Form  add_month
*&---------------------------------------------------------------------*
FORM add_month  USING     p_yyyymm TYPE clike
                                             p_relat_key TYPE lvc_nkey
                                             p_relationship TYPE int4
                         CHANGING  p_node_key TYPE lvc_nkey.
  DATA: l_node_text   TYPE lvc_value,
        ls_sflight    TYPE sflight,
        l_month       TYPE c LENGTH 25,
        l_layout_node TYPE lvc_s_layn.
  IF p_yyyymm CO ' 0123456789'.
    p_yyyymm = p_yyyymm && '01'.
    CALL FUNCTION 'CONVERSION_EXIT_LDATE_OUTPUT'
      EXPORTING
        input  = p_yyyymm
      IMPORTING
        output = l_month.
    REPLACE REGEX `(\d\d\.\s)([[:alpha:]]*)(\s\d{4})` IN l_month WITH '$2'.
    l_node_text = p_yyyymm(4) && `/` && l_month.
  ELSE.
    l_node_text = p_yyyymm.
  ENDIF.

  PERFORM make_drag CHANGING l_layout_node.
* add node
  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = p_relat_key
      i_relationship   = p_relationship
      i_node_text      = l_node_text
      is_outtab_line   = ls_sflight
      is_node_layout   = l_layout_node
    IMPORTING
      e_new_node_key   = p_node_key.
ENDFORM.                               " add_month
*-----------------------------------------------------------------------
FORM add_carrid_line USING     ps_sflight TYPE sflight
                                                  p_relat_key TYPE lvc_nkey
                                                  p_relationship TYPE int4
                     CHANGING  p_node_key TYPE lvc_nkey.
  DATA: l_node_text   TYPE lvc_value,
        ls_sflight    TYPE sflight,
        l_layout_node TYPE lvc_s_layn.

  l_node_text =  ps_sflight-carrid.
  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = p_relat_key
      i_relationship   = p_relationship
      i_node_text      = l_node_text
      is_outtab_line   = ls_sflight
      is_node_layout   = l_layout_node
    IMPORTING
      e_new_node_key   = p_node_key.
ENDFORM.                               " add_carrid_line
*&---------------------------------------------------------------------*
*&      Form  add_complete_line
*&---------------------------------------------------------------------*
FORM add_complete_line USING   ps_sflight TYPE sflight
                               p_relat_key TYPE lvc_nkey
                     CHANGING  p_node_key TYPE lvc_nkey.
  DATA: l_node_text   TYPE lvc_value,
        l_layout_node TYPE lvc_s_layn.
  WRITE ps_sflight-fldate TO l_node_text MM/DD/YYYY.
  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = p_relat_key
      i_relationship   = cl_gui_column_tree=>relat_last_child
      is_outtab_line   = ps_sflight
      i_node_text      = l_node_text
      is_node_layout   = l_layout_node
    IMPORTING
      e_new_node_key   = p_node_key.
ENDFORM.                               " add_complete_line

FORM define_dnd_behaviour.
  DATA: effect TYPE i.
  CREATE OBJECT g_drag_behaviour.
  effect = cl_dragdrop=>move.
  CALL METHOD g_drag_behaviour->add
    EXPORTING
      flavor     = 'default'                  "#EC NOTEXT
      dragsrc    = 'X'
      droptarget = ' '
      effect     = effect.
  CREATE OBJECT g_drop_behaviour.
  effect = cl_dragdrop=>move.
  CALL METHOD g_drop_behaviour->add
    EXPORTING
      flavor     = 'default'                  "#EC NOTEXT
      dragsrc    = ' '
      droptarget = 'X'
      effect     = effect.
ENDFORM.                    " DEFINE_DND_BEHAVIOUR

FORM delete_node.
  DATA: lt_selected_nodes TYPE lvc_t_nkey,
        l_selected_node   TYPE lvc_nkey.
  CALL METHOD g_alv_tree->get_selected_nodes
    CHANGING
      ct_selected_nodes = lt_selected_nodes.
  CALL METHOD cl_gui_cfw=>flush.
  READ TABLE lt_selected_nodes INTO l_selected_node INDEX 1.
  IF sy-subrc EQ 0.
    CALL METHOD g_alv_tree->delete_subtree
      EXPORTING
        i_node_key = l_selected_node.
    CALL METHOD g_alv_tree->frontend_update.
  ELSE. "sy-subrc EQ 0
    MESSAGE i000(0k) WITH 'Please select a node.'(900).
  ENDIF.
ENDFORM.

FORM make_drag CHANGING p_layout_node TYPE lvc_s_layn.
  DATA l_handle_line TYPE i.
  CALL METHOD g_drag_behaviour->get_handle
    IMPORTING
      handle = l_handle_line.
  p_layout_node-dragdropid = l_handle_line.
ENDFORM.

FORM make_drop CHANGING p_layout_node TYPE lvc_s_layn.
  DATA l_handle_line TYPE i.
  CALL METHOD g_drop_behaviour->get_handle
    IMPORTING
      handle = l_handle_line.
  p_layout_node-dragdropid = l_handle_line.
ENDFORM.

In the above example months are made draggable onto the root Flights node. When they are dragged onto it, the place of the dragged node within hierarchy became first. This is not exactly the behavior you asked, but! Through the set of N draggings you can place any node onto any place within that level of hierarchy.

More useful DND examples can be found via BCALV_TREE_* pattern.


问:
Disable Materialize Framework "Responsiveness"
I am attempting to use the materialize framework. I am very much liking the features it provides but I don't really care too much about making everything "responsive" right now. I would like to make things somewhat "static", meaning when I resize the browser, everything stays the same size (and user can scroll around in a smaller window to find what they want). I plan to later work on the full "responsiveness" to support things like mobile, window resizing, etc. Below shows whats currently happening. I downloaded the whole framework so I'm free to alter the .css that comes along with it, but I'm not really a .css expert so not really sure where to begin.

Full Screen

Resized Screen - obviously cannot stay like this forever

Any help is much appreciated.

答:
First to answer your question directly: I assume you are using the Materialize grid? Meaning you have divs with class names like "col l6"? To have non responsive elements you should not use any materialize column class names. It will then just be regular old HTML and CSS that you define. Materialize only applies its CSS to elements that use its classnames.

Now for a recommendation: This will probably break some of the features of Materialize. Or at the very least, it will look gross and you will have to add padding/margins everywhere manually. Then if you want to go back and enable mobile responsiveness, you will have to manually remove all of that. You will also have to use old fashioned CSS rules to determine you element sizing. Every element will need a height and width rule applied to it. It is a lot harder to add mobile responsive classes later. It will save you a lot of time if you just do it now. It's quite easy in Materialize once you get the hang of it.

One of the main reasons that Materialize and Bootstrap and the like are used, is to make mobile responsive websites easy. It really is an essential skill to learn for web development these days.


问:
ios - How to select multiple cells on a single click (Objective-c)
I'm coding an iOS app and was wondering if its possible to select 3 cells at once when the user clicks on a single cell in a uitableview. So 3 would be the one they click and the 2 below. Is this possible and if so how would it be done? Thanks

How I currently check user clicks:

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self tableView:tableView canCollapseSection:indexPath.section])
    {
        if (!indexPath.row)
        {
            // only first row toggles exapand/collapse
            [tableView deselectRowAtIndexPath:indexPath animated:YES];

            NSInteger section = indexPath.section;
            BOOL currentlyExpanded = [expandedSections containsIndex:section];
            NSInteger rows;

            NSMutableArray *tmpArray = [NSMutableArray array];

            if (currentlyExpanded)
            {
                rows = [self tableView:tableView numberOfRowsInSection:section];
                [expandedSections removeIndex:section];

            }
            else
            {

                [expandedSections addIndex:section];
                rows = [self tableView:tableView numberOfRowsInSection:section];
            }

            for (int i=1; i<rows; i++)
            {
                NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
                                                               inSection:section];
                [tmpArray addObject:tmpIndexPath];
            }

            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            if (currentlyExpanded)
            {
                dispatch_async(dispatch_get_main_queue(), ^{

                [tableView deleteRowsAtIndexPaths:tmpArray
                                 withRowAnimation:UITableViewRowAnimationTop];
                });
            }
            else
            {
                  dispatch_async(dispatch_get_main_queue(), ^{
                [tableView insertRowsAtIndexPaths:tmpArray
                                 withRowAnimation:UITableViewRowAnimationTop];
                  });

            }
        }
}
</code>```

I also have

```<code>self.tableView.allowsMultipleSelection = true;
</code>```

in my code, but the problem is that it doesn't allow me to select 3 at a time.

答:
To answer your question about selecting multiple cells on a single click (I'm ignoring for the moment your insertRows / deleteRows stuff)...

Here are a couple examples of selecting multiple rows. You should have no trouble implementing this for your specifics:

Objective-C

```<code>// select ALL rows in Section 0
for (int i = 0; i < [tableView numberOfRowsInSection:0]; i++) {
    NSIndexPath *iPath = [NSIndexPath indexPathForRow:i inSection:0];
    [tableView selectRowAtIndexPath:iPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}

// select ALL VISIBLE rows
for (NSIndexPath *iPath in [tableView indexPathsForVisibleRows]) {
    [tableView selectRowAtIndexPath:iPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}

// select rows 2, 4 and 6
for (NSNumber *n in @[@2, @4, @6]) {
    NSIndexPath *iPath = [NSIndexPath indexPathForRow:[n integerValue] inSection:0];
    [tableView selectRowAtIndexPath:iPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}

// deselect all rows
for (NSIndexPath *iPath in [tableView indexPathsForSelectedRows]) {
    [tableView deselectRowAtIndexPath:iPath animated:NO];
}
</code>```

Swift

```<code>// select ALL rows in Section 0
for i in 0..<tableView.numberOfRows(inSection: 0) {
    let iPath = IndexPath(item: i, section: 0)
    tableView.selectRow(at: iPath, animated: false, scrollPosition: .none)
}

// select ALL VISIBLE rows
for iPath in tableView.indexPathsForVisibleRows! {
    tableView.selectRow(at: iPath, animated: false, scrollPosition: .none)
}

// select rows 2, 4 and 6
for i in [2, 4, 6] {
    let iPath = IndexPath(item: i, section: 0)
    tableView.selectRow(at: iPath, animated: false, scrollPosition: .none)
}

// deselect all rows
for iPath in tableView.indexPathsForSelectedRows! {
    tableView.deselectRow(at: iPath, animated: false)
}
</code>```

Body:
I'm coding an iOS app and was wondering if its possible to select 3 cells at once when the user clicks on a single cell in a uitableview. So 3 would be the one they click and the 2 below. Is this possible and if so how would it be done? Thanks

How I currently check user clicks:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self tableView:tableView canCollapseSection:indexPath.section])
    {
        if (!indexPath.row)
        {
            // only first row toggles exapand/collapse
            [tableView deselectRowAtIndexPath:indexPath animated:YES];

            NSInteger section = indexPath.section;
            BOOL currentlyExpanded = [expandedSections containsIndex:section];
            NSInteger rows;

            NSMutableArray *tmpArray = [NSMutableArray array];

            if (currentlyExpanded)
            {
                rows = [self tableView:tableView numberOfRowsInSection:section];
                [expandedSections removeIndex:section];

            }
            else
            {

                [expandedSections addIndex:section];
                rows = [self tableView:tableView numberOfRowsInSection:section];
            }

            for (int i=1; i<rows; i++)
            {
                NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
                                                               inSection:section];
                [tmpArray addObject:tmpIndexPath];
            }

            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            if (currentlyExpanded)
            {
                dispatch_async(dispatch_get_main_queue(), ^{

                [tableView deleteRowsAtIndexPaths:tmpArray
                                 withRowAnimation:UITableViewRowAnimationTop];
                });
            }
            else
            {
                  dispatch_async(dispatch_get_main_queue(), ^{
                [tableView insertRowsAtIndexPaths:tmpArray
                                 withRowAnimation:UITableViewRowAnimationTop];
                  });

            }
        }
}

I also have

self.tableView.allowsMultipleSelection = true;

in my code, but the problem is that it doesn't allow me to select 3 at a time.

Body:
To answer your question about selecting multiple cells on a single click (I'm ignoring for the moment your insertRows / deleteRows stuff)...

Here are a couple examples of selecting multiple rows. You should have no trouble implementing this for your specifics:

Objective-C

// select ALL rows in Section 0
for (int i = 0; i < [tableView numberOfRowsInSection:0]; i++) {
    NSIndexPath *iPath = [NSIndexPath indexPathForRow:i inSection:0];
    [tableView selectRowAtIndexPath:iPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}

// select ALL VISIBLE rows
for (NSIndexPath *iPath in [tableView indexPathsForVisibleRows]) {
    [tableView selectRowAtIndexPath:iPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}

// select rows 2, 4 and 6
for (NSNumber *n in @[@2, @4, @6]) {
    NSIndexPath *iPath = [NSIndexPath indexPathForRow:[n integerValue] inSection:0];
    [tableView selectRowAtIndexPath:iPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}

// deselect all rows
for (NSIndexPath *iPath in [tableView indexPathsForSelectedRows]) {
    [tableView deselectRowAtIndexPath:iPath animated:NO];
}

Swift

// select ALL rows in Section 0
for i in 0..<tableView.numberOfRows(inSection: 0) {
    let iPath = IndexPath(item: i, section: 0)
    tableView.selectRow(at: iPath, animated: false, scrollPosition: .none)
}

// select ALL VISIBLE rows
for iPath in tableView.indexPathsForVisibleRows! {
    tableView.selectRow(at: iPath, animated: false, scrollPosition: .none)
}

// select rows 2, 4 and 6
for i in [2, 4, 6] {
    let iPath = IndexPath(item: i, section: 0)
    tableView.selectRow(at: iPath, animated: false, scrollPosition: .none)
}

// deselect all rows
for iPath in tableView.indexPathsForSelectedRows! {
    tableView.deselectRow(at: iPath, animated: false)
}


问:
Preprocessor output on Qt Creator
I am compiling C code in Qt Creator and I need to look at the preprocessor output.

I added the -E flag to the make, but I don't see the *.i files:

```<code>mingw32-make.exe -e -w in \qt\qt-build-desktop
</code>```

Please help.

答:
-E is a gcc option, not a make option, so passing it to make won't do anything. Also, using -E works fine for a single file, but will break your build as no proper .o file is generated (it contains the preprocessed source).
What works fine though is adding the following to the .pro file:

```<code>QMAKE_CXXFLAGS += -save-temps
</code>```

Now if you build your project, the preprocessed source of source file foo.cpp is kept as foo.ii.
(tested with make+gcc on OS X, I'd assume it works for mingw, too).

Edit: Just learned that the equivalent flag for MSVC is

```<code>QMAKE_CXXFLAGS += -P
</code>```

Title: Preprocessor output on Qt Creator

Body:
I am compiling C code in Qt Creator and I need to look at the preprocessor output.

I added the -E flag to the make, but I don't see the *.i files:

mingw32-make.exe -e -w in \qt\qt-build-desktop

Please help.

Body:
-E is a gcc option, not a make option, so passing it to make won't do anything. Also, using -E works fine for a single file, but will break your build as no proper .o file is generated (it contains the preprocessed source).
What works fine though is adding the following to the .pro file:

QMAKE_CXXFLAGS += -save-temps

Now if you build your project, the preprocessed source of source file foo.cpp is kept as foo.ii.
(tested with make+gcc on OS X, I'd assume it works for mingw, too).

Edit: Just learned that the equivalent flag for MSVC is

QMAKE_CXXFLAGS += -P


答:
Your font was actually located at http://benjaminthomasgibbs.co.uk/JosefinSans-Light.ttf

Note the uppercase L.

Title: Why is font not displaying on my live website?


问:
Is present National Instruments Measurement Studio compatible with Visual Studio 2017?
I'm using Visual Studio 2017 Pro.
I am using VB.NET to create a GUI windows app to manage an NI USB-6343 DAQ.</p>

答:
NI Measurement Studio 2015 does sadly not support VS2015 (and so also not VS2017), it supports VS 2013, 2012 and 2010. There is a workaround for 2015 see this link, that might also work for VS2017.

Update:

Measurement Studio 2019 Beta

Measurement Studio extends the power of Microsoft Visual Studio with a
set of .NET tools designed for building engineering test and
measurement applications.  Try out the beta to use:

Visual Studio 2015 and 2017 integration

Debug Visualizer

see http://www.ni.com/de-ch/support/software-technology-preview.html

Update 2

NI Measurement Studio 2019 supports VS2015, VS2017 and VS2019, see

https://www.ni.com/en-us/support/downloads/software-products/download.measurement-studio.html

and

https://knowledge.ni.com/KnowledgeArticleDetails?id=kA00Z0000019RD9SAM&l=de-CH


问:
LIFO Handler in Android
I have a bunch of asynchronous tasks I need to be run, but the task with the highest priority is the one that was added last.

Is there a LIFO (last in first out) stack-like Handler in Android that I can use for this?

If not, my alternative implementation is to have each task pull an item to process from a Stack. But this is causing issues with locking as the stack is populated dynamically. Is there a better approach?

答: You can easily implement from scratch a thread which feeds from a LinkedBlockingDeque. Users can put tasks to both sides of the deque.</p>

Title: LIFO Handler in Android