问:
Remove one element in array of document MongoDB
I have database in MongoDB like this

```<code>{"_id":{"$oid":"5eb8c55230cb8651e0906d7e"},"rolecode":"DHBK_ROLE_01","functioncode":"DHBK_FUNC_01, DHBK_FUNC_02","productid":"mBaaS_Platform","comid":"DHBK"}
{"_id":{"$oid":"5eb8c5a030cb8651e0906d7f"},"rolecode":"DHBK_ROLE_02","functioncode":"DHBK_FUNC_02, DHBK_FUNC_03","productid":"GIS_Platform","comid":"DHBK"}
{"_id":{"$oid":"5ebe0016b4146803d8ad2559"},"rolecode":"DHKT_ROLE_01","functioncode":"DHKT_FUNC_01, DHKT_FUNC_02","productid":"mBaaS_Platform","comid":"DHKT"}
{"_id":{"$oid":"5ebe003cb4146803d8ad255a"},"rolecode":"DHKT_ROLE_02","functioncode":"DHKT_FUNC_01","productid":"Analysis_Platform","comid":"DHKT"}
{"_id":{"$oid":"5ebe00ffb4146803d8ad255b"},"rolecode":"DHBK_ROLE_03","functioncode":"DHBK_FUNC_01, DHBK_FUNC_02,DHBK_FUNC_03","productid":"IOT_Platform","comid":"DHBK"}
{"_id":{"$oid":"5ecf89f969f07e1cb0ad063d"},"rolecode":"DHBK1_ROLE_01","functioncode":"DHBK1_FUNC_1,DHBK_FUNC_03","productid":"IOT_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ecf8b6169f07e1cb0ad063e"},"rolecode":"DHBK1_ROLE_02","functioncode":"DHBK1_FUNC_1,DHBK_FUNC_02","productid":"SSO_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ecf8b7969f07e1cb0ad063f"},"rolecode":"DHBK1_ROLE_03","functioncode":"","productid":"ABC_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}
</code>```

I have Mongo shell to find all document have DHBK1_FUNC_1 in functioncodelist properties.

Here is my Mongo shell

db.company_role_function.find( { functioncodelist: { $all: ["DHBK1_FUNC_1"] } } )

And this is the result

```<code>{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}
</code>```

Now I want to remove value DHBK1_FUNC_1 in that result. I hope my result after delete action like this

```<code>{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":[""],"comid":"DHBK1"}
</code>```

Thank in advanced

答:
```<code>{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}
</code>```

After getting the above result:

```<code>results.forEach(function(result) {
    let index = result.functioncodelist.indexOf("DHBK1_FUNC_1");
    result.functioncodelist.splice(index, 1);
    result.markModified('functioncodelist');
    result.save();
});
</code>```

Body:
I have database in MongoDB like this

{"_id":{"$oid":"5eb8c55230cb8651e0906d7e"},"rolecode":"DHBK_ROLE_01","functioncode":"DHBK_FUNC_01, DHBK_FUNC_02","productid":"mBaaS_Platform","comid":"DHBK"}
{"_id":{"$oid":"5eb8c5a030cb8651e0906d7f"},"rolecode":"DHBK_ROLE_02","functioncode":"DHBK_FUNC_02, DHBK_FUNC_03","productid":"GIS_Platform","comid":"DHBK"}
{"_id":{"$oid":"5ebe0016b4146803d8ad2559"},"rolecode":"DHKT_ROLE_01","functioncode":"DHKT_FUNC_01, DHKT_FUNC_02","productid":"mBaaS_Platform","comid":"DHKT"}
{"_id":{"$oid":"5ebe003cb4146803d8ad255a"},"rolecode":"DHKT_ROLE_02","functioncode":"DHKT_FUNC_01","productid":"Analysis_Platform","comid":"DHKT"}
{"_id":{"$oid":"5ebe00ffb4146803d8ad255b"},"rolecode":"DHBK_ROLE_03","functioncode":"DHBK_FUNC_01, DHBK_FUNC_02,DHBK_FUNC_03","productid":"IOT_Platform","comid":"DHBK"}
{"_id":{"$oid":"5ecf89f969f07e1cb0ad063d"},"rolecode":"DHBK1_ROLE_01","functioncode":"DHBK1_FUNC_1,DHBK_FUNC_03","productid":"IOT_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ecf8b6169f07e1cb0ad063e"},"rolecode":"DHBK1_ROLE_02","functioncode":"DHBK1_FUNC_1,DHBK_FUNC_02","productid":"SSO_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ecf8b7969f07e1cb0ad063f"},"rolecode":"DHBK1_ROLE_03","functioncode":"","productid":"ABC_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}

I have Mongo shell to find all document have DHBK1_FUNC_1 in functioncodelist properties.

Here is my Mongo shell

db.company_role_function.find( { functioncodelist: { $all: ["DHBK1_FUNC_1"] } } )

And this is the result

{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}

Now I want to remove value DHBK1_FUNC_1 in that result. I hope my result after delete action like this

{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":[""],"comid":"DHBK1"}

Thank in advanced

Body:
{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}

After getting the above result:

results.forEach(function(result) {
    let index = result.functioncodelist.indexOf("DHBK1_FUNC_1");
    result.functioncodelist.splice(index, 1);
    result.markModified('functioncodelist');
    result.save();
});


来源: stackexchange

问:
Stripe - Is there a way to get the revenue of a product for current/specific month?
Right now I am creating multiple products with 3 subscription plans. I am looking for a way how to get the monthly revenue for a product.

example:
Product 1  has 1 new (5$) subscription and 2 current subscription for this month. I want to get a total revenue of 15$ for this month for product 1.

I was reading the documentation and I can't seem to find anything about this.

答:
Subscriptions generate Invoices that create Charges, you could list the Charges:

```<code>await stripe.charges.list(
  {limit: 3}
);
</code>```

Hope that helps!

[1] https://stripe.com/docs/api/charges/list

ContentLicense: CC BY-SA 4.0

Body:
Subscriptions generate Invoices that create Charges, you could list the Charges:

await stripe.charges.list(
  {limit: 3}
);

Hope that helps!

[1] https://stripe.com/docs/api/charges/list


问:
can't use Terminal in VS Code with Python
I have installed VS Code, Python, and Python extension.

i'm following the Microsoft instructions, but for some reason i cant do -
Python filename.py

in the terminal, the path is correct.

it doesn't run the file

and when  i do run it add the " & " in the beginning.

now i want to create a virtual folder and there is no respond from the terminal.

where did i go wrong?
the installation process? does it matter if i'm administrator?
thanks you for your help.enter image description here

答:
my mistake was in the installation process.
before installing it ask you "add python to PATH" - check that box!

in this video, at 3:13
https://www.youtube.com/watch?v=bnhQBUEpWlg


问:
System.FormatException: 'Failed to convert parameter value from a String to a Boolean.'
This code keeps bringing up a:

Failed to convert parameter value from a String to a Boolean.

```<code>    public void BindToData()
    {
        try
        {
            DataSet ds = new DataSet();
            string connString = @"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
            string strproc = "TestReport";
            using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
            {
                SqlCommand cmd = new SqlCommand();
                sda.SelectCommand.CommandType = CommandType.StoredProcedure;

                sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = StatusId.SelectedValue;
                sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = orgUnitId.SelectedValue;
                sda.Fill(ds);

                XtraReport report = new XtraReport();
                report.DataSource = ds;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
</code>```

Stored Procedure

```<code>ALTER PROCEDURE [dbo].[TestReport]
(
    @Status bit,
    @OrgJed int
)
AS
BEGIN
    SELECT TOP 1 OrgUnitID
    FROM    tblZaposleni_AD
    WHERE  Status =    @Status AND
        OrgUnitID = @OrgJed
END
</code>```

I have looked everywhere and there have been suggestions to do converts, but I simply can't find what exactly I should have to convert in this code.
The problem is here, and I try everything but doesn't work.

```<code>sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = StatusId.SelectedValue;
sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = orgUnitId.SelectedValue;
</code>```

Note: StatusId is DropDownMenu which has 2 options, "0" or "1".  OrgJed is DropDownMenu which has values from "1" to "10"

答:
You need to convert the strings in your DropDownLists to a bool and an int respectively for use in your parameters e.g.

```<code>sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = StatusId.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = Int32.Parse(orgUnitId.SelectedValue);
</code>```

Note: For robust code you should really use Int32.TryParse() but I will leave that as an exercise for you.

Body:
This code keeps bringing up a:

Failed to convert parameter value from a String to a Boolean.

    public void BindToData()
    {
        try
        {
            DataSet ds = new DataSet();
            string connString = @"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
            string strproc = "TestReport";
            using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
            {
                SqlCommand cmd = new SqlCommand();
                sda.SelectCommand.CommandType = CommandType.StoredProcedure;

                sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = StatusId.SelectedValue;
                sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = orgUnitId.SelectedValue;
                sda.Fill(ds);

                XtraReport report = new XtraReport();
                report.DataSource = ds;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

Stored Procedure

ALTER PROCEDURE [dbo].[TestReport]
(
    @Status bit,
    @OrgJed int
)
AS
BEGIN
    SELECT TOP 1 OrgUnitID
    FROM    tblZaposleni_AD
    WHERE  Status =    @Status AND
        OrgUnitID = @OrgJed
END

I have looked everywhere and there have been suggestions to do converts, but I simply can't find what exactly I should have to convert in this code.
The problem is here, and I try everything but doesn't work.

sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = StatusId.SelectedValue;
sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = orgUnitId.SelectedValue;

Note: StatusId is DropDownMenu which has 2 options, "0" or "1".  OrgJed is DropDownMenu which has values from "1" to "10"

Body:
You need to convert the strings in your DropDownLists to a bool and an int respectively for use in your parameters e.g.

sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = StatusId.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = Int32.Parse(orgUnitId.SelectedValue);

Note: For robust code you should really use Int32.TryParse() but I will leave that as an exercise for you.


问:
Return a value inside a function after getting value from firebase storage closure Swift
I have a function which downloads data from firebase:

```<code>func downloadData(path: String) -> Data? {
    let data: Data?

    let storage = Storage.storage()
    storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in

    if let error = error {
        print("\(error)")
    } else {
        data = result
        print("finished")
    }

    return data // <-- this is called before closue ends
}
</code>```

but it is not returning the value from storage closure.
I tried using a dispatch group

```<code> func downloadData(path: String) -> Data? {
     ...
     let group = DispatchGroup()
     group.enter()
     storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
         ...
         ...
         group.leave()
     }

    group.notify(queue: .main) {
        return data // <-- build time error! the function doesn't return a value
    }
}
</code>```

so I tried a different approach: instead of group.notify() I used:

```<code>group.wait()
</code>```

but it didn't work also. the whole app was frozen and nothing happened

and I tried another one:

```<code>let semaphore = DispatchSemaphore(value: 0)

storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
    ...
    ...
    semaphore.signal()
}

semaphore.wait()

return data // <-- nothing happens... it is not being executed
</code>```

Any ideas on how to figure this out?

UPDATE

I tried using the completion option but it still didn't wait until it is downloded.

this is my outerFunction:

```<code>    var soundData: Data?
    var imageData: Data?
    downloadData(path: soundPath) { sound in
        soundData = sound

        downloadData(path: imageData) { image in
             imageData = image
        }

    }

    doMoreStuff() // <-- called before completeion blocks executed
</code>```

答:
You should use completion block for data instead of returning the data, here's how:

func downloadData(path: String, completion: @escaping ((Data?) -> Void)?) {
    ...
    let group = DispatchGroup()
    group.enter()
    var data: Data?
    storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
        ...
            ...
                data = dataReceived
                group.leave()
    }

    group.notify(queue: .main) {
        completion?(data)
    }
}
```

Body:
I have a function which downloads data from firebase:

func downloadData(path: String) -> Data? {
    let data: Data?

    let storage = Storage.storage()
    storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in

    if let error = error {
        print("\(error)")
    } else {
        data = result
        print("finished")
    }

    return data // <-- this is called before closue ends
}

but it is not returning the value from storage closure.
I tried using a dispatch group

 func downloadData(path: String) -> Data? {
     ...
     let group = DispatchGroup()
     group.enter()
     storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
         ...
         ...
         group.leave()
     }

    group.notify(queue: .main) {
        return data // <-- build time error! the function doesn't return a value
    }
}

so I tried a different approach: instead of group.notify() I used:

group.wait()

but it didn't work also. the whole app was frozen and nothing happened

and I tried another one:

let semaphore = DispatchSemaphore(value: 0)

storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
    ...
    ...
    semaphore.signal()
}

semaphore.wait()

return data // <-- nothing happens... it is not being executed

Any ideas on how to figure this out?

UPDATE

I tried using the completion option but it still didn't wait until it is downloded.

this is my outerFunction:

    var soundData: Data?
    var imageData: Data?
    downloadData(path: soundPath) { sound in
        soundData = sound

        downloadData(path: imageData) { image in
             imageData = image
        }

    }

    doMoreStuff() // <-- called before completeion blocks executed


问:
Using enums as status returned status indicators in C#
Just wondering what the general consensus was about returning enums from methods indicating the status. The notion of returning codes (ints) is pretty innate in oldschool systems programming (C) but I am wondering if the methodology for indicating the status has changed.

thanks

Edit: I am aware that enums are basically int values. I'm inquiring about the sheer practice of having methods start throwing around status codes (be them enums or ints) to indicate statuses altogether. It seems like a good practice but I was wondering if there is any negative feelings about the idea.

I would always choose an enum over an int return for a status code.

答:
Returning raw integers (for status and things like that) and not even hiding their numeric nature by constants (or if the language does not support real constants, then variables that are treated as constants by convention) is a very bad practice, even in old school languages like C. It is a source of a lot of bugs and endless headaches.

Also, C#-style enumerations provide (some) type safety and make less space for all sorts of errors and bugs. You should definitely use them. So it's really an improvement over returning an integer and then comparing it to an integer constant. If the language provides an usefule feature, why not use it?

OwnerDisplayName: Chance

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chance

OwnerDisplayName: DrJokepu

LastEditorDisplayName: DrJokepu


问:
add java applet to php
I'm trying to add java applet to my php code really I'm trying but still have the same error that the applet and the .jar not found can any one give me hello world example for that issue.</p>

答: See Embedding an Applet in an HTML Page. PHP is not involved.</p>

ContentLicense: CC BY-SA 3.0

Title: add java applet to php


问:
Does there exist an AES 128 or 256 GCM implementation in pure JavaScript or C?
I have been searching around for a pure JS implementation of AES 128 or 256 GCM but haven't found anything on GitHub. If none exist, perhaps there is one in Ruby or C in a minimal way for easy reading. Every language seems to only have a wrapper around OpenSSL to get this AES 128 or 256 GCM implementation, but I would like to see a simplified version for learning. Also, I can't even seem to find the OpenSSL implementation.

Forge doesn't seem to have it.

答:
There is a pure JS implementation of AES GCM On CyberChef.

https://gchq.github.io/CyberChef/#recipe=AES_Encrypt(%7B'option':'Hex','string':''%7D,%7B'option':'Hex','string':''%7D,'GCM','Raw','Hex')

They also support 128 bit.

This under the hood appears to use "node-forge"

https://github.com/digitalbazaar/forge/blob/master/lib/aes.js

And the implementation is right there.


问:
How to control subdirectory compiling order of cmake?
This is my CMakeLists.txt:

```<code>ADD_SUBDIRECTORY(third)
ADD_SUBDIRECTORY(utils)
ADD_SUBDIRECTORY(rpc)
</code>```

But the directory 'rpc' will be compiled before directory 'utils', actually the 'rpc' is depends on 'utils', so I will get a link error.

How can I make the 'rpc' compiling after 'utils'?

Thanks.

答:
I have the same question with you.

I have open source libs —— jthread and jrtplib. I want to build them by a main CmakeList.text so I make a folder like:

cpp
├─jrtplib
│  ├─src
│  └─CMakeFiles.txt
├─jthread
│    ├─src
│    └─CMakeFiles.txt
└─CMakeFiles.txt
```

<p>and cpp/CMakeFiles.txt like:</p>

```
cmake_minimum_required (VERSION 3.8)

set(JTHREAD_ENABLED 1)

# 包含子项目。

add_subdirectory ("jthread")
add_subdirectory ("jrtplib")

```

<p>but build error, it build jrtplib first, I think "jr" > "jt", so build jrtplib first, and it can't find libjthread.so , so <strong>target_link_libraries</strong> error
I find a solution :</p>

```
cmake_minimum_required (VERSION 3.8)

# ↓↓↓↓↓↓↓↓  attention ↓↓↓↓↓↓↓↓

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})

# ↑↑↑↑↑↑↑↑  attention ↑↑↑↑↑↑↑↑

set(JTHREAD_ENABLED 1)
# copy jthread/src/*.h to C:/thirdParty/include/jthread
set(JTHREAD_INCLUDE_DIRS "C:/thirdParty/include")
set(JTHREAD_LIBRARIES "libjthread.so")

# 包含子项目。
add_subdirectory (jthread)
add_subdirectory (jrtplib)

```

set xx_OUTPUT_DIRECTORY can set library build in main cmake_build folder, so jrtplib can find libjthread.so .

build success ...

Body:
This is my CMakeLists.txt:

ADD_SUBDIRECTORY(third)
ADD_SUBDIRECTORY(utils)
ADD_SUBDIRECTORY(rpc)

But the directory 'rpc' will be compiled before directory 'utils', actually the 'rpc' is depends on 'utils', so I will get a link error.

How can I make the 'rpc' compiling after 'utils'?

Thanks.

Body:
I have the same question with you.

I have open source libs —— jthread and jrtplib. I want to build them by a main CmakeList.text so I make a folder like:

cpp
├─jrtplib
│  ├─src
│  └─CMakeFiles.txt
├─jthread
│    ├─src
│    └─CMakeFiles.txt
└─CMakeFiles.txt

and cpp/CMakeFiles.txt like:

cmake_minimum_required (VERSION 3.8)

set(JTHREAD_ENABLED 1)

# 包含子项目。

add_subdirectory ("jthread")
add_subdirectory ("jrtplib")

but build error, it build jrtplib first, I think "jr" > "jt", so build jrtplib first, and it can't find libjthread.so , so target_link_libraries error
I find a solution :

cmake_minimum_required (VERSION 3.8)

# ↓↓↓↓↓↓↓↓  attention ↓↓↓↓↓↓↓↓

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})

# ↑↑↑↑↑↑↑↑  attention ↑↑↑↑↑↑↑↑

set(JTHREAD_ENABLED 1)
# copy jthread/src/*.h to C:/thirdParty/include/jthread
set(JTHREAD_INCLUDE_DIRS "C:/thirdParty/include")
set(JTHREAD_LIBRARIES "libjthread.so")

# 包含子项目。
add_subdirectory (jthread)
add_subdirectory (jrtplib)

set xx_OUTPUT_DIRECTORY can set library build in main cmake_build folder, so jrtplib can find libjthread.so .

build success ...


问:
php mvc – Remove Public from URL
I know this is a very popular question but I haven't been able to find a working solution in my project
I  want to set my document root to the public folder

change url for example from /public/login to /login

.htaccess code

```<code>  RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?$1 [L,QSA]
</code>```

答: Sometimes .htacess code doesnot work due to mod_rewrite. Try once using mod_rewrite enable. Alternately you can move you index.php file from public folder to main folder and update link that are used in index.php file. Another way is to use php artisan serve to run project and use htaccess that you have used.

Title: php mvc – Remove Public from URL

Body:
I know this is a very popular question but I haven't been able to find a working solution in my project
I  want to set my document root to the public folder

change url for example from /public/login to /login

.htaccess code

  RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?$1 [L,QSA]


问:
what is the use of ! sign in some ruby methods

Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

```<code>before_filter :authenticated!
</code>```

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

答: You can name every method you want with an exclamation mark at the end. However, the convention is that you use that syntax when methods are in any way intrusive. So, for example on an object of class Car, the method fast? should return true or false but fast! should perhaps change some instance variable @fast to true. </p>

Body:
Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

before_filter :authenticated!

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera


问:
Mocking ReturnsAsync using Moq to return 2 values
Given a interface:

```<code>Task<Booking> GetBookingAsync(Guid reservationId);
</code>```

I would mock the following like so:

```<code>_bookingLogic.Setup(x => x.GetBookingAsync(It.IsAny<Guid>())).ReturnsAsync(new Booking());
</code>```

Givent the interface now changes to:

```<code>Task<(Booking Booking, IList<GAEvent> GaEvents)> GetBookingAsync(Guid reservationId);
</code>```

How would this be mocked using Moq?

```<code>_bookingLogic.Setup(x => x.GetBookingAsync(It.IsAny<Guid>())).ReturnsAsync(?????);
</code>```

答:
In second case result is a value tuple so you need to create one. Try:</p>
```<code>.ReturnsAsync((new Booking(), (IList<GAEvent>)new List<GAEvent>()))
</code>```

Body:
Given a interface:

Task<Booking> GetBookingAsync(Guid reservationId);

I would mock the following like so:

_bookingLogic.Setup(x => x.GetBookingAsync(It.IsAny<Guid>())).ReturnsAsync(new Booking());

Givent the interface now changes to:

Task<(Booking Booking, IList<GAEvent> GaEvents)> GetBookingAsync(Guid reservationId);

How would this be mocked using Moq?

_bookingLogic.Setup(x => x.GetBookingAsync(It.IsAny<Guid>())).ReturnsAsync(?????);

Body:
In second case result is a value tuple so you need to create one. Try:

.ReturnsAsync((new Booking(), (IList<GAEvent>)new List<GAEvent>()))


问:
Setting form select disabled for a DOM element represented by a variable
I'm trying to make a form element, in this case the non-active options of a select input disabled. I came across this code here as a recommended solution:

```<code>$('#elementid option:not(:selected)').prop('disabled', true);
</code>```

I'm using a variable to represent the object within my loop:

```<code>var sinput = $(this).parents("tr").find('select');
</code>```

My question is - how do I apply the prop code via the representative variable sinput? Can I even do this?

答:
If I understood you correctly, the $(this) needs to be some object in an event

To re-use a var you can do

```<code>var $sinput = $(this).closest("tr").find('select');
$('option:not(:selected)', $sinput).prop('disabled', true);
</code>```

or

```<code>var $sinput = $(this).closest("tr").find('select');
$sinput.find('option:not(:selected)').prop('disabled', true);
</code>```

I would do it directly

$(".dis").on("click", function() {
  $(this).closest("tr")  // the row of the button
    .find('select option:not(:selected)') // all not selected options
    .prop('disabled', true);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><button type="button" class="dis">Disable not selected</button>
      <select>
        <option value="">Please select</option>
        <option value="1">One</option>
        <option value="2" selected>Two</option>
      </select>
    </td>
  </tr>
  <tr>
    <td><button type="button" class="dis">Disable not selected</button>
      <select>
        <option value="">Please select</option>
        <option value="1" selected>One</option>
        <option value="2">Two</option>
      </select>
    </td>
  </tr>
</table></code>```

If you just want to disable all not selected options in a table on page load, it could be

```<code>$(function() {
 $("#tableId")
   .find('select option:not(:selected)')
   .prop('disabled', true);
});
</code>```

Body:
I'm trying to make a form element, in this case the non-active options of a select input disabled. I came across this code here as a recommended solution:

$('#elementid option:not(:selected)').prop('disabled', true);

I'm using a variable to represent the object within my loop:

var sinput = $(this).parents("tr").find('select');

My question is - how do I apply the prop code via the representative variable sinput? Can I even do this?

Body:
If I understood you correctly, the $(this) needs to be some object in an event

To re-use a var you can do

var $sinput = $(this).closest("tr").find('select');
$('option:not(:selected)', $sinput).prop('disabled', true);

or

var $sinput = $(this).closest("tr").find('select');
$sinput.find('option:not(:selected)').prop('disabled', true);

I would do it directly

$(".dis").on("click", function() {
  $(this).closest("tr")  // the row of the button
    .find('select option:not(:selected)') // all not selected options
    .prop('disabled', true);
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><button type="button" class="dis">Disable not selected</button>
      <select>
        <option value="">Please select</option>
        <option value="1">One</option>
        <option value="2" selected>Two</option>
      </select>
    </td>
  </tr>
  <tr>
    <td><button type="button" class="dis">Disable not selected</button>
      <select>
        <option value="">Please select</option>
        <option value="1" selected>One</option>
        <option value="2">Two</option>
      </select>
    </td>
  </tr>
</table>

If you just want to disable all not selected options in a table on page load, it could be

$(function() {
 $("#tableId")
   .find('select option:not(:selected)')
   .prop('disabled', true);
});


问:
NPM shows a 403 when installing public packages
When I am trying to install my deps with NPM it gaves me à 403 status code. I am installing them using docker. Everything was going well till this morning when npm wasn't able to install dependencies anymore. The problem is only on my server. Locally the deps can be installed, no problems. I do not have any proxy on my server.

When I issue this command directly in my server :

```<code>wget https://registry.npmjs.org/
</code>```

I get :

```<code>> wget https://registry.npmjs.org/
--2020-05-29 12:09:35--  https://registry.npmjs.org/
Resolving registry.npmjs.org (registry.npmjs.org)... 2606:4700::6810:1b23, 2606:4700::6810:1523, 2606:4700::6810:1423, ...
Connecting to registry.npmjs.org (registry.npmjs.org)|2606:4700::6810:1b23|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2020-05-29 12:09:35 ERROR 403: Forbidden.
</code>```

I really do not understand what can be wrong in my server? Again, it was working yesterday, nothing changed in the server...

My server is an OVH Kimsufi.

答: Ok, seems to be an OVH problem : https://twitter.com/ovh_status/status/1266310329631465472</p>

Body:
When I am trying to install my deps with NPM it gaves me à 403 status code. I am installing them using docker. Everything was going well till this morning when npm wasn't able to install dependencies anymore. The problem is only on my server. Locally the deps can be installed, no problems. I do not have any proxy on my server.

When I issue this command directly in my server :

wget https://registry.npmjs.org/

I get :

> wget https://registry.npmjs.org/
--2020-05-29 12:09:35--  https://registry.npmjs.org/
Resolving registry.npmjs.org (registry.npmjs.org)... 2606:4700::6810:1b23, 2606:4700::6810:1523, 2606:4700::6810:1423, ...
Connecting to registry.npmjs.org (registry.npmjs.org)|2606:4700::6810:1b23|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2020-05-29 12:09:35 ERROR 403: Forbidden.

I really do not understand what can be wrong in my server? Again, it was working yesterday, nothing changed in the server...

My server is an OVH Kimsufi.


问:
Ag-grid filter menu automatically resizing
Looking how to make the filter menu of ag-grid automatically resizing (depending of contents).

Here there's an exemple
with tooltips for the columns B and C.

In Column A i would make a larger menu without fixing the width (then i can apply the code in other columns).

Maybe by changing the css classes ag-filter-virtual-list-container and ag-filter-virtual-list-item

答: Use Material UI popover component. It'll automatically resizes.Material UI PopOver</p>


问:
How to empty collection in mongodb using mongoose
In my code i am inserting a collection dynamically and this collation have default

```<code>_id:ObjectId("5ed0d4d3fec27620043ee59d")
__v:0
</code>```

I think this is default inserted in mongodb.Actully i no need like this si i am trying to remove these two _id and __:0 but not working.

Below my code:

```<code>   var NewModel = require(path.resolve('./models/newmodelschema.model.js'))(collectionName);
   NewModel.create({}, function(err, doc) {
                NewModel.remove({_id:'',__v:0}, function(err) {
                    if (!err) {
                        console.log(err);
                        return;
                    } else {
                        console.log("Model empty");
                    }
                });
            });
</code>```

答:
You can disable _id and _v by using options { _id: false, versionKey: false }, while creating schema.

Example:

create schema like below

```<code>    const NewModel = new mongoose.Schema({
      "name": { type: string}
    }, { _id: false, versionKey: false });
</code>```

Now insert a data,

```<code>NewModel.create({ "name": "foo"}, function(err, doc){
console.log("data ", doc);
});
</code>```

It should print,

```<code>data { "name": "foo" }
</code>```

without _id and __v

Edit 2:
You can't remove _id unless it's a subdocument

PS: I would recommend to keep this both, to know about these fields please read https://docs.mongodb.com/manual/core/document/#the-id-field and https://mongoosejs.com/docs/guide.html#versionKey

Body:
In my code i am inserting a collection dynamically and this collation have default

_id:ObjectId("5ed0d4d3fec27620043ee59d")
__v:0

I think this is default inserted in mongodb.Actully i no need like this si i am trying to remove these two _id and __:0 but not working.

Below my code:

   var NewModel = require(path.resolve('./models/newmodelschema.model.js'))(collectionName);
   NewModel.create({}, function(err, doc) {
                NewModel.remove({_id:'',__v:0}, function(err) {
                    if (!err) {
                        console.log(err);
                        return;
                    } else {
                        console.log("Model empty");
                    }
                });
            });

Body:
You can disable _id and _v by using options { _id: false, versionKey: false }, while creating schema.

Example:

create schema like below

    const NewModel = new mongoose.Schema({
      "name": { type: string}
    }, { _id: false, versionKey: false });

Now insert a data,

NewModel.create({ "name": "foo"}, function(err, doc){
console.log("data ", doc);
});

It should print,

data { "name": "foo" }

without _id and __v

Edit 2:
You can't remove _id unless it's a subdocument

PS: I would recommend to keep this both, to know about these fields please read https://docs.mongodb.com/manual/core/document/#the-id-field and https://mongoosejs.com/docs/guide.html#versionKey


问:
Gatsby add dynamic page on client side
I'm using a Gatsby setup hosted on Netlify.

I'm building some sort of recipe website where users can register, login and add recipes to their own cookbook page. To add a new recipe a user can fill in a form with some data (like recipe name, ingredients etc.). On submit the data will be stored inside a database. I then also want a dynamic page to be created for that specific recipe. (This is where you come in).

I know I can add pages via the gatsby-node.js file but I would prefer if this page can be added on the client side and exists instantly after the form submit without rebuilding the project. Is this possible in Gatsby and if so... how?

If this is not possible my best option would be calling the Netlify webhook to rebuild the project after the form submit and simply wait for the build to be completed before I can show the recipe detail page? Any thoughts on this?

Hope one of you coders can help me out here!

答:
Okay so I figured out there isn't a way in Gatsby to create the page directly in the client side. I decided to go with Albert's idea of first showing a dynamic page including a message saying this is a temporary page and the real recipe is "being cooked up".

On form submit I also just simply call the webhook to trigger Netlify deploy. This triggers a new deploy and in the gatsby-node.js I will create the new page based on the data I saved in my database on the form submit.

Title: Gatsby add dynamic page on client side


问:
Unable to locate element error while using find_element_by_css_selector in python
I am learning Selenium using Python. I have tried to check the button status - whether enabled or not? For that I have used mercury demo site and wrote the below code. I am getting

Unable to locate element: input[value=roundtrip]

Code which I have used:

```<code>from  selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Firefox(executable_path="C:\\Seleinum_Python\\WedDriver\\geckodriver.exe")
driver.get("http://newtours.demoaut.com/")
# Whether the user name & password enabled and displayed
user_ele = driver.find_element_by_name("userName")   # <input type="text" name="userName" size="10">
print(user_ele.is_displayed()) # Return True /False based on element status
print(user_ele.is_enabled())
pwd_ele = driver.find_element_by_name("password")   #<input type="password" name="password" size="10">
print(pwd_ele.is_displayed())
print(pwd_ele.is_enabled())
user_ele.send_keys("mercury")
pwd_ele.send_keys("mercury")
driver.find_element_by_name("login").click()
roundtrip_radio= driver.find_element_by_css_selector("input[value=roundtrip]") #<input type="radio" name="tripType" value="roundtrip" checked="">
print(roundtrip_radio.is_selected())
oneway_radio= driver.find_element_by_css_selector("input[value=oneway]")
print(oneway_radio.is_selected())
driver.close()
</code>```

I even tried with below combination but still I am getting the same element not found issue.

```<code> roundtrip_radio= driver.find_element_by_css_selector("input[value='roundtrip']")
 roundtrip_radio= driver.find_element_by_css_selector('input[value="roundtrip"]')
 roundtrip_radio= driver.find_element_by_css_selector("//input[value='roundtrip']")
 roundtrip_radio= driver.find_element_by_css_selector("input[value='roundtrip']")
 roundtrip_radio= driver.find_element_by_css_selector('input[name="tripType"][value="roundtrip"]')
</code>```

答:
In your css selector you can use :checked to identify selected elements.

for example :-

"input[type=radio]:checked"

Body:
I am learning Selenium using Python. I have tried to check the button status - whether enabled or not? For that I have used mercury demo site and wrote the below code. I am getting

Unable to locate element: input[value=roundtrip]

Code which I have used:

from  selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Firefox(executable_path="C:\\Seleinum_Python\\WedDriver\\geckodriver.exe")
driver.get("http://newtours.demoaut.com/")
# Whether the user name & password enabled and displayed
user_ele = driver.find_element_by_name("userName")   # <input type="text" name="userName" size="10">
print(user_ele.is_displayed()) # Return True /False based on element status
print(user_ele.is_enabled())
pwd_ele = driver.find_element_by_name("password")   #<input type="password" name="password" size="10">
print(pwd_ele.is_displayed())
print(pwd_ele.is_enabled())
user_ele.send_keys("mercury")
pwd_ele.send_keys("mercury")
driver.find_element_by_name("login").click()
roundtrip_radio= driver.find_element_by_css_selector("input[value=roundtrip]") #<input type="radio" name="tripType" value="roundtrip" checked="">
print(roundtrip_radio.is_selected())
oneway_radio= driver.find_element_by_css_selector("input[value=oneway]")
print(oneway_radio.is_selected())
driver.close()

I even tried with below combination but still I am getting the same element not found issue.

 roundtrip_radio= driver.find_element_by_css_selector("input[value='roundtrip']")
 roundtrip_radio= driver.find_element_by_css_selector('input[value="roundtrip"]')
 roundtrip_radio= driver.find_element_by_css_selector("//input[value='roundtrip']")
 roundtrip_radio= driver.find_element_by_css_selector("input[value='roundtrip']")
 roundtrip_radio= driver.find_element_by_css_selector('input[name="tripType"][value="roundtrip"]')


问:
Minio / Keycloak integration: connection refused
I am trying to connect MinIO with KeyCloak and I follow the instructions provided in this documentation:
https://github.com/minio/minio/blob/master/docs/sts/keycloak.md

What I have done so far is deploy a Docker container for the MinIO server, another one for the MinioClient and a third one used for the KeyCloak server.

As you can see in the following snippet the configuration of the Minio Client container is done correctly, since I can list the buckets available in the Minio Server:

mc ls myminio
[2020-05-14 11:54:59 UTC]      0B bucket1/
[2020-05-06 12:23:01 UTC]      0B bucket2/
```

<hr>

<p>I have an issue arising when I try to configure MinIO as depicted in <strong>step 3 (Configure MinIO)</strong> of the documentation. In more detail, the command that I run is this one:</p>

```mc admin config set myminio identity_openid config_url="http://localhost:8080/auth/realms/demo/.well-known/openid-configuration" client_id="account"
```

<p>And the error I get is this one: </p>

```mc: <ERROR> Cannot set 'identity_openid config_url=http://localhost:8080/auth/realms/demo/.well-known/openid-configuration client_id=account' to server. Get http://localhost:8080/auth/realms/demo/.well-known/openid-configuration: dial tcp 127.0.0.1:8080: connect: connection refused.
```

When I curl this address http://localhost:8080/auth/realms/demo/.well-known/openid-configuration from the MinIO Client container though,  I retrieve the JSON file.

答:
Connection refused occurs when a port is not accessible on the hostname or IP we specified.
Please try exposing the port using --expose flag along with the port number which you wish to expose when using the docker CLI. Then being exposed, you can access on it on localhost

Body:
I am trying to connect MinIO with KeyCloak and I follow the instructions provided in this documentation:
https://github.com/minio/minio/blob/master/docs/sts/keycloak.md

What I have done so far is deploy a Docker container for the MinIO server, another one for the MinioClient and a third one used for the KeyCloak server.

As you can see in the following snippet the configuration of the Minio Client container is done correctly, since I can list the buckets available in the Minio Server:

mc ls myminio
[2020-05-14 11:54:59 UTC]      0B bucket1/
[2020-05-06 12:23:01 UTC]      0B bucket2/

I have an issue arising when I try to configure MinIO as depicted in step 3 (Configure MinIO) of the documentation. In more detail, the command that I run is this one:

mc admin config set myminio identity_openid config_url="http://localhost:8080/auth/realms/demo/.well-known/openid-configuration" client_id="account"

And the error I get is this one:

mc: <ERROR> Cannot set 'identity_openid config_url=http://localhost:8080/auth/realms/demo/.well-known/openid-configuration client_id=account' to server. Get http://localhost:8080/auth/realms/demo/.well-known/openid-configuration: dial tcp 127.0.0.1:8080: connect: connection refused.

When I curl this address http://localhost:8080/auth/realms/demo/.well-known/openid-configuration from the MinIO Client container though,  I retrieve the JSON file.


问:
Dynamic type guard functions
I would like to create a type guard function which checks if specific keys in an object have e.g. a string value. This is easy enough if I know the key names:

const data: object = { a: 'one', b: 'two', c: 'three' };

function hasStringKeyA(data: any): data is { a: string } {
    return typeof data.a === 'string';
}

if (hasStringKeyA(data)) {
    console.log(data.a);
}
```

<p>But when I need to check for more keys, this gets messy:</p>

<pre class="lang-js prettyprint-override"><code>if (hasStringKeyA(data) && hasStringKeyB(data)) {
    console.log([ data.a, data.b ].join(', '));
}
</code>```

What I would like to do instead:

```<code>if (hasStringKeys(data, ['a', 'b', 'c'])) {
    console.log([ data.a, data.c, data.b ].join(', '));
}
</code>```

But I cannot figure out how to write a type guard function which can be parametrized this way. Here’s a lousy attempt which does not work:

```<code>function hasStringKeys <K extends string[]> (data: any, keys: Keys): data is { [ k: typeof K ]: string } {
    for (const key of keys) {
        if (typeof data[key] !== 'string') {
            return false;
        }
    }
    return true;
}
</code>```

Is this possible? How?

答:
You are pretty close. I would use a type parameter to capture the string literal type of the items instead of the whole string array. And you need to use a mapped type instead of an index signature, you could write it yourself ({ [ k in K ]: string }) but the predefined Record type should work as well:

```<code>const data: object = { a: 'one', b: 'two', c: 'three' };

if (hasStringKeys(data, ['a', 'b', 'c'])) {
    console.log([ data.a, data.c, data.b ].join(', '));
}

function hasStringKeys <K extends string> (data: any, keys: K[]): data is Record<K, string> {
    for (const key of keys) {
        if (typeof data[key] !== 'string') {
            return false;
        }
    }
    return true;
}
</code>```

Playground Link

Title: Dynamic type guard functions

Body:
I would like to create a type guard function which checks if specific keys in an object have e.g. a string value. This is easy enough if I know the key names:

const data: object = { a: 'one', b: 'two', c: 'three' };

function hasStringKeyA(data: any): data is { a: string } {
    return typeof data.a === 'string';
}

if (hasStringKeyA(data)) {
    console.log(data.a);
}

But when I need to check for more keys, this gets messy:

if (hasStringKeyA(data) && hasStringKeyB(data)) {
    console.log([ data.a, data.b ].join(', '));
}

What I would like to do instead:

if (hasStringKeys(data, ['a', 'b', 'c'])) {
    console.log([ data.a, data.c, data.b ].join(', '));
}

But I cannot figure out how to write a type guard function which can be parametrized this way. Here’s a lousy attempt which does not work:

function hasStringKeys <K extends string[]> (data: any, keys: Keys): data is { [ k: typeof K ]: string } {
    for (const key of keys) {
        if (typeof data[key] !== 'string') {
            return false;
        }
    }
    return true;
}

Is this possible? How?

Body:
You are pretty close. I would use a type parameter to capture the string literal type of the items instead of the whole string array. And you need to use a mapped type instead of an index signature, you could write it yourself ({ [ k in K ]: string }) but the predefined Record type should work as well:

const data: object = { a: 'one', b: 'two', c: 'three' };

if (hasStringKeys(data, ['a', 'b', 'c'])) {
    console.log([ data.a, data.c, data.b ].join(', '));
}

function hasStringKeys <K extends string> (data: any, keys: K[]): data is Record<K, string> {
    for (const key of keys) {
        if (typeof data[key] !== 'string') {
            return false;
        }
    }
    return true;
}

Playground Link


问:
Center one and right/left align other flexbox element
I would like to have A B and C aligned in the middle.

How can I get D to go completely to the right?

BEFORE:

AFTER:

ul {
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
li {
  display: flex;
  margin: 1px;
  padding: 5px;
  background: #aaa;
}
li:last-child {
  background: #ddd;
  /* magic to throw to the right*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
</ul></code>```

https://jsfiddle.net/z44p7bsx/

答:
Inspired by the Method #5: CSS Grid Layout of @Michal Benjamin's solution and because I'm using Tailwind and as of now still don't have access to all the grid options by default. This seems to work:

ul {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

li {
  align-self: center;
}

li:nth-child(1) {
  justify-content: flex-start; /* OR margin-right: auto */
}

li:nth-child(3) {
  justify-content: flex-end; /* OR margin-left:auto */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul></code>```

PS: Not sure if mixing up flex and grid like this is a good idea!

Body:
I would like to have A B and C aligned in the middle.

How can I get D to go completely to the right?

BEFORE:

AFTER:

ul {
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
li {
  display: flex;
  margin: 1px;
  padding: 5px;
  background: #aaa;
}
li:last-child {
  background: #ddd;
  /* magic to throw to the right*/
}

A

B

C

D

https://jsfiddle.net/z44p7bsx/

Body:
Inspired by the Method #5: CSS Grid Layout of @Michal Benjamin's solution and because I'm using Tailwind and as of now still don't have access to all the grid options by default. This seems to work:

ul {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

li {
  align-self: center;
}

li:nth-child(1) {
  justify-content: flex-start; /* OR margin-right: auto */
}

li:nth-child(3) {
  justify-content: flex-end; /* OR margin-left:auto */
}

<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>

PS: Not sure if mixing up flex and grid like this is a good idea!


问:
How to insert a LUA Table to Tarantool with Key and Value?
I have a JSON string:

```<code>{
"entry_offset" : 180587225765,
"entry_size" : 54003,
"created_time" : 1577500878,
"additional_meta" : {
    "geohash64" : 5637765837143565,
    "mime_type" : "image/jpg"
}
</code>```

And I have converted it to Lua Table using Tarantool's module json:

```<code>table = json.decode(JSONstring)
</code>```

Then I want to insert the table to Tarantool with ID = 1

```<code>box.space.somespace:insert{1, table}
</code>```

The result is like this when I select the table which added to Tarantool database in JSON form:

Cannot access values through key

I can only access to table[1] and table[2]: table[1] is the ID = 1 while table[2] is all the JSON string. Which means I can't access the Values of JSON with Keys: table['entry_offset'], table['entry_size'], ....
return nil when I try to access them

So how can I insert a Lua table to Tarantool and then access the values through its keys?

Thanh you so much for helping!!!

答:
You are basically inserting a wrapping tuple into the space, not table object itself, so when you do:

obj = box.space.somespace:get{1}
```

<p>you get your tuple back, not <code>table</code>. That said if you want to access <code>table</code>'s fields using keys, you just need to index that obj like this:</p>

```table = obj[2]
print(table.entry_offset)
```

<p>Once you get used to it, check out tarantool space format feature with its <code>tomap</code>/<code>frommap</code> functions. Here is basic example, which may help you:</p>

<pre class="lang-lua prettyprint-override"><code>box.cfg{}
box.schema.create_space('test', {if_not_exists = true})
box.space.test:create_index('pk', {unique = true, if_not_exists = true, parts = {1, 'unsigned'}})
box.space.test:format({
    { name = 'id', 'unsigned' },
    { name = 'entry_offset', 'unsigned' },
    { name = 'entry_size', 'unsigned' },
    { name = 'created_time', 'unsigned' },
    { name = 'additional_meta', 'map' },
})

json = require('json')
obj_json = [[{
"entry_offset" : 180587225765,
"entry_size" : 54003,
"created_time" : 1577500878,
"additional_meta" : {
    "geohash64" : 5637765837143565,
    "mime_type" : "image/jpg"
}}]]
obj = json.decode(obj_json)
obj.id = 1

tuple = box.space.test:frommap(obj)
box.space.test:insert(tuple)
result = box.space.test:get({1}):tomap()

print(result.additional_meta.mime_type)
</code>```

Or, for more advanced serialization approach, take a look at avro-schema with its flatten/unflatten methods. There are examples in README

Body:
I have a JSON string:

{
"entry_offset" : 180587225765,
"entry_size" : 54003,
"created_time" : 1577500878,
"additional_meta" : {
    "geohash64" : 5637765837143565,
    "mime_type" : "image/jpg"
}

And I have converted it to Lua Table using Tarantool's module json:

table = json.decode(JSONstring)

Then I want to insert the table to Tarantool with ID = 1

box.space.somespace:insert{1, table}

The result is like this when I select the table which added to Tarantool database in JSON form:

Cannot access values through key

I can only access to table[1] and table[2]: table[1] is the ID = 1 while table[2] is all the JSON string. Which means I can't access the Values of JSON with Keys: table['entry_offset'], table['entry_size'], ....
return nil when I try to access them

So how can I insert a Lua table to Tarantool and then access the values through its keys?

Thanh you so much for helping!!!

Body:
You are basically inserting a wrapping tuple into the space, not table object itself, so when you do:

obj = box.space.somespace:get{1}

you get your tuple back, not table. That said if you want to access table's fields using keys, you just need to index that obj like this:

table = obj[2]
print(table.entry_offset)

Once you get used to it, check out tarantool space format feature with its tomap/frommap functions. Here is basic example, which may help you:

box.cfg{}
box.schema.create_space('test', {if_not_exists = true})
box.space.test:create_index('pk', {unique = true, if_not_exists = true, parts = {1, 'unsigned'}})
box.space.test:format({
    { name = 'id', 'unsigned' },
    { name = 'entry_offset', 'unsigned' },
    { name = 'entry_size', 'unsigned' },
    { name = 'created_time', 'unsigned' },
    { name = 'additional_meta', 'map' },
})

json = require('json')
obj_json = [[{
"entry_offset" : 180587225765,
"entry_size" : 54003,
"created_time" : 1577500878,
"additional_meta" : {
    "geohash64" : 5637765837143565,
    "mime_type" : "image/jpg"
}}]]
obj = json.decode(obj_json)
obj.id = 1

tuple = box.space.test:frommap(obj)
box.space.test:insert(tuple)
result = box.space.test:get({1}):tomap()

print(result.additional_meta.mime_type)

Or, for more advanced serialization approach, take a look at avro-schema with its flatten/unflatten methods. There are examples in README


问:
How to conditionalize nested stack creation via CommaDelimitedList parameter
in my AWS CloudFormation Template, I would like to conditionalize nested stack creation via a CommaDelimitedList parameter.

I would have done it this way:

```<code>{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Parameters": {
    "DeployNestedStacks": {
      "Description": "List of nested stack resources to deploy",
      "Type": "CommaDelimitedList",
      "AllowedValues": [
        "nestedStack1",
        "nestedStack2"
      ]
    }
  },
  "Conditions": {
    "DeployNestedStack1": { "Fn::Contains": [ { "Ref": "DeployNestedStacks" } , "nestedStack1" ] }
    "DeployNestedStack2": { "Fn::Contains": [ { "Ref": "DeployNestedStacks" } , "nestedStack2" ] }
  },
  "Resources": {
    "MyNestedStack1": {
      "Condition": "DeployNestedStack1",
      "Type": "AWS::CloudFormation::Stack",
      ...
    },
    "MyNestedStack2": {
      "Condition": "DeployNestedStack2",
      "Type": "AWS::CloudFormation::Stack",
      ...
    }
  }
}
</code>```

unfortunately Fn::Contains is not a valide Fn.

Still, I think it illustrates well what I would like to achieve.

How would you achieve this, please?

答:
Unfortunately, there is no such functionality in plain CloudFormation (CFN). CFN is not a programming language and it does not have loops, searches though lists and many other things found in regular programming language.

However, there some possible alternatives to consider:

Use of macros

Use of custom resources

Using CDK, instead of CFN.

Redesigning your template to have Conditions based on regular parameter values, not lists. For example using Select to do index based comparison.

Body:
in my AWS CloudFormation Template, I would like to conditionalize nested stack creation via a CommaDelimitedList parameter.

I would have done it this way:

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Parameters": {
    "DeployNestedStacks": {
      "Description": "List of nested stack resources to deploy",
      "Type": "CommaDelimitedList",
      "AllowedValues": [
        "nestedStack1",
        "nestedStack2"
      ]
    }
  },
  "Conditions": {
    "DeployNestedStack1": { "Fn::Contains": [ { "Ref": "DeployNestedStacks" } , "nestedStack1" ] }
    "DeployNestedStack2": { "Fn::Contains": [ { "Ref": "DeployNestedStacks" } , "nestedStack2" ] }
  },
  "Resources": {
    "MyNestedStack1": {
      "Condition": "DeployNestedStack1",
      "Type": "AWS::CloudFormation::Stack",
      ...
    },
    "MyNestedStack2": {
      "Condition": "DeployNestedStack2",
      "Type": "AWS::CloudFormation::Stack",
      ...
    }
  }
}

unfortunately Fn::Contains is not a valide Fn.

Still, I think it illustrates well what I would like to achieve.

How would you achieve this, please?


问:
simplest way to do a recurring text file upload to sql server
i have a TAB DELIMITTED log file where new data in this log file needs to be dumped into a sql server 2008 database. i am wondering what is the best way to automate this? is there a service i can use inside the management studio that will help me? </p>

答:
I would use SSIS (if available) and automate through that: http://msdn.microsoft.com/en-us/library/dd440761%28v=sql.100%29.aspx

Failing that, you could do a joined process of [scripting language of choice] + SSIS to have something watching the correct folder for the specific file and then have that kick off the SSIS package.

If SSIS is not available at all, then you're stuck with parsing out the file in code, and turning that into insert/update statements or calls to a stored proc that will do the same.


问:
Select the first visible cell in every sheet with a loop in VBA
I use the below VBA to select the first visible cell in a filtered range:

```<code>Sub Postioning_Option_01()
Sheet1.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
End Sub
</code>```

Now, instead of only applying this VBA to Sheet1 I want to loop through all sheets.

Therefore, I tried to go with this VBA:

```<code>Sub Postioning_Option_02()
Dim b As Worksheet
For Each b In Worksheets
b.Select
b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
Next b
End Sub
</code>```

When I run this VBA I get error Object variable or With block variable not set.

What do I need to change in the VBA to make it work?

答:
A Small AutoFilter Study

Nothing special about the first 4 subs, but the last 2 look a little bit deeper, but might be out of context.

```<code>Option Explicit

Sub Positioning_Option_01()
    If Sheet1.AutoFilterMode Then
        Sheet1.AutoFilter.Range.Offset(1) _
          .SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
    Else
    End If
End Sub

Sub Postioning_Option_02()
    Dim b As Worksheet
    For Each b In ThisWorkbook.Worksheets
        b.Activate
        If b.AutoFilterMode Then
            b.AutoFilter.Range.Offset(1) _
              .SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
        Else
        End If
    Next
End Sub

Sub Positioning_Option_01_With()
    With Sheet1
        If .AutoFilterMode Then
            With .AutoFilter.Range.Offset(1) _
              .SpecialCells(xlCellTypeVisible).Cells(1, 2)
                .Select
            End With
        Else
        End If
    End With
End Sub

Sub Postioning_Option_02_With()
    Dim b As Worksheet
    For Each b In ThisWorkbook.Worksheets
        b.Activate
        With b
            If .AutoFilterMode Then
                With .AutoFilter.Range.Offset(1) _
                  .SpecialCells(xlCellTypeVisible).Cells(1, 2)
                    .Select
                End With
            Else
            End If
        End With
    Next
End Sub

Sub Pos_Offset()
    With Sheet1
        If .AutoFilterMode Then
            ' The following range refers to the range below headers containing
            ' data and one empty row range below data.
            With .AutoFilter.Range.Offset(1)
                ' If no match in AutoFilter, after applying "SpecialCells"
                ' the cell in the row below data will be selected. You can't
                ' tell if it is contained in "AutoFilter.Range".
                With .SpecialCells(xlCellTypeVisible).Cells(1, 2)
                    .Select
                    Debug.Print .Address, .Value
                End With
            End With
        Else
            ' AutoFilterMode is False
            MsgBox "AutoFilterMode is set to 'False'."
        End If
    End With
End Sub

Sub Pos_Actual()
    With Sheet1
        If .AutoFilterMode Then
            ' The range below headers containing data.
            With .AutoFilter.Range
                With .Rows(2).Resize(.Rows.Count - 1)
                    ' If no match in AutoFilter, after applying SpecialCells
                    ' in the following line, the following error occurs:
                    ' "Run-time error '1004': No cells were found."
                    ' Therefore:
                    On Error Resume Next
                    With .SpecialCells(xlCellTypeVisible).Cells(1, 2)
                        If Err.Number <> 0 Then
                            ' The are no visible cells.
                            MsgBox "No visible cells."
                        Else
                            .Select
                            Debug.Print .Address, .Value
                        End If
                        On Error GoTo 0
                    End With
                End With
            End With
        Else
            ' AutoFilterMode is False
            MsgBox "AutoFilterMode is set to 'False'."
        End If
    End With
End Sub
</code>```

Body:
I use the below VBA to select the first visible cell in a filtered range:

Sub Postioning_Option_01()
Sheet1.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
End Sub

Now, instead of only applying this VBA to Sheet1 I want to loop through all sheets.

Therefore, I tried to go with this VBA:

Sub Postioning_Option_02()
Dim b As Worksheet
For Each b In Worksheets
b.Select
b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
Next b
End Sub

When I run this VBA I get error Object variable or With block variable not set.

What do I need to change in the VBA to make it work?

Body:
A Small AutoFilter Study

Nothing special about the first 4 subs, but the last 2 look a little bit deeper, but might be out of context.

Option Explicit

Sub Positioning_Option_01()
    If Sheet1.AutoFilterMode Then
        Sheet1.AutoFilter.Range.Offset(1) _
          .SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
    Else
    End If
End Sub

Sub Postioning_Option_02()
    Dim b As Worksheet
    For Each b In ThisWorkbook.Worksheets
        b.Activate
        If b.AutoFilterMode Then
            b.AutoFilter.Range.Offset(1) _
              .SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
        Else
        End If
    Next
End Sub

Sub Positioning_Option_01_With()
    With Sheet1
        If .AutoFilterMode Then
            With .AutoFilter.Range.Offset(1) _
              .SpecialCells(xlCellTypeVisible).Cells(1, 2)
                .Select
            End With
        Else
        End If
    End With
End Sub

Sub Postioning_Option_02_With()
    Dim b As Worksheet
    For Each b In ThisWorkbook.Worksheets
        b.Activate
        With b
            If .AutoFilterMode Then
                With .AutoFilter.Range.Offset(1) _
                  .SpecialCells(xlCellTypeVisible).Cells(1, 2)
                    .Select
                End With
            Else
            End If
        End With
    Next
End Sub

Sub Pos_Offset()
    With Sheet1
        If .AutoFilterMode Then
            ' The following range refers to the range below headers containing
            ' data and one empty row range below data.
            With .AutoFilter.Range.Offset(1)
                ' If no match in AutoFilter, after applying "SpecialCells"
                ' the cell in the row below data will be selected. You can't
                ' tell if it is contained in "AutoFilter.Range".
                With .SpecialCells(xlCellTypeVisible).Cells(1, 2)
                    .Select
                    Debug.Print .Address, .Value
                End With
            End With
        Else
            ' AutoFilterMode is False
            MsgBox "AutoFilterMode is set to 'False'."
        End If
    End With
End Sub

Sub Pos_Actual()
    With Sheet1
        If .AutoFilterMode Then
            ' The range below headers containing data.
            With .AutoFilter.Range
                With .Rows(2).Resize(.Rows.Count - 1)
                    ' If no match in AutoFilter, after applying SpecialCells
                    ' in the following line, the following error occurs:
                    ' "Run-time error '1004': No cells were found."
                    ' Therefore:
                    On Error Resume Next
                    With .SpecialCells(xlCellTypeVisible).Cells(1, 2)
                        If Err.Number <> 0 Then
                            ' The are no visible cells.
                            MsgBox "No visible cells."
                        Else
                            .Select
                            Debug.Print .Address, .Value
                        End If
                        On Error GoTo 0
                    End With
                End With
            End With
        Else
            ' AutoFilterMode is False
            MsgBox "AutoFilterMode is set to 'False'."
        End If
    End With
End Sub


问:
Remove one element in array of document MongoDB
I have database in MongoDB like this

```<code>{"_id":{"$oid":"5eb8c55230cb8651e0906d7e"},"rolecode":"DHBK_ROLE_01","functioncode":"DHBK_FUNC_01, DHBK_FUNC_02","productid":"mBaaS_Platform","comid":"DHBK"}
{"_id":{"$oid":"5eb8c5a030cb8651e0906d7f"},"rolecode":"DHBK_ROLE_02","functioncode":"DHBK_FUNC_02, DHBK_FUNC_03","productid":"GIS_Platform","comid":"DHBK"}
{"_id":{"$oid":"5ebe0016b4146803d8ad2559"},"rolecode":"DHKT_ROLE_01","functioncode":"DHKT_FUNC_01, DHKT_FUNC_02","productid":"mBaaS_Platform","comid":"DHKT"}
{"_id":{"$oid":"5ebe003cb4146803d8ad255a"},"rolecode":"DHKT_ROLE_02","functioncode":"DHKT_FUNC_01","productid":"Analysis_Platform","comid":"DHKT"}
{"_id":{"$oid":"5ebe00ffb4146803d8ad255b"},"rolecode":"DHBK_ROLE_03","functioncode":"DHBK_FUNC_01, DHBK_FUNC_02,DHBK_FUNC_03","productid":"IOT_Platform","comid":"DHBK"}
{"_id":{"$oid":"5ecf89f969f07e1cb0ad063d"},"rolecode":"DHBK1_ROLE_01","functioncode":"DHBK1_FUNC_1,DHBK_FUNC_03","productid":"IOT_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ecf8b6169f07e1cb0ad063e"},"rolecode":"DHBK1_ROLE_02","functioncode":"DHBK1_FUNC_1,DHBK_FUNC_02","productid":"SSO_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ecf8b7969f07e1cb0ad063f"},"rolecode":"DHBK1_ROLE_03","functioncode":"","productid":"ABC_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}
</code>```

I have Mongo shell to find all document have DHBK1_FUNC_1 in functioncodelist properties.

Here is my Mongo shell

db.company_role_function.find( { functioncodelist: { $all: ["DHBK1_FUNC_1"] } } )

And this is the result

```<code>{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}
</code>```

Now I want to remove value DHBK1_FUNC_1 in that result. I hope my result after delete action like this

```<code>{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":[""],"comid":"DHBK1"}
</code>```

Thank in advanced

答:
You can use the $pull operator to achieve this.

db.company_role_function.update(
  { },
  { $pull: { functioncodelist: { $in: ['DHBK1_FUNC_1'] }}},
  { multi: true }
)
```

Body:
I have database in MongoDB like this

{"_id":{"$oid":"5eb8c55230cb8651e0906d7e"},"rolecode":"DHBK_ROLE_01","functioncode":"DHBK_FUNC_01, DHBK_FUNC_02","productid":"mBaaS_Platform","comid":"DHBK"}
{"_id":{"$oid":"5eb8c5a030cb8651e0906d7f"},"rolecode":"DHBK_ROLE_02","functioncode":"DHBK_FUNC_02, DHBK_FUNC_03","productid":"GIS_Platform","comid":"DHBK"}
{"_id":{"$oid":"5ebe0016b4146803d8ad2559"},"rolecode":"DHKT_ROLE_01","functioncode":"DHKT_FUNC_01, DHKT_FUNC_02","productid":"mBaaS_Platform","comid":"DHKT"}
{"_id":{"$oid":"5ebe003cb4146803d8ad255a"},"rolecode":"DHKT_ROLE_02","functioncode":"DHKT_FUNC_01","productid":"Analysis_Platform","comid":"DHKT"}
{"_id":{"$oid":"5ebe00ffb4146803d8ad255b"},"rolecode":"DHBK_ROLE_03","functioncode":"DHBK_FUNC_01, DHBK_FUNC_02,DHBK_FUNC_03","productid":"IOT_Platform","comid":"DHBK"}
{"_id":{"$oid":"5ecf89f969f07e1cb0ad063d"},"rolecode":"DHBK1_ROLE_01","functioncode":"DHBK1_FUNC_1,DHBK_FUNC_03","productid":"IOT_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ecf8b6169f07e1cb0ad063e"},"rolecode":"DHBK1_ROLE_02","functioncode":"DHBK1_FUNC_1,DHBK_FUNC_02","productid":"SSO_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ecf8b7969f07e1cb0ad063f"},"rolecode":"DHBK1_ROLE_03","functioncode":"","productid":"ABC_Platform","comid":"DHBK1"}
{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}

I have Mongo shell to find all document have DHBK1_FUNC_1 in functioncodelist properties.

Here is my Mongo shell

db.company_role_function.find( { functioncodelist: { $all: ["DHBK1_FUNC_1"] } } )

And this is the result

{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}

Now I want to remove value DHBK1_FUNC_1 in that result. I hope my result after delete action like this

{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":[""],"comid":"DHBK1"}

Thank in advanced


问:
Secrets in Azure Stream Analytics
In our Stream Analytics Job we have some constant values that are required for further computations. Those are considered "secret" by our customer, so it would be good to not have them set directly in the Query or the User Defined Function we're using. Is there any best practice how to deal with these, e.g. can we somehow retrieve these values from Azure Key Vault?

答:
Unfortunately, Azure Stream Analytics don’t support Azure Key Vault bindings.

I would suggest you to vote up an idea submitted by another Azure customer.

https://feedback.azure.com/forums/270577-stream-analytics/suggestions/35328418-enhance-security-for-asa-managed-services-identit

https://feedback.azure.com/forums/270577-stream-analytics/suggestions/40530247-azure-key-vault-as-reference-data-input

All of the feedback you share in these forums will be monitored and reviewed by the Microsoft engineering teams responsible for building Azure.

Title: Secrets in Azure Stream Analytics


问:
Creating a new Shared Drive
When I run the code below, which is taken from: https://developers.google.com/drive/api/v3/manage-shareddrives#python

```<code># Create a new drive
        test_drive_metadata = {'name': 'Test Drive'}
        request_id = str(uuid.uuid4())
        test_drive = self.service.drives().create(
            body=test_drive_metadata,
            requestId=request_id,
            fields='id'
        ).execute()
</code>```

I get "The user does not have sufficient permissions for this file." This does not happen if I create files, if I list shared drives or anything else. There are no other required scopes other than ['https://www.googleapis.com/auth/drive'].

It should be noted that I am using a service account. Are service accounts not allowed to create shared drives? This is not documented anywhere as far as I am aware if this is the case.

答:
There doesn't seem to be any explicit documentation regarding this limitation, but considering that Service Accounts (without using DWD and impersonation) are supposed to manage application data, and not user data, it makes sense that they cannot be used to manage data that is shared with regular users.

Also, the use of Service Accounts to manage shared documents seems to be advised against, according to the official documentation:

Using the service account as a common owner to create many shared documents can have severe performance implications.

On the other hand, since Service Accounts have certain limitations compared to regular accounts (for example, Event creation in Calendar), this could probably be one of these limitations.

In any case, in order to make sure that's the case, I'd suggest you to report this behaviour in this Issue Tracker component.

Reference:

Drive API: Perform G Suite Domain-Wide Delegation of Authority

Using OAuth 2.0 for Server to Server Applications

Title: Creating a new Shared Drive

Body:
When I run the code below, which is taken from: https://developers.google.com/drive/api/v3/manage-shareddrives#python

# Create a new drive
        test_drive_metadata = {'name': 'Test Drive'}
        request_id = str(uuid.uuid4())
        test_drive = self.service.drives().create(
            body=test_drive_metadata,
            requestId=request_id,
            fields='id'
        ).execute()

I get "The user does not have sufficient permissions for this file." This does not happen if I create files, if I list shared drives or anything else. There are no other required scopes other than ['https://www.googleapis.com/auth/drive'].

It should be noted that I am using a service account. Are service accounts not allowed to create shared drives? This is not documented anywhere as far as I am aware if this is the case.


问:
RegEx remove part of string and and replace another part
I have a challenge getting the desired result with RegEx (using C#) and I hope that the community can help.

I have a URL in the following format:
https://somedomain.com/subfolder/category/?abc=text:value&ida=0&idb=1

I want make two modifications, specifically:

1) Remove everything after 'value' e.g. '&ida=0&idb=1'

2) Replace 'category' with e.g. 'newcategory'

So the result is:
https://somedomain.com/subfolder/newcategory/?abc=text:value

I can remove the string from 1) e.g. ^[^&]+ above but I have been unable to figure out how to replace the 'category' substring.

Any help or guidance would be much appreciated.

Thank you in advance.

答:
You haven't specified language here, I mainly work on python so the solution is in python.

```<code>url = re.sub('category','newcategory',re.search('^https.*value', value).group(0))
</code>```

Explanation
re.sub is used to replace value a with b in c.

re.search is used to match specific patterns in string and store value in the group. so in the above code re.search will store value from "https to value" in group 0.

Body:
You haven't specified language here, I mainly work on python so the solution is in python.

url = re.sub('category','newcategory',re.search('^https.*value', value).group(0))

Explanation
re.sub is used to replace value a with b in c.

re.search is used to match specific patterns in string and store value in the group. so in the above code re.search will store value from "https to value" in group 0.


问:
How to pass common arguments in Dart?
Say, I have:

```<code>callback.orderBy('foo', reverse: true).localToThis();
callback.orderBy('foo', reverse: true);
</code>```

You can see in both callbacks, I am passing same arguments,

```<code>'foo', reverse: true
</code>```

Is there any way I can make them something (a variable or a method) so that I can use something like this:

```<code>callback.orderBy(common).localToThis();
callback.orderBy(common);
</code>```

答:
You can create a class, containing fields you want to be common

class OrderConfiguration {
  final String orderBy;
  final bool reverse;

  OrderConfiguration(this.orderBy, {reverse = false});
}
```

<p>and then accept an instance of <code>OrderConfiguration</code> as an argument to <code>orderBy</code></p>

<p><br>
But you can do this only for your own functions, for functions that weren't written by you, you could make a wrapper function. (May be this is a better option for your function too)</p>

<pre class="lang-dart prettyprint-override"><code>void orderCallback(callback) {
  callback.orderBy('foo', reverse: true);
}
</code>```

or if orderBy returns a value

Type orderCallback(callback) {
  return callback.orderBy('foo', reverse: true);
}
```

Title: How to pass common arguments in Dart?

Body:
Say, I have:

callback.orderBy('foo', reverse: true).localToThis();
callback.orderBy('foo', reverse: true);

You can see in both callbacks, I am passing same arguments,

'foo', reverse: true

Is there any way I can make them something (a variable or a method) so that I can use something like this:

callback.orderBy(common).localToThis();
callback.orderBy(common);

Body:
You can create a class, containing fields you want to be common

class OrderConfiguration {
  final String orderBy;
  final bool reverse;

  OrderConfiguration(this.orderBy, {reverse = false});
}

and then accept an instance of OrderConfiguration as an argument to orderBy

But you can do this only for your own functions, for functions that weren't written by you, you could make a wrapper function. (May be this is a better option for your function too)

void orderCallback(callback) {
  callback.orderBy('foo', reverse: true);
}

or if orderBy returns a value

Type orderCallback(callback) {
  return callback.orderBy('foo', reverse: true);
}


问:
Corda - In a Corda network, how do participating companies handle customer interaction and identities on the ledger?
If a group of companies want to create a loyalty token scheme via a Corda network, how do they enable customers to be able to receive or spend loyalty tokens via any of the participating company channels?

For example, Alice earns 100 tokens from Company X's shopping app for being a loyal customer. The record of Alice's balance is captured on the Corda ledger via Company X's Corda node. Alice then wants to spend these tokens on Company Y's shopping app.

How is Alice identified on the Corda network?
How can this be achieved so that only Alice has the power to spend her tokens (i.e. the participating companies cannot edit her balance without her consent.)?

I'm thinking this could be achieved if customers had their own key pair and needed their private key to transact. Is this currently possible on Corda or is it on the roadmap?

答:
Hi this is now possible with accounts-sdk released with Corda 4.3.
So you could now have multiple companies host their customers on their nodes as accounts and have loyalty tokens issued to them. So accounts feature can be integrated with tokens feature.

To your question regarding, How can this be achieved so that only Alice has the power to spend her tokens, tokens sdk makes sure that only the current holder/owner of the token has the right to spend the tokens.

Your last question
I'm thinking this could be achieved if customers had their own key pair and needed their private key to transact. Is this currently possible on Corda or is it on the roadmap?
As I mentioned above that the companies can have their customers represented as accounts on their nodes. But please note that as of now, accounts are not true identities, i.e. they do not have any certificate issued by the doorman. They use anonymous identities to transact with each other. But yes, there is a plan where accounts will be able to move these key pairs outside of the node and effectively own their own private keys.


问:
How to call a Vuex method from life cycles
I have the following function in Vuex actions:

```<code>async toggleNavMenu({commit}){
  commit('changeNavMenu')
}
</code>```

which just changes state.ShowNavMenu status from true to false and vise versa. I'm trying to call it the moment SignUp.vue component render to hide the NavMenu, like this

```<code>import { mapActions } from 'vuex'
export default {
  name:"NavMenu",
  methods:{
    ...mapActions({
      Toggle: actions => actions.toggleNavMenu
        })
      },
    beforeCreate() {
      this.Toggle()
  }
}
</code>```

but when ever I render the component I get the following error:

```<code>[Vue warn]: Error in created hook: "TypeError: Cannot read property 'dispatch' of undefined"

</code>```

any idea to fix this, or if there a better approach for this ? thanks in advance

答:
I found the solution.Change the life cycle from beforeCreate() to created()
and change:

```<code>  ...mapActions({
      Toggle: actions => actions.toggleNavMenu
    })
</code>```

to:

```<code>  ...mapActions({
     Toggle: 'toggleNavMenu'
  })
</code>```

I don't why I had to change Toggle assignment like this though

Body:
I have the following function in Vuex actions:

async toggleNavMenu({commit}){
  commit('changeNavMenu')
}

which just changes state.ShowNavMenu status from true to false and vise versa. I'm trying to call it the moment SignUp.vue component render to hide the NavMenu, like this

import { mapActions } from 'vuex'
export default {
  name:"NavMenu",
  methods:{
    ...mapActions({
      Toggle: actions => actions.toggleNavMenu
        })
      },
    beforeCreate() {
      this.Toggle()
  }
}

but when ever I render the component I get the following error:

[Vue warn]: Error in created hook: "TypeError: Cannot read property 'dispatch' of undefined"

any idea to fix this, or if there a better approach for this ? thanks in advance

Body:
I found the solution.Change the life cycle from beforeCreate() to created()
and change:

  ...mapActions({
      Toggle: actions => actions.toggleNavMenu
    })

to:

  ...mapActions({
     Toggle: 'toggleNavMenu'
  })

I don't why I had to change Toggle assignment like this though


问:
what is the use of ! sign in some ruby methods

Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

```<code>before_filter :authenticated!
</code>```

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

答: ! can be used as last character in Ruby method names (as can ? and =). It's often used to denote "dangerous" methods (e.g. mutating a value in place) or generally methods you should pay attention to.

Body:
Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

before_filter :authenticated!

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera


问:
Issue with Reacts render method :Giving Parsing error
Im getting the following error Parsing error: Unexpected token, expected ",",for the below code

```<code>class ProductDetails extends React.Component{
constructor(){
    super();
    this.state = {timer:0};
}
start = () => {
    this.setState({timer:this.state.timer + 1});
}
componentDidMount(){
    setInterval(this.start,1000)
}
render(){
    var data = [{ _id:12345,
                pdtName:"Gaming Laptop",
                pdtPrice:35000,
                pdtDescription:"An excellent choice for great gaming experience",
                img:'images/Laptop.jpg',
                rating:5,
                isDiscontinued:false

            }];

    return(
            <h3>Timer: {this.state.timer} </h3>

             data.map(product =>{
                return <Product pimg={product.img} pid = {product._id} pname = {product.pdtName} pprice = {product.pdtPrice} pdesc = {product.pdtDescription}
                 prating = {product.rating} pisdiscon = {product.isDiscontinued} key={product._id}/>
            })

        )
}
</code>```

}

When I remove
Timer: {this.state.timer}
 from render() Im not getting the error.Simillarly if i remove data.map leaving  not getting error..But when using both getting the above error.How to fix it?

Thanks

答:
render() function should return only one element. In your case it is returning 2 elements which are
 and <Product>.
You can resolve this by using <React.Fragment> as mentioned above or simply put everything inside

Body:
Im getting the following error Parsing error: Unexpected token, expected ",",for the below code

class ProductDetails extends React.Component{
constructor(){
    super();
    this.state = {timer:0};
}
start = () => {
    this.setState({timer:this.state.timer + 1});
}
componentDidMount(){
    setInterval(this.start,1000)
}
render(){
    var data = [{ _id:12345,
                pdtName:"Gaming Laptop",
                pdtPrice:35000,
                pdtDescription:"An excellent choice for great gaming experience",
                img:'images/Laptop.jpg',
                rating:5,
                isDiscontinued:false

            }];

    return(

Timer: {this.state.timer}

             data.map(product =>{
                return <Product pimg={product.img} pid = {product._id} pname = {product.pdtName} pprice = {product.pdtPrice} pdesc = {product.pdtDescription}
                 prating = {product.rating} pisdiscon = {product.isDiscontinued} key={product._id}/>
            })

        )
}

}

When I remove
Timer: {this.state.timer}
 from render() Im not getting the error.Simillarly if i remove data.map leaving  not getting error..But when using both getting the above error.How to fix it?

Thanks

Body:
render() function should return only one element. In your case it is returning 2 elements which are <h3> and <Product>.
You can resolve this by using <React.Fragment> as mentioned above or simply put everything inside <div>


问:
How to extend the functionality of vector class as well as its iterator C++
I would like to find a clean way to slightly change the way std::vector operates.

Problem background

I need to be able to have index in the vector where the pointer would essentially slip one back, so for example; if my vector contains {0,1,2,3,4,5} and index [3] needs to slip, when iterating through the vector it should return: 0, 1, 2, 3, 3, 4, 5

Problem

Without rewriting the entire vector class and implementing my changes, is it possible to inherit std::vector<T> into a custom class, and override the behavior of the iterators ++ operator as well as the vector::begin()? (to add memory of the fact that it has already slipped one and not to slip again)

What I have tried

I have tried a basically implementation so far, but have gotten stuck when trying to override the begin() function.

```<code>#include <vector>
#include <iostream>
#include <iterator>

template <typename T>
class myVector : public std::vector<T>{
public:
  class myIterator : public std::vector<T>::iterator
  {
    // call vector's iterotor constructor

    //override
    // iterator& operator++(void){}
    // iterator operator++(int){}
  };

  using std::vector<T>::vector; // use the constructor from vector

  // extend the begin function, but include original operation
  myVector::myIterator begin() const
  {
    std::cout << "hi\n"; // testing to see if begin has been overriden properly
    return std::vector<T>::begin();
  }

};

// print out the vector
template <typename T>
std::ostream& operator<<(std::ostream& os, const myVector<T>& v)
{
  auto begin=v.begin();
  while (begin!=v.end())
  {
    os << *begin;
    ++begin;

    if(begin!=v.end())
    {
      os << ',';
    }
  }
  return os;
}

int main() {
  myVector<int> vec = {1,2,3,4};

  std::cout << vec << '\n';
}
</code>```

If you have an alternative clean solutions, it is also welcome.

Thanks

答:
As others already said, just define a custom iterator. If you moreover want the nice range iteration, you can then just define a custom range class returning your custom iterators.

See a working example below (needs --std=c++17):

```<code>#include <vector>
#include <iostream>

template<typename T>
class SlipIterator {
private:
  using iterator = typename std::vector<T>::const_iterator;
  iterator i;
  iterator slip;
  bool has_slipped;

public:
  SlipIterator(iterator i, iterator slip): i(i), slip(slip), has_slipped(false) {}

  SlipIterator &operator++() {
    if ((!has_slipped) && (i == slip))
      has_slipped = true;
    else
      ++i;
    return *this;
  }

  bool operator!=(SlipIterator<T> &the_end) const { return i != the_end.i; }

  const T &operator*() const { return *i; }

};

template<typename T>
class SlipperyRange {
private:
  const std::vector<T> &v;
  size_t slip_index;

public:
  SlipperyRange(const std::vector<T> &v, size_t slip_index) : v(v), slip_index(slip_index) {}

  SlipIterator<T> begin() const { return SlipIterator<T>(v.cbegin(), v.cbegin() + slip_index); }

  SlipIterator<T> end() const { return SlipIterator<T>(v.cend(), v.cend()); }
};

int main() {
  std::vector<int> v{1,2,3,4,5};
  for(const int i: SlipperyRange{v, 2})
    std::cout << i << ' ';
  std::cout << '\n';
  return 0;
}
</code>```

Body:
I would like to find a clean way to slightly change the way std::vector operates.

Problem background

I need to be able to have index in the vector where the pointer would essentially slip one back, so for example; if my vector contains {0,1,2,3,4,5} and index [3] needs to slip, when iterating through the vector it should return: 0, 1, 2, 3, 3, 4, 5

Problem

Without rewriting the entire vector class and implementing my changes, is it possible to inherit std::vector<T> into a custom class, and override the behavior of the iterators ++ operator as well as the vector::begin()? (to add memory of the fact that it has already slipped one and not to slip again)

What I have tried

I have tried a basically implementation so far, but have gotten stuck when trying to override the begin() function.

#include <vector>
#include <iostream>
#include <iterator>

template <typename T>
class myVector : public std::vector<T>{
public:
  class myIterator : public std::vector<T>::iterator
  {
    // call vector's iterotor constructor

    //override
    // iterator& operator++(void){}
    // iterator operator++(int){}
  };

  using std::vector<T>::vector; // use the constructor from vector

  // extend the begin function, but include original operation
  myVector::myIterator begin() const
  {
    std::cout << "hi\n"; // testing to see if begin has been overriden properly
    return std::vector<T>::begin();
  }

};

// print out the vector
template <typename T>
std::ostream& operator<<(std::ostream& os, const myVector<T>& v)
{
  auto begin=v.begin();
  while (begin!=v.end())
  {
    os << *begin;
    ++begin;

    if(begin!=v.end())
    {
      os << ',';
    }
  }
  return os;
}

int main() {
  myVector<int> vec = {1,2,3,4};

  std::cout << vec << '\n';
}

If you have an alternative clean solutions, it is also welcome.

Thanks

Body:
As others already said, just define a custom iterator. If you moreover want the nice range iteration, you can then just define a custom range class returning your custom iterators.

See a working example below (needs --std=c++17):

#include <vector>
#include <iostream>

template<typename T>
class SlipIterator {
private:
  using iterator = typename std::vector<T>::const_iterator;
  iterator i;
  iterator slip;
  bool has_slipped;

public:
  SlipIterator(iterator i, iterator slip): i(i), slip(slip), has_slipped(false) {}

  SlipIterator &operator++() {
    if ((!has_slipped) && (i == slip))
      has_slipped = true;
    else
      ++i;
    return *this;
  }

  bool operator!=(SlipIterator<T> &the_end) const { return i != the_end.i; }

  const T &operator*() const { return *i; }

};

template<typename T>
class SlipperyRange {
private:
  const std::vector<T> &v;
  size_t slip_index;

public:
  SlipperyRange(const std::vector<T> &v, size_t slip_index) : v(v), slip_index(slip_index) {}

  SlipIterator<T> begin() const { return SlipIterator<T>(v.cbegin(), v.cbegin() + slip_index); }

  SlipIterator<T> end() const { return SlipIterator<T>(v.cend(), v.cend()); }
};

int main() {
  std::vector<int> v{1,2,3,4,5};
  for(const int i: SlipperyRange{v, 2})
    std::cout << i << ' ';
  std::cout << '\n';
  return 0;
}