问:
Angular - Get Component name from a URL
I have routes defined this way in app-routing.module.ts:

```<code>const routes: Routes = [
  {
    path: 'abc/:id', component: AbcComponent
  },
  {
    path: 'xyz/:id/tester/:mapId', component: XyzComponent
  },
  { path: '**', redirectTo: '/page-not-found', pathMatch: 'full'}
]
</code>```

I would like to get the component name based on a URL in app.component.ts

Ex: If a user navigated to http://myapp.com/abc/123 I would like to the get the component name, which in this case would be AbcComponent

If a user navigated to http://myapp.com/xyz/123/tester/456 I would like to the get the component name, which in this case would be XyzComponent

How can I get that?

I tried to use ActivatedRoute, but it doesn't seem to work, as I get Cannot read property 'component' of null.

```<code>  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
 this.checkRoute()
}

checkRoute()
{
   console.log(this.activatedRoute.routeConfig.component.name)
}
</code>```

答:
Try this it work for me

```<code>constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
 this.checkRoute()
}

checkRoute()
{
   var snapshot = route.snapshot;
   console.log(snapshot._routeConfig.component.name);
}
</code>```

Hope useful

Title: Angular - Get Component name from a URL

Body:
I have routes defined this way in app-routing.module.ts:

const routes: Routes = [
  {
    path: 'abc/:id', component: AbcComponent
  },
  {
    path: 'xyz/:id/tester/:mapId', component: XyzComponent
  },
  { path: '**', redirectTo: '/page-not-found', pathMatch: 'full'}
]

I would like to get the component name based on a URL in app.component.ts

Ex: If a user navigated to http://myapp.com/abc/123 I would like to the get the component name, which in this case would be AbcComponent

If a user navigated to http://myapp.com/xyz/123/tester/456 I would like to the get the component name, which in this case would be XyzComponent

How can I get that?

I tried to use ActivatedRoute, but it doesn't seem to work, as I get Cannot read property 'component' of null.

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
 this.checkRoute()
}

checkRoute()
{
   console.log(this.activatedRoute.routeConfig.component.name)
}

Body:
Try this it work for me

constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
 this.checkRoute()
}

checkRoute()
{
   var snapshot = route.snapshot;
   console.log(snapshot._routeConfig.component.name);
}

Hope useful


来源: stackexchange

问:
The dynamically added click event gets fired many times
I am adding a row to the html table on click event of a button. Inside that row, I have 1 cell which contains li element. I have assigned click event for that li element. When I click on li the event gets fired many times, i dont know why...kindly help.</p>

```<code><input id="btnAddRow" type="button" value="Add Row" />
<div id="mainSection">
    <table id="tblList" border="1" cellpadding="1" cellspacing="1">

    </table>
</div>
$(document).ready(function ()
{
    $('#btnAddRow').click(function ()
    {
        $('body').on('click', 'li', function () {
            alert($(this).text());
        })
        var markUp = '<tr><td>1</td><td>2</td><td>3</td><td><li>Hello</li></td></tr>';
        $('table').append(markUp);
        $('table').on('click', 'li', function () {
            alert($(this).text());
        })
    })

});
</code>```

答:
You're binding the click handler multiple times.

```<code>// on each click…
$('#btnAddRow').click(function() {
  // bind a click event on body
  $('body').on('click', 'li', function () {
    alert($(this).text());
  })
  // ...
  // bind a click event on every table
  $('table').on('click', 'li', function () {
    alert($(this).text());
  })
})
</code>```

As a result, every time your #btnAddRow is clicked you add two additional event handlers, one to body and another to all table elements.

ContentLicense: CC BY-SA 4.0

Body:
I am adding a row to the html table on click event of a button. Inside that row, I have 1 cell which contains li element. I have assigned click event for that li element. When I click on li the event gets fired many times, i dont know why...kindly help.

<input id="btnAddRow" type="button" value="Add Row" />

$(document).ready(function ()
{
    $('#btnAddRow').click(function ()
    {
        $('body').on('click', 'li', function () {
            alert($(this).text());
        })
        var markUp = '
1	2	3
Hello

';
        $('table').append(markUp);
        $('table').on('click', 'li', function () {
            alert($(this).text());
        })
    })

});

Body:
You're binding the click handler multiple times.

// on each click…
$('#btnAddRow').click(function() {
  // bind a click event on body
  $('body').on('click', 'li', function () {
    alert($(this).text());
  })
  // ...
  // bind a click event on every table
  $('table').on('click', 'li', function () {
    alert($(this).text());
  })
})

As a result, every time your #btnAddRow is clicked you add two additional event handlers, one to body and another to all table elements.


问:
Should I check the dotnet-tools .config directory into source control?
Recently I've noticed a .config directory being created by Visual Studio with a dotnet-tools.json file in.  Should this be .gitignored or checked into source control?

答:
.config directory with dotnet-tools.json file is created when you install a tool for your project with dotnet tool install command. This file dotnet-tools.json contains details like version, installation command etc. about all the tools installed for your project. It is more of a local configuration related to setup on local machine.
If you want your colleague  to install the same tools on her/his machine then you should check-in this file and your colleague is required to clone and run command to restore the same tool on her/his machine. This is very much similar to NuGet packages.

You can safely add this to .gitignore. In this case, your collegue will still be able to perform a fresh install of the same tool using dotnet tool install with same or different version.

Here is a good article on this topic


问:
Why do Powershell and the WinAPI recognize huge numbers as negative numbers when seeking in a file?
I'm studying the NTFS filesystem, and I have a weird problem when trying to seek in \\.\PhysicalDrive0 with a huge number like 0xb2ec0000 (3001810944). The $MFT of my Windows partition is supposed to reside at that offset (which is the case).

When I was seeking from that number (even from the decimal form: 3001810944), SetFilePointer returned ERROR_NEGATIVE_SEEK, so I decided to learn how negative numbers work in hexadecimal.

From that topic, I understood why 0xb2ec0000 was considered as negative, because it starts with b. Powershell also recognizes it as negative:

PS A:\core> 0xb2ec0000
-1293156352
```

<p>It can't only be a negative number, if we exclude the existence of negative numbers in hexadecimal, from some hexadecimal to decimal converters we realize that it's also equal to <code>3001810944</code>.</p>

<p>To successfully seek at offset <code>0xb2ec0000</code>, I decided to seek two times of <code>3001810944 / 2</code> bytes (<code>1500905472</code>), it worked fine, but it's a problem if some natural numbers are considered as negative if they aren't in the given context, it doesn't seem normal at all.</p>

<p>And concerning the division, if I decide to do <code>0xb2ec0000 / 2</code> it outputs:</p>

<pre class="lang-none prettyprint-override"><code>PS A:\core> 0xb2ec0000 / 2
-646578176
</code>```

but

PS A:\core> 3001810944 / 2
1500905472
```

<p>Here is the Rust code of the program:</p>

<p>You can reproduce the example by opening <code>\\.\PhysicalDrive0</code> and seeking at offset <code>0xb2ec0000</code>:</p>

```extern "system"{
    // [...]
    fn CreateFileA(a: *const u8, b: u32, c: u32, d: *mut c_void, e: u32, f: u32, g: *mut c_void) -> *mut c_void;
    fn SetFilePointer(a: *mut c_void, b: i64, c: *mut i32, d: u32) -> i32;
}
// [...]

let boot = CreateFileA(
    "\\\\.\\PhysicalDrive0\0".as_ptr(),
    25,
    0x00000002 | 0x00000001,
    null_mut(),
    3,
    128,
    null_mut()
);

// [...] Calculating $MFT offset

let mft_offset: i64 = mft_logical_cluster * (bpb.wBytesPerSec * bpb.uchSecPerClust as u16) as i64 + (dsk_info.dwRelativeSector * 512) as i64;

println!("{:x}", mft_offset); // outputs 0xb2ec0000

if(SetFilePointer(boot,mft_offset,null_mut(),0) == -1){
    println!("Error: {}", GetLastError()); // outputs 131
}
```

答:
You have incorrectly defined SetFilePointer as taking an i64 when it is an i32.

If you take the time to thoroughly read the docs for SetFilePointer, you'll see:

lDistanceToMove

The low order 32-bits of a signed value that specifies the number of
  bytes to move the file pointer.

If lpDistanceToMoveHigh is not NULL, lpDistanceToMoveHigh and
  lDistanceToMove form a single 64-bit signed value that specifies the
  distance to move.

If lpDistanceToMoveHigh is NULL, lDistanceToMove is a 32-bit signed
  value. A positive value for lDistanceToMove moves the file pointer
  forward in the file, and a negative value moves the file pointer back.

lpDistanceToMoveHigh

A pointer to the high order 32-bits of the signed 64-bit distance to
  move.

If you do not need the high order 32-bits, this pointer must be set to
  NULL.

You will need to split the i64 into two parts and pass each part separately, the high bits as a pointer to a value.

You should not be attempting to write the FFI definitions yourself (because you'll get them wrong). Ideally, use the winapi crate, which has the correct definition for SetFilePointer.

Even better, just use regular Rust types like File and Seek.

Body:
I'm studying the NTFS filesystem, and I have a weird problem when trying to seek in \\.\PhysicalDrive0 with a huge number like 0xb2ec0000 (3001810944). The $MFT of my Windows partition is supposed to reside at that offset (which is the case).

When I was seeking from that number (even from the decimal form: 3001810944), SetFilePointer returned ERROR_NEGATIVE_SEEK, so I decided to learn how negative numbers work in hexadecimal.

From that topic, I understood why 0xb2ec0000 was considered as negative, because it starts with b. Powershell also recognizes it as negative:

PS A:\core> 0xb2ec0000
-1293156352

It can't only be a negative number, if we exclude the existence of negative numbers in hexadecimal, from some hexadecimal to decimal converters we realize that it's also equal to 3001810944.

To successfully seek at offset 0xb2ec0000, I decided to seek two times of 3001810944 / 2 bytes (1500905472), it worked fine, but it's a problem if some natural numbers are considered as negative if they aren't in the given context, it doesn't seem normal at all.

And concerning the division, if I decide to do 0xb2ec0000 / 2 it outputs:

PS A:\core> 0xb2ec0000 / 2
-646578176

but

PS A:\core> 3001810944 / 2
1500905472

Here is the Rust code of the program:

You can reproduce the example by opening \\.\PhysicalDrive0 and seeking at offset 0xb2ec0000:

extern "system"{
    // [...]
    fn CreateFileA(a: *const u8, b: u32, c: u32, d: *mut c_void, e: u32, f: u32, g: *mut c_void) -> *mut c_void;
    fn SetFilePointer(a: *mut c_void, b: i64, c: *mut i32, d: u32) -> i32;
}
// [...]

let boot = CreateFileA(
    "\\\\.\\PhysicalDrive0\0".as_ptr(),
    25,
    0x00000002 | 0x00000001,
    null_mut(),
    3,
    128,
    null_mut()
);

// [...] Calculating $MFT offset

let mft_offset: i64 = mft_logical_cluster * (bpb.wBytesPerSec * bpb.uchSecPerClust as u16) as i64 + (dsk_info.dwRelativeSector * 512) as i64;

println!("{:x}", mft_offset); // outputs 0xb2ec0000

if(SetFilePointer(boot,mft_offset,null_mut(),0) == -1){
    println!("Error: {}", GetLastError()); // outputs 131
}


问:
JavaFX: Hide ComBox arrow
I am trying to hide the ComboBox arrow using the method in here, but for some reason I get this:

答:
This is really old post but just an update if anybody need it. If you want to style just one combo box you can do it in two other ways. First to define id of the combo in Css

```<code>#idOfTheComboBox>  .arrow-button > .arrow {
   -fx-background-color: transparent;
}
#idOfTheComboBox>  .arrow-button {
   -fx-background-color: transparent;
}
</code>```

or with class

```<code>.your-class >  .arrow-button > .arrow {
   -fx-background-color: transparent;
}
.your-class >  .arrow-button {
   -fx-background-color: transparent;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: JavaFX: Hide ComBox arrow

Body:
This is really old post but just an update if anybody need it. If you want to style just one combo box you can do it in two other ways. First to define id of the combo in Css

#idOfTheComboBox>  .arrow-button > .arrow {
   -fx-background-color: transparent;
}
#idOfTheComboBox>  .arrow-button {
   -fx-background-color: transparent;
}

or with class

.your-class >  .arrow-button > .arrow {
   -fx-background-color: transparent;
}
.your-class >  .arrow-button {
   -fx-background-color: transparent;
}


问:
Object creation order with class having containment of other objects
```<code>#include "iostream"
using namespace std;
class C
{
    public:
    C() { cout << "C's Constructor Called " << endl;  }
};

class A
{
    public:
    A() { cout << "A's Constructor Called " << endl;  }
    A(int) {  cout << "A's int Constructor Called " << endl;  }
};

class B
{
    public:
    A a;
    B() { cout << "B's Constructor Called " << endl; }
    B(int i) : a(i) { cout << "B's int Constructor Called " << endl; }
    C c;
};

int main()
{
    B b1(1);
    return 0;
}
</code>```

Output:

    A's int Constructor Called

    C's Constructor Called

    B's int Constructor Called

Question :

Why output does not contain "A's Constructor Called"

According to me i thought Output would be like below :

    A's Constructor Called

    C's Constructor Called

    B's int Constructor Called

Wondering why A a does not lead to constructor A() being called but only A(int) because of a(i)

答:
A's constructor is not called because it is overridden by the parameterised constructor in the initialisation list here - B(int i) : a(i).

If you observe carefully "B's Constructor Called" is also not printed because of the same reason.

Body:
#include "iostream"
using namespace std;
class C
{
    public:
    C() { cout << "C's Constructor Called " << endl;  }
};

class A
{
    public:
    A() { cout << "A's Constructor Called " << endl;  }
    A(int) {  cout << "A's int Constructor Called " << endl;  }
};

class B
{
    public:
    A a;
    B() { cout << "B's Constructor Called " << endl; }
    B(int i) : a(i) { cout << "B's int Constructor Called " << endl; }
    C c;
};

int main()
{
    B b1(1);
    return 0;
}

Output:

    A's int Constructor Called

    C's Constructor Called

    B's int Constructor Called

Question :

Why output does not contain "A's Constructor Called"

According to me i thought Output would be like below :

    A's Constructor Called

    C's Constructor Called

    B's int Constructor Called

Wondering why A a does not lead to constructor A() being called but only A(int) because of a(i)


问:
Perform a lookup between C# Lists and return matched where value is minimum
I have two lists:

```<code>var qtys = new List<InventoryQuantity>()
{
    new InventoryQuantity() { WarehouseId = 1, QuantityInWarehouse = 0 },
    new InventoryQuantity() { WarehouseId = 2, QuantityInWarehouse = 452 },
    new InventoryQuantity() { WarehouseId = 3, QuantityInWarehouse = 184 },
    new InventoryQuantity() { WarehouseId = 4, QuantityInWarehouse = 328 },
    new InventoryQuantity() { WarehouseId = 5, QuantityInWarehouse = 0 },
};

var times = new List<WarehouseTransitTime>()
{
    new WarehouseTransitTime() { WarehouseId = 1, TransitDays = 1 },
    new WarehouseTransitTime() { WarehouseId = 2, TransitDays = 4 },
    new WarehouseTransitTime() { WarehouseId = 3, TransitDays = 2 },
    new WarehouseTransitTime() { WarehouseId = 4, TransitDays = 3 },
    new WarehouseTransitTime() { WarehouseId = 5, TransitDays = 5 },
};

class InventoryQuantity
{
    public int WarehouseId { get; set; }
    public int QuantityInWarehouse { get; set; }
}

class WarehouseTransitTime
{
    public int WarehouseId { get; set; }
    public int TransitDays { get; set; }
}
</code>```

I need to return the WarehouseId from qtys where the Quantity > 0 and the WarehouseId equals the minimum transit days WarehouseId in times.

I know I can do something like below but seems clunky and there must be an elegant solution.

```<code>    public int NearestWarehouse()
    {
        var withQty = qtys.Where(i => i.QuantityInWarehouse > 0);
        var orderedTransit = times.OrderBy(tt => tt.TransitDays).ToList();
        //loop and compare
    }
</code>```

Example data:

qtys

```<code>WarehouseId | Quantity
1           | 0
2           | 452
3           | 184
4           | 328
5           | 0
</code>```

times

```<code>WarehouseId | TransitTime
1           | 1
2           | 4
3           | 2
4           | 3
5           | 5
</code>```

Expected output would be 3, because warehouse 3 has inventory and the shortest transit time (2)

答:
Well you mention an AND relation between the two, right?

I was thinking of databases with a forignkey... but Linq prety much does it if your lists aren't to big:

```<code>keys = qtys.Where(i => i.QuantityInWarehouse > 0).Select(i => i.WarehouseId).ToList();
// get the smallest not a list
var result = times.Where(tt => keys.Contains(tt.wharehouseId)).orderby(tt => tt.Transitdays).FirstOrDefault();
</code>```

Otherwise you could have Dictionary with ID as key...

Body:
I have two lists:

var qtys = new List<InventoryQuantity>()
{
    new InventoryQuantity() { WarehouseId = 1, QuantityInWarehouse = 0 },
    new InventoryQuantity() { WarehouseId = 2, QuantityInWarehouse = 452 },
    new InventoryQuantity() { WarehouseId = 3, QuantityInWarehouse = 184 },
    new InventoryQuantity() { WarehouseId = 4, QuantityInWarehouse = 328 },
    new InventoryQuantity() { WarehouseId = 5, QuantityInWarehouse = 0 },
};

var times = new List<WarehouseTransitTime>()
{
    new WarehouseTransitTime() { WarehouseId = 1, TransitDays = 1 },
    new WarehouseTransitTime() { WarehouseId = 2, TransitDays = 4 },
    new WarehouseTransitTime() { WarehouseId = 3, TransitDays = 2 },
    new WarehouseTransitTime() { WarehouseId = 4, TransitDays = 3 },
    new WarehouseTransitTime() { WarehouseId = 5, TransitDays = 5 },
};

class InventoryQuantity
{
    public int WarehouseId { get; set; }
    public int QuantityInWarehouse { get; set; }
}

class WarehouseTransitTime
{
    public int WarehouseId { get; set; }
    public int TransitDays { get; set; }
}

I need to return the WarehouseId from qtys where the Quantity > 0 and the WarehouseId equals the minimum transit days WarehouseId in times.

I know I can do something like below but seems clunky and there must be an elegant solution.

    public int NearestWarehouse()
    {
        var withQty = qtys.Where(i => i.QuantityInWarehouse > 0);
        var orderedTransit = times.OrderBy(tt => tt.TransitDays).ToList();
        //loop and compare
    }

Example data:

qtys

WarehouseId | Quantity
1           | 0
2           | 452
3           | 184
4           | 328
5           | 0

times

WarehouseId | TransitTime
1           | 1
2           | 4
3           | 2
4           | 3
5           | 5

Expected output would be 3, because warehouse 3 has inventory and the shortest transit time (2)

Body:
Well you mention an AND relation between the two, right?

I was thinking of databases with a forignkey... but Linq prety much does it if your lists aren't to big:

keys = qtys.Where(i => i.QuantityInWarehouse > 0).Select(i => i.WarehouseId).ToList();
// get the smallest not a list
var result = times.Where(tt => keys.Contains(tt.wharehouseId)).orderby(tt => tt.Transitdays).FirstOrDefault();

Otherwise you could have Dictionary with ID as key...


问:
How to create a floating label entry in Xamarin Forms?
I decided to create a control that will work like Android's floating label entry (for it to work with both, Android and iOS). The way to go for me seemed to create a view that will have two items, Entry and Label. On Entry.Focused event I'll animate the label to move upward. On Entry.Unfocused event, if there'll be any text, nothing will change, if the entry will be empty, I'll reverse the animation. Now, the problem is that I don't want to inherit from View, because I want my view to have all the properties that Entry has and I don't want to implement all of them by myself. The best way seems to be inheriting from Entry and adding custom functionality, but in this case, I don't know how to overlay a Label over the entry. My question is, how do I do that? How do I extend Entry so that I'll be able to overlay it with some other items?

Sorry if I didn't make myself clear, please ask for more info if something is unclear and I'll elaborate.

答: I realize this post is on the old side, but for anyone who has the same question, there's a library that can do this for you called PhantomLib. It's an open source nuget package that has a bunch of features like adding a show/hide button to an entry for passwords, adding an X button to an entry for clearing the text, floating label entry, and much more. Here's a blog post on how to use it  and the library is located here.


问:
Delete scheduled task in Marklogic
I'm trying to delete a scheduled task in Marklogic every time my function is called. It should go through the tasks, and delete the task if it matches the correct task path type and time. However I'm getting a
500 Internal Server Error

XDMP-UNEXPECTED: (err:XPST0003) Unexpected token syntax error, unexpected QName_

in /eval, at 10:20 [1.0-ml]

The code should delete the task if it is there, and then add a new task on deployment, thus deleting the task if it was in the scheduled tasks, then creating a new one. Here is my code:

```<code>      def delete_cron
            r = execute_query_camel_rest(%Q{
            xquery version "1.0-ml";
            import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
            declare namespace group = "http://marklogic.com/xdmp/group";

            let $taskPath := "/my/task/path.xqy" (: Replace with .xqy file :)

            let $tasks :=
                for admin:group-get-scheduled-tasks($config, admin:group-get-id($config, "Default"))
                where $task/group:task-path = $taskPath and $task/group:task-type = minutely and $task/group:task-period = 1
            return $task

        let $deleteTask := admin:group-delete-scheduled-task($config,  admin:group-get-id($config, "Default"), $task)
        return admin:save-configuration($deleteTask)

  },
           {
              :db_name => @properties["ml.database-name"]
           }
  )
</code>```

I want that delete function to be called before my add task function like so..

```<code>def add_cron
        delete_heartbeat_cron
            r = execute_query_camel_rest(%Q{
            xquery version "1.0-ml";
            import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
            declare namespace group = "http://marklogic.com/xdmp/group";
</code>```

答:
I have successfully deleted the task by specifying certain properties it has and calling the admin:group-delete-scheduled-task.

```<code>         let $deleteTask :=
         for $task in $tasks
            where $task/group:task-period = 1 and $task/group:task-type = "minutely" and $task/group:task-path = $taskPath
         return $task

        let $config := admin:group-delete-scheduled-task($config,  admin:group-get-id($config, "Default"), $deleteTask)
        return admin:save-configuration($config)
</code>```

I had to change my for loop, and added the variable $deleteTask.

Title: Delete scheduled task in Marklogic

Body:
I'm trying to delete a scheduled task in Marklogic every time my function is called. It should go through the tasks, and delete the task if it matches the correct task path type and time. However I'm getting a
500 Internal Server Error

XDMP-UNEXPECTED: (err:XPST0003) Unexpected token syntax error, unexpected QName_

in /eval, at 10:20 [1.0-ml]

The code should delete the task if it is there, and then add a new task on deployment, thus deleting the task if it was in the scheduled tasks, then creating a new one. Here is my code:

      def delete_cron
            r = execute_query_camel_rest(%Q{
            xquery version "1.0-ml";
            import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
            declare namespace group = "http://marklogic.com/xdmp/group";

            let $taskPath := "/my/task/path.xqy" (: Replace with .xqy file :)

            let $tasks :=
                for admin:group-get-scheduled-tasks($config, admin:group-get-id($config, "Default"))
                where $task/group:task-path = $taskPath and $task/group:task-type = minutely and $task/group:task-period = 1
            return $task

        let $deleteTask := admin:group-delete-scheduled-task($config,  admin:group-get-id($config, "Default"), $task)
        return admin:save-configuration($deleteTask)

  },
           {
              :db_name => @properties["ml.database-name"]
           }
  )

I want that delete function to be called before my add task function like so..

def add_cron
        delete_heartbeat_cron
            r = execute_query_camel_rest(%Q{
            xquery version "1.0-ml";
            import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
            declare namespace group = "http://marklogic.com/xdmp/group";

Body:
I have successfully deleted the task by specifying certain properties it has and calling the admin:group-delete-scheduled-task.

         let $deleteTask :=
         for $task in $tasks
            where $task/group:task-period = 1 and $task/group:task-type = "minutely" and $task/group:task-path = $taskPath
         return $task

        let $config := admin:group-delete-scheduled-task($config,  admin:group-get-id($config, "Default"), $deleteTask)
        return admin:save-configuration($config)

I had to change my for loop, and added the variable $deleteTask.


问:
use psych reverse.code() on dataframe in R
I'm trying to use reverse.code() from the psych package on one column in a dataframe that has numeric and non-numeric columns. However, when I try to do this, I get an error:

```<code>Error in items %*% keys.d :
  requires numeric/complex matrix/vector arguments
</code>```

Do you have any suggestions on how to make this work? I am making a tutorial for my students who vary greatly in their R capabilities, so the simpler the code, the better. Here is a mock dataset that gives the same error:

```<code>sample <- tibble(name = c("Joe", "Frank"),
                 item_1 = c(1, 1),
                 item_2 = c(1, 1),
                 item_3 = c(5, 5))

key <- c("item_3")
reverse.code(keys = key, items = sample, mini = 1, maxi = 5)
</code>```

答:
If we select the data without including the first column i.e. character column, it should work

```<code>library(psych)
reverse.code(keys = key, items =sample[-1], mini = 1, maxi = 5)
#    item_1 item_2 item_3-
#[1,]      1      1       1
#[2,]      1      1       1
</code>```

Or in a %>%

```<code>library(dplyr)
sample %>%
    select_if(is.numeric) %>%
    reverse.code(keys  = key, items = ., mini = 1, maxi = 5)
</code>```

Body:
I'm trying to use reverse.code() from the psych package on one column in a dataframe that has numeric and non-numeric columns. However, when I try to do this, I get an error:

Error in items %*% keys.d :
  requires numeric/complex matrix/vector arguments

Do you have any suggestions on how to make this work? I am making a tutorial for my students who vary greatly in their R capabilities, so the simpler the code, the better. Here is a mock dataset that gives the same error:

sample <- tibble(name = c("Joe", "Frank"),
                 item_1 = c(1, 1),
                 item_2 = c(1, 1),
                 item_3 = c(5, 5))

key <- c("item_3")
reverse.code(keys = key, items = sample, mini = 1, maxi = 5)

Body:
If we select the data without including the first column i.e. character column, it should work

library(psych)
reverse.code(keys = key, items =sample[-1], mini = 1, maxi = 5)
#    item_1 item_2 item_3-
#[1,]      1      1       1
#[2,]      1      1       1

Or in a %>%

library(dplyr)
sample %>%
    select_if(is.numeric) %>%
    reverse.code(keys  = key, items = ., mini = 1, maxi = 5)


问:
Unable to draw multiple objects using VAOs and EBOs (openGL)
I was experimenting with using Vertex Array Objects and Element Buffer Objects. I managed to draw the letter "H" on my screen using a single VAO with an EBO bound since all my vertices and indices were in one array. I wanted to split each rectangle into a different object though and give them a different color, but only one of them is drawing on the screen.

Here's the code:

```<code>#include <glew.h>
#include <glfw3.h>
#include <iostream>

const char* vertexShaderSource = "#version 330 core\n"
    "layout (location = 0) in vec3 aPos;\n"
    "void main()\n"
    "{\n"
    "gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
    "}\0";

const char* fragmentShaderSource = "#version 330 core\n"
    "out vec4 FragColor;\n"
    "void main()\n"
    "{\n"
    "FragColor = vec4(0.2f, 0.6f, 0.7f, 1.0f);\n"
    "}\0";

const char* fragmentShaderSource2 = "#version 330 core\n"
    "out vec4 FragColor;\n"
    "void main()\n"
    "{\n"
    "FragColor = vec4(0.7f, 0.4f, 0.3f, 1.0f);\n"
    "}\0";

const char* fragmentShaderSource3 = "#version 330 core\n"
    "out vec4 FragColor;\n"
    "void main()\n"
    "{\n"
    "FragColor = vec4(0.1f, 0.2f, 0.6f, 1.0f);\n"
    "}\0";

int main(void)
{
    GLFWwindow* window;

    glewInit();
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    if (glewInit() != GLEW_OK)
        std::cout << "Error!" << std::endl;

    float vertices[] = {
         0.2f, 0.7f, 0.0f,
         0.3f, 0.7f, 0.0f,
         0.3f, 0.2f, 0.0f,
         0.2f, 0.2f, 0.0f
    };

    float vertices2[] = {
         0.6f, 0.7f, 0.0f,
         0.7f, 0.7f, 0.0f,
         0.7f, 0.2f, 0.0f,
         0.6f, 0.2f, 0.0f
    };

    float vertices3[] = {
        0.3f, 0.4f, 0.0f,
        0.3f, 0.5f, 0.0f,
        0.6f, 0.5f, 0.0f,
        0.6f, 0.4f, 0.0f
    };

    unsigned int indices[] = {
        1, 0, 2,
        2, 3, 0
    };

    unsigned int indices2[] = {
        5, 4, 6,
        6, 7, 4
    };

    unsigned int indices3[] = {
        8, 9, 11,
        11, 10, 9
    };

    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);

    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);

    int  success;
    char infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);

    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);

    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);

    if (!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    unsigned int fragmentShader2 = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader2, 1, &fragmentShaderSource2, NULL);
    glCompileShader(fragmentShader2);

    unsigned int fragmentShader3 = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader3, 1, &fragmentShaderSource3, NULL);
    glCompileShader(fragmentShader3);

    unsigned int shaderProgram;
    shaderProgram = glCreateProgram();

    unsigned int shaderProgram2;
    shaderProgram2 = glCreateProgram();

    unsigned int shaderProgram3;
    shaderProgram3 = glCreateProgram();

    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    glAttachShader(shaderProgram2, fragmentShader2);
    glAttachShader(shaderProgram2, vertexShader);
    glLinkProgram(shaderProgram2);
    glAttachShader(shaderProgram3, fragmentShader3);
    glAttachShader(shaderProgram3, vertexShader);
    glLinkProgram(shaderProgram3);

    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);

    if (!success)
    {
        glGetShaderInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
    glDeleteShader(fragmentShader2);
    glDeleteShader(fragmentShader3);

    unsigned int VBOs[3], VAOs[3], EBOs[3];

    glGenVertexArrays(3, VAOs);
    glGenBuffers(3, VBOs);
    glGenBuffers(3, EBOs);

    glBindVertexArray(VAOs[0]);
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBOs[0]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindVertexArray(VAOs[1]);
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBOs[1]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices2), indices2, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindVertexArray(VAOs[2]);
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[2]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices3), vertices3, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBOs[2]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices3), indices3, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {

        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shaderProgram);
        glBindVertexArray(VAOs[0]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        glUseProgram(shaderProgram2);
        glBindVertexArray(VAOs[1]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        glUseProgram(shaderProgram3);
        glBindVertexArray(VAOs[2]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }
    glDeleteVertexArrays(3, VAOs);
    glDeleteBuffers(3, VBOs);
    glDeleteBuffers(3, EBOs);

    glfwTerminate();
    return 0;
}
</code>```

答:
You'll have here:

```<code>float vertices2[] = {
     0.6f, 0.7f, 0.0f,
     0.7f, 0.7f, 0.0f,
     0.7f, 0.2f, 0.0f,
     0.6f, 0.2f, 0.0f
};
</code>```

together with:

```<code>unsigned int indices2[] = {
    5, 4, 6,
    6, 7, 4
};
</code>```

That does not make sense. You only copy 4 vertices to your VBO[1], and you set the attrib pointer to offset 0 in that buffer, so the only valid indices are 0,1,2 and 3.

Your indices are set as if all your vertices were in a single big array as before, and actually, that would be a much better strategy: Keep one big vertex array, and one big element indices array, and one VAO, and just draw individual parts of that array by changing the indices argument in the glDrawElements() call, like this:

```<code>glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // first 6 indices
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void*)(6*sizeof(GLuint))); // second 6 indices
// ...
</code>```

Also not that using 3 different shaders here is very inefficient. It woold be best if you just added the color as another attribute, and use a single draw call (implying a single shader, single VAO) for everything.

Body:
I was experimenting with using Vertex Array Objects and Element Buffer Objects. I managed to draw the letter "H" on my screen using a single VAO with an EBO bound since all my vertices and indices were in one array. I wanted to split each rectangle into a different object though and give them a different color, but only one of them is drawing on the screen.

Here's the code:

#include <glew.h>
#include <glfw3.h>
#include <iostream>

const char* vertexShaderSource = "#version 330 core\n"
    "layout (location = 0) in vec3 aPos;\n"
    "void main()\n"
    "{\n"
    "gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
    "}\0";

const char* fragmentShaderSource = "#version 330 core\n"
    "out vec4 FragColor;\n"
    "void main()\n"
    "{\n"
    "FragColor = vec4(0.2f, 0.6f, 0.7f, 1.0f);\n"
    "}\0";

const char* fragmentShaderSource2 = "#version 330 core\n"
    "out vec4 FragColor;\n"
    "void main()\n"
    "{\n"
    "FragColor = vec4(0.7f, 0.4f, 0.3f, 1.0f);\n"
    "}\0";

const char* fragmentShaderSource3 = "#version 330 core\n"
    "out vec4 FragColor;\n"
    "void main()\n"
    "{\n"
    "FragColor = vec4(0.1f, 0.2f, 0.6f, 1.0f);\n"
    "}\0";

int main(void)
{
    GLFWwindow* window;

    glewInit();
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    if (glewInit() != GLEW_OK)
        std::cout << "Error!" << std::endl;

    float vertices[] = {
         0.2f, 0.7f, 0.0f,
         0.3f, 0.7f, 0.0f,
         0.3f, 0.2f, 0.0f,
         0.2f, 0.2f, 0.0f
    };

    float vertices2[] = {
         0.6f, 0.7f, 0.0f,
         0.7f, 0.7f, 0.0f,
         0.7f, 0.2f, 0.0f,
         0.6f, 0.2f, 0.0f
    };

    float vertices3[] = {
        0.3f, 0.4f, 0.0f,
        0.3f, 0.5f, 0.0f,
        0.6f, 0.5f, 0.0f,
        0.6f, 0.4f, 0.0f
    };

    unsigned int indices[] = {
        1, 0, 2,
        2, 3, 0
    };

    unsigned int indices2[] = {
        5, 4, 6,
        6, 7, 4
    };

    unsigned int indices3[] = {
        8, 9, 11,
        11, 10, 9
    };

    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);

    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);

    int  success;
    char infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);

    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);

    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);

    if (!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    unsigned int fragmentShader2 = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader2, 1, &fragmentShaderSource2, NULL);
    glCompileShader(fragmentShader2);

    unsigned int fragmentShader3 = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader3, 1, &fragmentShaderSource3, NULL);
    glCompileShader(fragmentShader3);

    unsigned int shaderProgram;
    shaderProgram = glCreateProgram();

    unsigned int shaderProgram2;
    shaderProgram2 = glCreateProgram();

    unsigned int shaderProgram3;
    shaderProgram3 = glCreateProgram();

    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    glAttachShader(shaderProgram2, fragmentShader2);
    glAttachShader(shaderProgram2, vertexShader);
    glLinkProgram(shaderProgram2);
    glAttachShader(shaderProgram3, fragmentShader3);
    glAttachShader(shaderProgram3, vertexShader);
    glLinkProgram(shaderProgram3);

    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);

    if (!success)
    {
        glGetShaderInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
    glDeleteShader(fragmentShader2);
    glDeleteShader(fragmentShader3);

    unsigned int VBOs[3], VAOs[3], EBOs[3];

    glGenVertexArrays(3, VAOs);
    glGenBuffers(3, VBOs);
    glGenBuffers(3, EBOs);

    glBindVertexArray(VAOs[0]);
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBOs[0]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindVertexArray(VAOs[1]);
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBOs[1]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices2), indices2, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindVertexArray(VAOs[2]);
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[2]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices3), vertices3, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBOs[2]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices3), indices3, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {

        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shaderProgram);
        glBindVertexArray(VAOs[0]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        glUseProgram(shaderProgram2);
        glBindVertexArray(VAOs[1]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        glUseProgram(shaderProgram3);
        glBindVertexArray(VAOs[2]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }
    glDeleteVertexArrays(3, VAOs);
    glDeleteBuffers(3, VBOs);
    glDeleteBuffers(3, EBOs);

    glfwTerminate();
    return 0;
}

Body:
You'll have here:

float vertices2[] = {
     0.6f, 0.7f, 0.0f,
     0.7f, 0.7f, 0.0f,
     0.7f, 0.2f, 0.0f,
     0.6f, 0.2f, 0.0f
};

together with:

unsigned int indices2[] = {
    5, 4, 6,
    6, 7, 4
};

That does not make sense. You only copy 4 vertices to your VBO[1], and you set the attrib pointer to offset 0 in that buffer, so the only valid indices are 0,1,2 and 3.

Your indices are set as if all your vertices were in a single big array as before, and actually, that would be a much better strategy: Keep one big vertex array, and one big element indices array, and one VAO, and just draw individual parts of that array by changing the indices argument in the glDrawElements() call, like this:

glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // first 6 indices
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void*)(6*sizeof(GLuint))); // second 6 indices
// ...

Also not that using 3 different shaders here is very inefficient. It woold be best if you just added the color as another attribute, and use a single draw call (implying a single shader, single VAO) for everything.


问:
How to uninstall dotnetcli from command line
Im using the formula described here (https://learn.microsoft.com/en-us/dotnet/core/versions/remove-runtime-sdk-versions?tabs=macos) to uninstall dotnet core sdk from macos. I followed the steps and after finishing and verifying there is not an sdk nor a runtime, the command dotnet is still valid in the terminal and is referring that is valid at hosting. Any ideas around how to remove all the sdk, cli from my laptop? </p>

答:
If you want to remove all versions and components of .NET Core, just delete the main dotnet directory:

```<code>sudo rm -rf /usr/local/share/dotnet
</code>```

Body:
If you want to remove all versions and components of .NET Core, just delete the main dotnet directory:

sudo rm -rf /usr/local/share/dotnet


问:
FFTW Segfault (Likely simple answer)
I'm trying to write a simple FFTW routine (version 2), and I think I've just about got the bones down, but I'm running into a persistent segfault when I call the fftwnd_one function (I'm doing a one dimensional transform, but I'm using the n-dimensional code for modularity's sake).  However, I believe my problem to be in the plan creation; could anyone offer some insight as to what's wrong with this code?  I'd greatly appreciate it if so - thank you!

For reference, the function that I'm working with here is sin(x).  I realize that not all of the mathematical operations have been implemented, I'm just trying to get the FFTW2 library working first, then I can make the data useful.

```<code>#include <stdio.h>
#include <fftw.h>
#include <math.h>
#include <complex.h>

int main(){
  int i;
  fftw_complex in[8];
  fftwnd_plan p;
  const int *n;
  int temp = (int)pow(2, 2)*pow(3,2)*pow(5,1)*pow(7,1)*pow(11,1)*pow(13,0);
  n = &temp;

  in[0].re = 0;
  in[1].re = (sqrt(2)/2);
  in[2].re = 1;
  in[3].re = (sqrt(2)/2);
  in[4].re = 0;
  in[5].re = -(sqrt(2)/2);
  in[6].re = -1;
  in[7].re = -(sqrt(2)/2);

  for(i = 0; i < 8; i++){
    (in[i]).im = 0;
  }

  p = fftwnd_create_plan(8, n, FFTW_FORWARD, FFTW_ESIMATE | FFTW_IN_PLACE);
  fftwnd_one(p, &in[0], NULL);
  fftwnd_destroy_plan(p);

  printf("Sin\n");
  for(i = 0; i < 8; i++){
    printf("%d\n", n[i]);
  }
  return 0;
}
</code>```

答:
You seem to be treating n as an array, when it only points to a single integer. For example, should not this:

```<code>printf("%d\n", n[i]);
</code>```

be:

```<code>printf("%d\n", in[i]);
</code>```

Title: FFTW Segfault (Likely simple answer)

Body:
I'm trying to write a simple FFTW routine (version 2), and I think I've just about got the bones down, but I'm running into a persistent segfault when I call the fftwnd_one function (I'm doing a one dimensional transform, but I'm using the n-dimensional code for modularity's sake).  However, I believe my problem to be in the plan creation; could anyone offer some insight as to what's wrong with this code?  I'd greatly appreciate it if so - thank you!

For reference, the function that I'm working with here is sin(x).  I realize that not all of the mathematical operations have been implemented, I'm just trying to get the FFTW2 library working first, then I can make the data useful.

#include <stdio.h>
#include <fftw.h>
#include <math.h>
#include <complex.h>

int main(){
  int i;
  fftw_complex in[8];
  fftwnd_plan p;
  const int *n;
  int temp = (int)pow(2, 2)*pow(3,2)*pow(5,1)*pow(7,1)*pow(11,1)*pow(13,0);
  n = &temp;

  in[0].re = 0;
  in[1].re = (sqrt(2)/2);
  in[2].re = 1;
  in[3].re = (sqrt(2)/2);
  in[4].re = 0;
  in[5].re = -(sqrt(2)/2);
  in[6].re = -1;
  in[7].re = -(sqrt(2)/2);

  for(i = 0; i < 8; i++){
    (in[i]).im = 0;
  }

  p = fftwnd_create_plan(8, n, FFTW_FORWARD, FFTW_ESIMATE | FFTW_IN_PLACE);
  fftwnd_one(p, &in[0], NULL);
  fftwnd_destroy_plan(p);

  printf("Sin\n");
  for(i = 0; i < 8; i++){
    printf("%d\n", n[i]);
  }
  return 0;
}

Body:
You seem to be treating n as an array, when it only points to a single integer. For example, should not this:

printf("%d\n", n[i]);

be:

printf("%d\n", in[i]);


问:
Implementing OAuth2.0 to secure microservice architecture
I have been looking for several weeks to find a way to secure my application using microservice architecture using OAuth2 and I couldn't find any helpful material.

I would appreciate if anyone of you could help me.

答:
A common option is to use 2 levels of API:

The outside world connects to entry point APIs targeted at particular customers - eg Online Sales UI / B2B Partners

Entry point APIs call potentially many microservices focused on domain capabilities (Product / Customer / Stock)

In terms of security:

Entry point APIs require OAuth tokens

They validate tokens and get claims

They orchestrate calls to microservices

Microservices are in a locked down virtual private cloud

Microservices do not use OAuth security

Microservices receive OAuth claims, perhaps via headers

In this type of setup, microservices need to be properly locked down - typically no person should be able to access them directly in Staging or PROD - though you may make exceptions in earlier stages of the pipeline for QA purposes.

Also of course your stakeholders would need to sign off on whether this is acceptable from a security viewpoint.

Some further thoughts of mine in my blog post, though I am in the early days of applying this at scale.


问:
difference between http_proxy and https_proxy
I want to understand the difference between http_proxy and https_proxy environment variables.

So my understanding is that http_proxy will be used if I(as client) that sends http request. https_proxy will be used if I(as client) that sends https request.

There are some possible setting to set http_proxy and https_proxy:

```<code>1. http_proxy = http://proxy:port
2. https_proxy = http://proxy:port
3. http_proxy = https://proxy:port
4. https_proxy = https://proxy:port
</code>```

As I understand, Variant 1, 2 may be common settings. What about variant 3, is it a possible setting? How are the requests transmitted? I think 4 is also a possible setting, but I am not clear about the workflow.

Here is my guess:

In first setting, if I send a http request to a destination server, then http_proxy will be used, with this setting, the request will be send as client --(http request) --proxy --(http request) -- server

In second setting, if I send a https request to a destination server, then https_proxy will be used, with this setting, the request will be client --(https request)-- proxy --(https request) --server. In this case, the proxy will just transmit encrypted packets to server, the packets will be decrypted only at server side.

In third setting, if I send a http request to a destination server, with this setting, what will happen? Is it a eligible setting?

In fourth setting, if I send a https request to a destination server, then https_proxy will be used, with this setting, the request will be send with client --(https request) --proxy --(https request) -- server. In this case, does that means the client's https request encrypted with proxy's public key, , which proxy decrypt the request first, then encrypted with destination server's pk, and then forward the request to server? however, in this case, isn't it break the end to end encryption between client and server? If my assumption is wrong, what is the correct picture for this setting?

Concretely, I want to know the workflow about packets flow from client - proxy - server with different proxies(http/https) and proxy setting (set it with http_proxy/https_proxy).

In all cases I assume server can accept both http/https request. What about if server only accept http/https request? What happen regarding the above setting and how they will be activated?
I don't have a clear picture regarding to them.

答:
I think the picture you have is entirely correct.

http_proxy / https_proxy should both point to a proxy server that can proxy requests upstream. http_proxy would be used for plain http requests, meaning that the traffic from the client to the proxy would be unencrypted. https_proxy is used for https requests. In both cases, the client first would send an HTTP CONNECT request for a specific upstream to the proxy (which results in a TCP tunnel being created between the proxy and the upstream), and then sends the actual payload. The actual payload could be either plaintext or TLS encrypted, relayed from the client directly to the upstream by the proxy, without it ever decrypting the packets. The proxy establishes a TCP connection with the upstream. From that point on, the proxy relays every request from the client directly to the upstream over this connection, and likewise delivers every response back to the client. This means, there is no TLS termination or origination happening at the proxy - which is completely unaware of the content.

You can have a TLS-enabled forward proxy server, but the mechanisms are slightly different. With http_proxy and https_proxy, your clients are aware of the proxy's presence and suitably change the HTTP request to make it amenable for a proxy. TLS-enabled forward proxies are usually transparent. They decrypt the clients request (TLS termination), initiate a new TLS request to the server using standard client credentials when applicable, and then relays back the response to the client after applying some security policies to the request / response. The http_proxy / https_proxy environment variable don't directly have a role to play - nor is HTTP tunneling (via HTTP CONNECT or otherwise) involved.

In addition, there is another environment variable - NO_PROXY - which can be set to a comma-separated list of addresses, requests to which should not be proxied.

Body:
I want to understand the difference between http_proxy and https_proxy environment variables.

So my understanding is that http_proxy will be used if I(as client) that sends http request. https_proxy will be used if I(as client) that sends https request.

There are some possible setting to set http_proxy and https_proxy:

1. http_proxy = http://proxy:port
2. https_proxy = http://proxy:port
3. http_proxy = https://proxy:port
4. https_proxy = https://proxy:port

As I understand, Variant 1, 2 may be common settings. What about variant 3, is it a possible setting? How are the requests transmitted? I think 4 is also a possible setting, but I am not clear about the workflow.

Here is my guess:

In first setting, if I send a http request to a destination server, then http_proxy will be used, with this setting, the request will be send as client --(http request) --proxy --(http request) -- server

In second setting, if I send a https request to a destination server, then https_proxy will be used, with this setting, the request will be client --(https request)-- proxy --(https request) --server. In this case, the proxy will just transmit encrypted packets to server, the packets will be decrypted only at server side.

In third setting, if I send a http request to a destination server, with this setting, what will happen? Is it a eligible setting?

In fourth setting, if I send a https request to a destination server, then https_proxy will be used, with this setting, the request will be send with client --(https request) --proxy --(https request) -- server. In this case, does that means the client's https request encrypted with proxy's public key, , which proxy decrypt the request first, then encrypted with destination server's pk, and then forward the request to server? however, in this case, isn't it break the end to end encryption between client and server? If my assumption is wrong, what is the correct picture for this setting?

Concretely, I want to know the workflow about packets flow from client - proxy - server with different proxies(http/https) and proxy setting (set it with http_proxy/https_proxy).

In all cases I assume server can accept both http/https request. What about if server only accept http/https request? What happen regarding the above setting and how they will be activated?
I don't have a clear picture regarding to them.


问:
Calling graphql api on AWS with Cognito user pool id
I spent two days googling for a solution. But couldn't find a proper solution.
I am provided with the following information.

```<code>Cognito Identity pool ids:
INT: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
CRT: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
PSS: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
PREPROD: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
PROD: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

Api url : https://xxxxxxxxxxxxxxxx.appsync-api.us-east-2.amazonaws.com/graphql
Api id : 63xxxxxxxxxxxxxxxxxx
Appsync name : TheAppSyncName
Authorization mechanism : IAM auth
</code>```

I found there are few different ways to do this in Android, https://github.com/awslabs/aws-mobile-appsync-sdk-android

But no example could be found with .net c# AWS sdk.

Can someone please explain the meaning of the above values and how it can be used to call the graphql API in .net C#?

Update:
After trying multiple times I ended up without any solution. Then I found the appsync can't be used with the given information in c# .net. I was provided with the AWS account number and unauth role ARN in addition to above.

答:
The answer here will provide you with some context about the AWS SDK.

As that answer mentions, the AWS SDK does not provide a way invoke your API. To invoke you API it is as simple as making a post request to your API url.
There are a lot of answers about using postman for AppSync, which will help you understand the topic:

how to send graphql query by postman

how do I integrate amazon cognito login in postman

Once you understand that you should be able to do the same with any HTTP client of your choosing.

Body:
I spent two days googling for a solution. But couldn't find a proper solution.
I am provided with the following information.

Cognito Identity pool ids:
INT: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
CRT: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
PSS: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
PREPROD: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
PROD: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

Api url : https://xxxxxxxxxxxxxxxx.appsync-api.us-east-2.amazonaws.com/graphql
Api id : 63xxxxxxxxxxxxxxxxxx
Appsync name : TheAppSyncName
Authorization mechanism : IAM auth

I found there are few different ways to do this in Android, https://github.com/awslabs/aws-mobile-appsync-sdk-android

But no example could be found with .net c# AWS sdk.

Can someone please explain the meaning of the above values and how it can be used to call the graphql API in .net C#?

Update:
After trying multiple times I ended up without any solution. Then I found the appsync can't be used with the given information in c# .net. I was provided with the AWS account number and unauth role ARN in addition to above.


问:
Why Dice Coefficient and not IOU for segmentation tasks?
I have seen people using IOU as the metric for detection tasks and Dice Coeff for segmentation tasks. The two metrics looks very much similar in terms of equation except that dice gives twice the weightage to the intersection part. If I am correct, then

```<code>Dice: (2 x (A*B) / (A + B))
IOU : (A * B) / (A + B)
</code>```

Is there any particular reason for preferring dice for segmentation and IOU for detection?

答:
This is not exactly right.

The Dice coefficient (also known as the Sørensen–Dice coefficient and F1 score) is defined as two times the area of the intersection of A and B, divided by the sum of the areas of A and B:

```<code>Dice = 2 |A∩B| / (|A|+|B|) = 2 TP / (2 TP + FP + FN)
</code>```

(TP=True Positives, FP=False Positives, FN=False Negatives)

The IOU (Intersection Over Union, also known as the Jaccard Index) is defined as the area of the intersection divided by the area of the union:

```<code>Jaccard = |A∩B| / |A∪B| = TP / (TP + FP + FN)
</code>```

Note that the sum of the areas of A and B is not the same as the area of the union of A and B. In particular, if there is 100% overlap, then the one is twice the other. This is the reason of the "two times" in the Dice coefficent: they are both defined such that, with 100% overlap, the values are 1, and with 0% overlap the values are 0.

Which one to use depends on personal preference and customs in each field. That you see one used more in one field is related more to chance than anything else. Someone started using the Dice coefficient for segmentation, and other people just followed along. Someone started using IOU for detection, and other people just followed along.

Body:
I have seen people using IOU as the metric for detection tasks and Dice Coeff for segmentation tasks. The two metrics looks very much similar in terms of equation except that dice gives twice the weightage to the intersection part. If I am correct, then

Dice: (2 x (A*B) / (A + B))
IOU : (A * B) / (A + B)

Is there any particular reason for preferring dice for segmentation and IOU for detection?

Body:
This is not exactly right.

The Dice coefficient (also known as the Sørensen–Dice coefficient and F1 score) is defined as two times the area of the intersection of A and B, divided by the sum of the areas of A and B:

Dice = 2 |A∩B| / (|A|+|B|) = 2 TP / (2 TP + FP + FN)

(TP=True Positives, FP=False Positives, FN=False Negatives)

The IOU (Intersection Over Union, also known as the Jaccard Index) is defined as the area of the intersection divided by the area of the union:

Jaccard = |A∩B| / |A∪B| = TP / (TP + FP + FN)

Note that the sum of the areas of A and B is not the same as the area of the union of A and B. In particular, if there is 100% overlap, then the one is twice the other. This is the reason of the "two times" in the Dice coefficent: they are both defined such that, with 100% overlap, the values are 1, and with 0% overlap the values are 0.

Which one to use depends on personal preference and customs in each field. That you see one used more in one field is related more to chance than anything else. Someone started using the Dice coefficient for segmentation, and other people just followed along. Someone started using IOU for detection, and other people just followed along.


问:
How many branches can be created in github/gitlab?
Are there any limitations to create branches in GitHub/GitLab?

I am currenly working on a project, so that I am curious about creation of branches.
   How many branches can be created ?

答:
There is no hard limit on the number of branches, tags, remote-tracking names, and other references.  (All of Git's name-to-hash-ID map entries are refs or references: branch names are just refs whose full name starts with refs/heads/).

These are not always stored in separate files.  In particular, refs will become "packed" over time.  Packed refs live in one flat file, which makes them take (much) less disk space, though now reading any one particular ref's value—its hash ID—may involve reading a fairly large file, if you have many refs.  (Writing the value causes the ref to become unpacked, leaving the previous value behind in the packed-refs file—so as you can see, the process of finding a ref's value starts by looking for the unpacked copy first, as that must override any packed copy.)

Since each name-and-value-pair occupies so little disk space (one block or less), it's definitely possible to create millions of refs.  If you do this, though, your Git operations will slow down noticeably.  The reason is that Git is full of linear scans through all refs.  For instance, to "decorate" git log output,1 before git log prints a commit, it looks through every ref to see if that ref refers to that commit.  The question to which rootkonda's answer links has, in qqx's answer, another link to a nabble.com archived mailing list thread about performance issues that occur (some are fixed already, some remain).

GitHub and Google also both discovered some years ago that Git can spend a lot of time and network bandwidth in the greeting process that two Gits go through at startup, too: when you have your Git call up a server's Git for git fetch for instance, your Git has the server Git list out all of its branch and tag and other such names.  If there are, say ten thousand listed names, each an average of about 60 characters long when expanded with hash IDs,2 that's about 600 kilobytes of data transfer before any useful commit exchanges can occur.

In general, it's not a good plan to create thousands or millions of refs.  There's no theoretical reason not to do it but for protocol and performance reasons, a soft cap of under a thousand refs might be advisable.

1In:

```<code>commit c7a62075917b3340f908093f63f1161c44ed1475 (HEAD -> master, origin/master, origin/HEAD)
</code>```

the HEAD, master, origin master, and origin/HEAD are decorations found by searching all refs; the HEAD -> formatting indicates that HEAD is attached, in this case to master).

2Note that annotated tags get doubled here, as they list both the tag name and hash ID, and the tag name suffixed with ^{} and tag's target.  refs/tags/v1.2.3 09e393d913072d7765b02aba1210d843a83cfbae is 57 characters even without a newline or other separator.

Body:
There is no hard limit on the number of branches, tags, remote-tracking names, and other references.  (All of Git's name-to-hash-ID map entries are refs or references: branch names are just refs whose full name starts with refs/heads/).

These are not always stored in separate files.  In particular, refs will become "packed" over time.  Packed refs live in one flat file, which makes them take (much) less disk space, though now reading any one particular ref's value—its hash ID—may involve reading a fairly large file, if you have many refs.  (Writing the value causes the ref to become unpacked, leaving the previous value behind in the packed-refs file—so as you can see, the process of finding a ref's value starts by looking for the unpacked copy first, as that must override any packed copy.)

Since each name-and-value-pair occupies so little disk space (one block or less), it's definitely possible to create millions of refs.  If you do this, though, your Git operations will slow down noticeably.  The reason is that Git is full of linear scans through all refs.  For instance, to "decorate" git log output,1 before git log prints a commit, it looks through every ref to see if that ref refers to that commit.  The question to which rootkonda's answer links has, in qqx's answer, another link to a nabble.com archived mailing list thread about performance issues that occur (some are fixed already, some remain).

GitHub and Google also both discovered some years ago that Git can spend a lot of time and network bandwidth in the greeting process that two Gits go through at startup, too: when you have your Git call up a server's Git for git fetch for instance, your Git has the server Git list out all of its branch and tag and other such names.  If there are, say ten thousand listed names, each an average of about 60 characters long when expanded with hash IDs,2 that's about 600 kilobytes of data transfer before any useful commit exchanges can occur.

In general, it's not a good plan to create thousands or millions of refs.  There's no theoretical reason not to do it but for protocol and performance reasons, a soft cap of under a thousand refs might be advisable.

1In:

commit c7a62075917b3340f908093f63f1161c44ed1475 (HEAD -> master, origin/master, origin/HEAD)

the HEAD, master, origin master, and origin/HEAD are decorations found by searching all refs; the HEAD -> formatting indicates that HEAD is attached, in this case to master).

2Note that annotated tags get doubled here, as they list both the tag name and hash ID, and the tag name suffixed with ^{} and tag's target.  refs/tags/v1.2.3 09e393d913072d7765b02aba1210d843a83cfbae is 57 characters even without a newline or other separator.


问:
How can I get Flash to share the browser cookies/session?
I'm building a PHP-based web app and am integrating a Flash-based charting engine.  The Flash chart needs to make a AJAX request for its data.  This request fails because it is seen as a new user agent and doesn't contain the PHP session cookie to identify it.  So, it gets redirected to the login page.

I've read a few hacks to make this work, including supplying the session ID on the querystring, but that opens up security holes.  How can I get Flash and PHP to share cookie-based session state automatically and stay secure?

答: Use ExternalInterface to talk to the Flex chart. Some browser related information can be passed around via the LoaderContext and BrowserManager classes as well. Dig in a bit into the AS3 documentation.

OwnerDisplayName: spoulson

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: dirkgently


问:
What is best way to create elements and append them to the dom in jquery?
Let's say I am adding li elements in javascript code with jQuery.

Example 1:

```<code>for(var i=0 i<=5; i++){

    var li = $("<li/>");
    li.html("teest "+i);
    $("#ulid").append(li);

}
</code>```

I've learned that the above example is a bad practice due to the fact that the loop rebuilds dom each time it hits append(li).

If that is the case, what is the best way to do the exact same thing as the above example?

答:
The jQuery .append method accepts arrays of elements, so you can do this:</p>

```<code>var elems = [];
for(var i=0; i<=5; i++){
    var li = $("<li/>");
    li.html("teest "+i);
    elems.push(li[0]); // Note we're pushing the element, rather than the jQuery object
}
$("#ulid").append(elems);
</code>```

Body:
Let's say I am adding li elements in javascript code with jQuery.

Example 1:

for(var i=0 i<=5; i++){

    var li = $("
");
    li.html("teest "+i);
    $("#ulid").append(li);

}

I've learned that the above example is a bad practice due to the fact that the loop rebuilds dom each time it hits append(li).

If that is the case, what is the best way to do the exact same thing as the above example?

Body:
The jQuery .append method accepts arrays of elements, so you can do this:

var elems = [];
for(var i=0; i<=5; i++){
    var li = $("<li/>");
    li.html("teest "+i);
    elems.push(li[0]); // Note we're pushing the element, rather than the jQuery object
}
$("#ulid").append(elems);


问:
How to make queryset in django?
```<code>item_list = Item.objects. filter(location_id=location_id)

image_list = Image.objects.filter(?????)

class Image(models.Model):
    item = models.ForeignKey(Item, models.on_delete=CASCADE)
</code>```

I want to get only those images which item_id in the first queryset item_list

答:
You can make use of the __in lookup [Django-doc]:

```<code>image_list = Image.objects.filter(<b>item__in=item_list</b>)</code>```

for some databases, like MySQL that are sometimes not good in optimizing subqueries that have are not dynamic, it might be better to first materialize the list of Items, and then thus pass a list of ids in Django:

```<code>image_list = Image.objects.filter(item__in=<b>list(</b>item_list<b>)</b>)</code>```

This is specified in the documentation as:

Be cautious about using nested queries and understand your database server’s performance characteristics (if in doubt, benchmark!). Some database backends, most notably MySQL, don’t optimize nested queries very well. It is more efficient, in those cases, to extract a list of values and then pass that into the second query.

Title: How to make queryset in django?

Body:
item_list = Item.objects. filter(location_id=location_id)

image_list = Image.objects.filter(?????)

class Image(models.Model):
    item = models.ForeignKey(Item, models.on_delete=CASCADE)

I want to get only those images which item_id in the first queryset item_list

Body:
You can make use of the __in lookup [Django-doc]:

image_list = Image.objects.filter(item__in=item_list)

for some databases, like MySQL that are sometimes not good in optimizing subqueries that have are not dynamic, it might be better to first materialize the list of Items, and then thus pass a list of ids in Django:

image_list = Image.objects.filter(item__in=list(item_list))

This is specified in the documentation as:

Be cautious about using nested queries and understand your database server’s performance characteristics (if in doubt, benchmark!). Some database backends, most notably MySQL, don’t optimize nested queries very well. It is more efficient, in those cases, to extract a list of values and then pass that into the second query.


问:
Nuxt: how do I access axios within the fetch() method?
I'm using nuxt and am looking for a way to access the axios object from within the nuxt fetch() method. Unfortunately I can't seem to access it. This is what I've tried...

```<code>    async fetch({store, params}) {
        // const result = await axios.$get('/api/v2/inventory/3906?apiKey=xxx');
        // const result = await this.axios.$get('/api/v2/inventory/3906?apiKey=xxx');
        // const result = await $axios.$get('/api/v2/inventory/3906?apiKey=xxx');
        store.commit('property/setProperty', result);
    }
</code>```

this is (obviously) not available and $axios and axios are undefined.

I do have @nuxtjs/axios defined in my nuxt.config.js

```<code>modules: [
    'nuxt-buefy',
    '@nuxtjs/style-resources',
    '@nuxtjs/device',
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
],
</code>```

答:
@balexandre should actually get the credit for this. Thanks for the help.

This is an incredibly stupid question I asked, but I'm going to post the answer here in case anyone else has the same experience brain-fart.

```<code>import axios from 'axios' // don't forget me!

... later...

fetch() {
  async fetch({store, params}) {
    const result = await axios.get('/api/v2/inventory/3906?apiKey=xxx');
    store.commit('property/setProperty', result);
  }
}
</code>```

Body:
I'm using nuxt and am looking for a way to access the axios object from within the nuxt fetch() method. Unfortunately I can't seem to access it. This is what I've tried...

    async fetch({store, params}) {
        // const result = await axios.$get('/api/v2/inventory/3906?apiKey=xxx');
        // const result = await this.axios.$get('/api/v2/inventory/3906?apiKey=xxx');
        // const result = await $axios.$get('/api/v2/inventory/3906?apiKey=xxx');
        store.commit('property/setProperty', result);
    }

this is (obviously) not available and $axios and axios are undefined.

I do have @nuxtjs/axios defined in my nuxt.config.js

modules: [
    'nuxt-buefy',
    '@nuxtjs/style-resources',
    '@nuxtjs/device',
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
],

Body:
@balexandre should actually get the credit for this. Thanks for the help.

This is an incredibly stupid question I asked, but I'm going to post the answer here in case anyone else has the same experience brain-fart.

import axios from 'axios' // don't forget me!

... later...

fetch() {
  async fetch({store, params}) {
    const result = await axios.get('/api/v2/inventory/3906?apiKey=xxx');
    store.commit('property/setProperty', result);
  }
}


问:
integrating a web server into a python script
I have written a program to generate sequences that pass certain filters (the exact sequences etc don't matter).  Each sequence is generated by making a random string of 40 characters made up of C, G, T or A. When each string is generated, it is put through a set of filters, and if it passes the filters it is saved to a list.

I am trying to make one of those filters include an online tool, BPROM, which doesn't appear to have a python library implementation.  This means I will need to get my python script to send the sequence string described above to the online tool, and save the output as a python variable.

My question is, if I have a url to the tool (http://www.softberry.com/berry.phtml?topic=bprom&group=programs&subgroup=gfindb), how can I interface my script that generates the sequences, with the online tool - is there a way to send data to the web tool and save the tool's output as a variable?  I've been looking into requests but i'm not sure it is the right way to approach this (as a massive python/coding noob).

Thanks for reading, I'm a bit brain dead so I hope this made sense :P

答:
Of course, you can use requests or urllib
Here is demo code:

with urllib.request.urlopen('http://www.softberry.com/berry.phtml?topic=bprom&group=programs&subgroup=gfindb') as response:
   html = response.read()
```


问:
Fatal Error when clicking on save detail: You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop(…)
I want to click on save detail and not receive this error:

You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop(…)

This is my code:

```<code>      render(){

const{detailItem,index,fields,handleSubmit,isSubtotal,loading} = this.props;

if (loading) {
  return <span>Loading...</span>;
}

return(

  <dd key={index}>
  <br></br>
    <button className= 'btn btn-light mr-2'
      type="button"
      title="Remove detail"
      onClick={() => { fields.remove(index)
        if(fields.length == 0 || fields.length === undefined){

        }
        try{
        for(let x in fields){
          fields.remove(index)
          let d = fields.selectedIndex;
          if(fields.remove(index) && d >= 1 && d< fields.length ){
          fields.removeAll(index);
          }
        }
      }catch{console.info("deletes non numerical index")}

        }}> Delete </button>

            <h4>DetailRegister #{index + 1}</h4>

                  <form onSubmit={ handleSubmit }>

                  <Field
                   id={`${detailItem}._id`}
                   name={`${detailItem}.quantity`}
                   component= {NumberPickerInteger}
                   placeholder= '...quantity'
                   label = "Quantity"
                      />
                    <br></br>
                 <h3><b>Product</b></h3>
                   <Field
                    id={`${detailItem}._id`}
                    name={`${detailItem}.product.code`}
                    type="number"
                    component= {RenderFieldNumeric}
                    placeholder='...product code'
                    label = "product's code"
                    />
                    <Field
                     id={`${detailItem}._id`}
                     name={`${detailItem}.product.name`}
                     type="text"
                     component= {RenderField}
                     placeholder='...product's name'
                     label = "product's name"
                      />
                    <Field
                      id={`${detailItem}._id`}
                      name={`${detailItem}.product.price`}
                      component= {NumberPickerr}
                      placeholder= '...Price'
                      label = "product's price"
                      />
                    <br></br>
                     <h3><b>Subtotal</b></h3>
                      <Field
                       id={`${detailItem}._id`}
                       name={`${detailItem}.subtotal`}
                       component= {SubtotalWidget}
                       placeholder= '...subtotal'
                       label = "Subtotal"
                       // value={this.state.subtotal}
                       // onChange={(event) => this.props.onChange(event.target.value)}
                          >
                         {haySubtotal}
                         </Field>

                          <button className= 'btn btn-primary' type='submit'>

                           Save Detail  </button>

                           </form>

                            </dd>
                          );

                        }

                       }
</code>```

How can I solve this issue in code?, I want to clicking in a button called Save detail. When I'm clicking on this one, this will be save the object in store of redux.

答:
Let's assume your component code is inside a component called DetailForm. First, you need to make sure you are returning it like this:

```<code>export default reduxForm({
  form: 'detailForm',
  })(DetailForm);
</code>```

and where you use the form you should pass onSubmit prop like below:

```<code>  <DetailForm onSubmit={functionWhichHandlesValues} />
</code>```

Please note that you should not pass handleSubmit prop, you should pass onSubmit prop instead.

Body:
I want to click on save detail and not receive this error:

You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop(…)

This is my code:

      render(){

const{detailItem,index,fields,handleSubmit,isSubtotal,loading} = this.props;

if (loading) {
  return Loading...;
}

return(

    <button className= 'btn btn-light mr-2'
      type="button"
      title="Remove detail"
      onClick={() => { fields.remove(index)
        if(fields.length == 0 || fields.length === undefined){

        }
        try{
        for(let x in fields){
          fields.remove(index)
          let d = fields.selectedIndex;
          if(fields.remove(index) && d >= 1 && d< fields.length ){
          fields.removeAll(index);
          }
        }
      }catch{console.info("deletes non numerical index")}

        }}> Delete </button>

DetailRegister #{index + 1}

                  <form onSubmit={ handleSubmit }>

                  <Field
                   id={`${detailItem}._id`}
                   name={`${detailItem}.quantity`}
                   component= {NumberPickerInteger}
                   placeholder= '...quantity'
                   label = "Quantity"
                      />

Product

                   <Field
                    id={`${detailItem}._id`}
                    name={`${detailItem}.product.code`}
                    type="number"
                    component= {RenderFieldNumeric}
                    placeholder='...product code'
                    label = "product's code"
                    />
                    <Field
                     id={`${detailItem}._id`}
                     name={`${detailItem}.product.name`}
                     type="text"
                     component= {RenderField}
                     placeholder='...product's name'
                     label = "product's name"
                      />
                    <Field
                      id={`${detailItem}._id`}
                      name={`${detailItem}.product.price`}
                      component= {NumberPickerr}
                      placeholder= '...Price'
                      label = "product's price"
                      />

Subtotal

                      <Field
                       id={`${detailItem}._id`}
                       name={`${detailItem}.subtotal`}
                       component= {SubtotalWidget}
                       placeholder= '...subtotal'
                       label = "Subtotal"
                       // value={this.state.subtotal}
                       // onChange={(event) => this.props.onChange(event.target.value)}
                          >
                         {haySubtotal}
                         </Field>

                          <button className= 'btn btn-primary' type='submit'>

                           Save Detail  </button>

                           </form>

                          );

                        }

                       }

How can I solve this issue in code?, I want to clicking in a button called Save detail. When I'm clicking on this one, this will be save the object in store of redux.

Body:
Let's assume your component code is inside a component called DetailForm. First, you need to make sure you are returning it like this:

export default reduxForm({
  form: 'detailForm',
  })(DetailForm);

and where you use the form you should pass onSubmit prop like below:

  <DetailForm onSubmit={functionWhichHandlesValues} />

Please note that you should not pass handleSubmit prop, you should pass onSubmit prop instead.


问:
How to let JVM know about custom marker interface in java
Is that possible to write our own marker interface in java. I am writing a code like

```<code>public interface MyMarker {

}
</code>```

Is that a marker interface?

If it is possible then how can I let JVM know that this interface is my own created marker interface?

答:
"Generally " Marker Interfaces are used to signal compile or JVM, of the additional metadata that might be needed while dealing with the object of "marker type".

For example,
    if a class uses java.io.Serializable interface, the compile actually generates the implementation code for that marker interface for the class which is needed at run time by JVM while storing/marshaling that object.

So I don't see any practical utility of custom marker interface (as it wont mean anything for compiler/JVM which works on a finite set of marker interfaces in java)

Body:
Is that possible to write our own marker interface in java. I am writing a code like

public interface MyMarker {

}

Is that a marker interface?

If it is possible then how can I let JVM know that this interface is my own created marker interface?


问:
There are 100 promises in an array and we need to process 5 at a time in JS. how to achieve this?
There are 100 promises in an array and we need to process 5 at a time in JS. how to achieve this?
(Asked in Microsoft interview)</p>

答:
I would use a function to execute promises in sequence instead of parallel. Once done, create an array of groups of 5 to solve in parallel using Promise.all:

const PROMISES_AMOUNT = 100
const GROUP_AMOUNT = 5

 // Function to divide the array in various chuncks of similar size
 function chunkArray(myArray, chunk_size){
    let index = 0;
    let arrayLength = myArray.length;
    let tempArray = [];

    for (index = 0; index < arrayLength; index += chunk_size) {
        myChunk = myArray.slice(index, index+chunk_size);
        // Do something if you want with the group
        tempArray.push(myChunk);
    }

    return tempArray;
}

 // the promise we will use
 function interval(index) {
    return new Promise(function(resolve, reject) {
        const time = index*100
        setTimeout(function() {
          console.log(`Waited ${time}!`)
            resolve(index);
        }, time)
  })
};

// Our array of 100 promises
const promises = new Array(PROMISES_AMOUNT).fill(null).map((_, index) => interval(index ))

// The array of 100 promises divided by groups of 5 elements
const groupedPromises = chunkArray(promises, GROUP_AMOUNT).map((promisesGroup) => () => Promise.all(promisesGroup))

// A function to divide an array
function chunkArray(myArray, chunk_size){
    var index = 0;
    var arrayLength = myArray.length;
    var tempArray = [];

    for (index = 0; index < arrayLength; index += chunk_size) {
        myChunk = myArray.slice(index, index+chunk_size);
        // Do something if you want with the group
        tempArray.push(myChunk);
    }

    return tempArray;
}

// A function to execute promises in sequence
const promisesInSequence = (arrayOfTasks) => {
  let results = []
  return new Promise((resolve, reject) => {
    const resolveNext = (arrayOfTasks) => {
      // If all tasks are already resolved, return the final array of results
      if (arrayOfTasks.length === 0) return resolve(results)

      // Extract first promise and solve it
      const first = arrayOfTasks.shift()

      first().then((res) => {
        console.log('Solved a group in parallel: ', res)
        results.push(res)
        resolveNext(arrayOfTasks)
      }).catch((err) => {
        reject(err)
      })
    }
    resolveNext(arrayOfTasks)
  })
}

promisesInSequence(groupedPromises)
 .then((result) => console.log(result))```


问:
Drop observations once condition is met by multiple variables
I have the following data and used one of the existing answered questions to solve my data problem but could not get what I want. Here is what I have in my data

Amt1 is populated when the Evt_type is Fee

Amt2 is populated when the Evt_type is REF1/REF2

I don't want to display any observations after the last Flag='Y'

If there is no Flag='Y' then I want all the observations for that id (e.g. id=102)

I want to display if the next row for that id is a Fee followed by REF1/REF2 after flag='Y' (e.g. id=101) However I don't want if there is no REF1/REF2 (e.g.id=103)

Have:

```<code>       id   Date        Evt_Type   Flag   Amt1   Amt2
      101  2/2/2019      Fee              5
      101  2/3/2019      REF1      Y             5
      101  2/4/2019      Fee              10
      101  2/6/2019      REF2      Y             10
      101  2/7/2019      Fee               4
      101  2/8/2019      REF1
      102  2/2/2019      Fee              25
      102  2/2/2019      REF1      N      25
      103  2/3/2019      Fee              10
      103  2/4/2019      REF1      Y             10
      103  2/5/2019      Fee              10
</code>```

Want:

```<code>      id   Date        Evt_Type   Flag   Amt1   Amt2
     101  2/2/2019      Fee              5
     101  2/3/2019      REF1      Y             5
     101  2/4/2019      Fee              10
     101  2/6/2019      REF2      Y             10
     101  2/7/2019      Fee               4
     101  2/8/2019      REF1
     102  2/2/2019      Fee              25
     102  2/2/2019      REF1      N      25
     103  2/4/2019      REF1      Y             10
     103  2/5/2019      Fee              10
</code>```

I tried the following

```<code>data want;
    set have;
    by id Date;
    drop count;

    if (first.id or first.date) and FLAG='Y' then
        do;
            retain count;
            count=1;
            output;
            return;
        end;

    if count=1 and ((first.id or first.date) and Flag ne 'Y') then
        do;
            retain count;
            delete;
            return;
        end;
    output;
run;
</code>```

Any help is appreciated.

Thanks

答:
A technique known as DOW loop can perform a computation that measures a group in some way and then, in a second loop, apply that computation to members of the group.

The DOW relies on a SET statement inside the loop.  In this case the computation is 'what row in the group is the last one having flag="Y".

```<code>data want;
  * DOW loop, contains computation;

  _max_n_with_Y = 1e12;

  do _n_ = 1 by 1 until (last.id);
    set have;
    by id;
    if flag='Y' then _max_n_with_Y = _n_;
  end;

  * Follow up loop, applies computation;
  do _n_ = 1 to _n_;
    set have;
    if _n_ <= _max_n_with_Y then OUTPUT;
  end;
  drop _:;
run;
</code>```

Body:
I have the following data and used one of the existing answered questions to solve my data problem but could not get what I want. Here is what I have in my data

Amt1 is populated when the Evt_type is Fee

Amt2 is populated when the Evt_type is REF1/REF2

I don't want to display any observations after the last Flag='Y'

If there is no Flag='Y' then I want all the observations for that id (e.g. id=102)

I want to display if the next row for that id is a Fee followed by REF1/REF2 after flag='Y' (e.g. id=101) However I don't want if there is no REF1/REF2 (e.g.id=103)

Have:

       id   Date        Evt_Type   Flag   Amt1   Amt2
      101  2/2/2019      Fee              5
      101  2/3/2019      REF1      Y             5
      101  2/4/2019      Fee              10
      101  2/6/2019      REF2      Y             10
      101  2/7/2019      Fee               4
      101  2/8/2019      REF1
      102  2/2/2019      Fee              25
      102  2/2/2019      REF1      N      25
      103  2/3/2019      Fee              10
      103  2/4/2019      REF1      Y             10
      103  2/5/2019      Fee              10

Want:

      id   Date        Evt_Type   Flag   Amt1   Amt2
     101  2/2/2019      Fee              5
     101  2/3/2019      REF1      Y             5
     101  2/4/2019      Fee              10
     101  2/6/2019      REF2      Y             10
     101  2/7/2019      Fee               4
     101  2/8/2019      REF1
     102  2/2/2019      Fee              25
     102  2/2/2019      REF1      N      25
     103  2/4/2019      REF1      Y             10
     103  2/5/2019      Fee              10

I tried the following

data want;
    set have;
    by id Date;
    drop count;

    if (first.id or first.date) and FLAG='Y' then
        do;
            retain count;
            count=1;
            output;
            return;
        end;

    if count=1 and ((first.id or first.date) and Flag ne 'Y') then
        do;
            retain count;
            delete;
            return;
        end;
    output;
run;

Any help is appreciated.

Thanks

Body:
A technique known as DOW loop can perform a computation that measures a group in some way and then, in a second loop, apply that computation to members of the group.

The DOW relies on a SET statement inside the loop.  In this case the computation is 'what row in the group is the last one having flag="Y".

data want;
  * DOW loop, contains computation;

  _max_n_with_Y = 1e12;

  do _n_ = 1 by 1 until (last.id);
    set have;
    by id;
    if flag='Y' then _max_n_with_Y = _n_;
  end;

  * Follow up loop, applies computation;
  do _n_ = 1 to _n_;
    set have;
    if _n_ <= _max_n_with_Y then OUTPUT;
  end;
  drop _:;
run;