问:
Is there a way for me to convert O'reilly to O'Reilly?
I would like to display names in title case and also convert the hyphenated names — such as O'Reilly — properly.

Right now, when I use the ToUpperCase function, I get "O'reilly", and that is not what I want.

Here's the function I am using:

```<code>@functions
{
    public static class TextConvert
    {
        public static string ToTitleCase(string s)
        {
            s = s.ToLower();
            return Regex.Replace(s, @"(^\w)|(\s\w)",b => b.Value.ToUpper());
        }
    }
}
</code>```

How can I do that, accounting for cases like O'Reilly?

答:
You can try It.

```<code>var titlecase = PrintName("o'riley");
</code>```

Call this function

```<code>Public static string PrintName(string StrValue)//pass here - o'riley
        {
            if (!string.IsNullOrEmpty(StrValue))
            {
                return Regex.Replace(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(StrValue.ToLower()),
                 "['-](?:.)", m => m.Value.ToUpperInvariant());
            }
            else
            {
                return "Something meaningful message";
            }
        }
</code>```

Body:
I would like to display names in title case and also convert the hyphenated names — such as O'Reilly — properly.

Right now, when I use the ToUpperCase function, I get "O'reilly", and that is not what I want.

Here's the function I am using:

@functions
{
    public static class TextConvert
    {
        public static string ToTitleCase(string s)
        {
            s = s.ToLower();
            return Regex.Replace(s, @"(^\w)|(\s\w)",b => b.Value.ToUpper());
        }
    }
}

How can I do that, accounting for cases like O'Reilly?

Body:
You can try It.

var titlecase = PrintName("o'riley");

Call this function

Public static string PrintName(string StrValue)//pass here - o'riley
        {
            if (!string.IsNullOrEmpty(StrValue))
            {
                return Regex.Replace(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(StrValue.ToLower()),
                 "['-](?:.)", m => m.Value.ToUpperInvariant());
            }
            else
            {
                return "Something meaningful message";
            }
        }


来源: stackexchange

问:
Mongo DB with C# - document added regardless of transaction
I'm trying to test the newly supported transactions in Mongo DB with a simple example I wrote.
I'm using Mongo DB version 4.0.5 with driver version 2.8.1.
It's only a primary instance with no shards/replicas.

I must be missing something basic in the following code.
I create a Mongo client, session & database, then start a transaction, add a document and abort the transaction. After this code, I expect nothing to change in the database, but the document is added. When debugging I can also see the document right after the InsertOne() by using Robo 3T (Mongo client GUI).

Any idea what am I missing?

```<code>        var client =  new MongoClient("mongodb://localhost:27017");
        var session = client.StartSession();
        var database = session.Client.GetDatabase("myDatabase", new MongoDatabaseSettings
        {
            GuidRepresentation = GuidRepresentation.Standard,
            ReadPreference = ReadPreference.Primary,
            WriteConcern = new WriteConcern(1,
                new MongoDB.Driver.Optional<TimeSpan?>(TimeSpan.FromSeconds(30))),

        });

        var entities = database.GetCollection<MyEntity>("test");

        session.StartTransaction();

        // After this line I can already see the document in the db collection using Mongo client GUI (Robo 3T), although I expect not to see it until committing
        entities.InsertOne(new MyEntity { Name =  "Entity" });

        // This does not have any effect
        session.AbortTransaction();
</code>```

Edit:

It's possible to run MongoDB as a 1-node replica set, although I'm not sure what's the difference between a standalone and a 1-node replica set.
See my post below.

In any case, to use the started transaction the insertion code must receive the session as a parameter:

```<code>entities.InsertOne(session, new MyEntity { Name = "Entity" });
</code>```

With these 2 change now the transaction works.

答:
I found a solution, although not sure what the consequences are, maybe someone can point it out:
It seems it's possible to use Mongo DB as a 1-node replica set (instead of a standalone) by simply adding the following in the mongod.cfg file:

```<code>replication:
   replSetName: rs1
</code>```

Also, thanks to the following link the code should use the correct overload of InsertOne() which receives the session as the first parameter (see the edit on the original post):

multiple document transaction not working in c# using mongodb 4.08 community server

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to test the newly supported transactions in Mongo DB with a simple example I wrote.
I'm using Mongo DB version 4.0.5 with driver version 2.8.1.
It's only a primary instance with no shards/replicas.

I must be missing something basic in the following code.
I create a Mongo client, session & database, then start a transaction, add a document and abort the transaction. After this code, I expect nothing to change in the database, but the document is added. When debugging I can also see the document right after the InsertOne() by using Robo 3T (Mongo client GUI).

Any idea what am I missing?

        var client =  new MongoClient("mongodb://localhost:27017");
        var session = client.StartSession();
        var database = session.Client.GetDatabase("myDatabase", new MongoDatabaseSettings
        {
            GuidRepresentation = GuidRepresentation.Standard,
            ReadPreference = ReadPreference.Primary,
            WriteConcern = new WriteConcern(1,
                new MongoDB.Driver.Optional<TimeSpan?>(TimeSpan.FromSeconds(30))),

        });

        var entities = database.GetCollection<MyEntity>("test");

        session.StartTransaction();

        // After this line I can already see the document in the db collection using Mongo client GUI (Robo 3T), although I expect not to see it until committing
        entities.InsertOne(new MyEntity { Name =  "Entity" });

        // This does not have any effect
        session.AbortTransaction();

Edit:

It's possible to run MongoDB as a 1-node replica set, although I'm not sure what's the difference between a standalone and a 1-node replica set.
See my post below.

In any case, to use the started transaction the insertion code must receive the session as a parameter:

entities.InsertOne(session, new MyEntity { Name = "Entity" });

With these 2 change now the transaction works.

Body:
I found a solution, although not sure what the consequences are, maybe someone can point it out:
It seems it's possible to use Mongo DB as a 1-node replica set (instead of a standalone) by simply adding the following in the mongod.cfg file:

replication:
   replSetName: rs1

Also, thanks to the following link the code should use the correct overload of InsertOne() which receives the session as the first parameter (see the edit on the original post):

multiple document transaction not working in c# using mongodb 4.08 community server


问:
Convert array to key value object
I have this kind of array

```<code>['item one', 'item two', 'item three']
</code>```

Ad would like to convert it to an object like this;

```<code>{
"name": 'item one',
"name": 'item two',
"name": 'item three'
}
</code>```

I have tried looping through and creating a default key which i feel am not doing the right way

```<code>let arr = ['item one', 'item two', 'item three']
let obj = {};
arr.forEach((cv) => {
  obj["name"] = cv;
}
console.log(obj)
</code>```

But this just returns an obj with the last value like this;

```<code>{
"name": 'item three'
}
</code>```

答:
why same keys? for an object, keys should be unique.

instead, you can try this,

```<code>const arr = ['one', 'two', 'three' ]

let newArr = arr.map(item => {
    return { name: item } })
</code>```

result

```<code>newArr = [
 { name: 'one' },
 { name: 'two' },
 { name: 'three' },
]
</code>```

Title: Convert array to key value object

Body:
I have this kind of array

['item one', 'item two', 'item three']

Ad would like to convert it to an object like this;

{
"name": 'item one',
"name": 'item two',
"name": 'item three'
}

I have tried looping through and creating a default key which i feel am not doing the right way

let arr = ['item one', 'item two', 'item three']
let obj = {};
arr.forEach((cv) => {
  obj["name"] = cv;
}
console.log(obj)

But this just returns an obj with the last value like this;

{
"name": 'item three'
}

Body:
why same keys? for an object, keys should be unique.

instead, you can try this,

const arr = ['one', 'two', 'three' ]

let newArr = arr.map(item => {
    return { name: item } })

result

newArr = [
 { name: 'one' },
 { name: 'two' },
 { name: 'three' },
]


问:
Validating if variable is int
I have a script to create vlan in cisco switches, and I need the user to input a number to the script.

I'm having trouble to make the script validate if the input is a number(must be int) and if the number is inside the range 2~4094, before it moves to the next steps.

I already wrote the rest of the script.

答:
When the function below return True, you can do the Math you need to do with the number.</p>

```<code>def as_int_in_range(value,range):
    try:
        value = int(value)
        if value >= range[0] and value <= range[1]:
            return True,value
        else:
            return False,None
    except ValueError:
        return False,None

is_int,val = as_int_in_range('12',(10,100))
if is_int:
    # do something with 'val' assuming it is int in the range
else:
    # do something  else
</code>```

Title: Validating if variable is int

Body:
When the function below return True, you can do the Math you need to do with the number.

def as_int_in_range(value,range):
    try:
        value = int(value)
        if value >= range[0] and value <= range[1]:
            return True,value
        else:
            return False,None
    except ValueError:
        return False,None

is_int,val = as_int_in_range('12',(10,100))
if is_int:
    # do something with 'val' assuming it is int in the range
else:
    # do something  else


问:
Get values from 'composed Annotations' in Spring
With Spring, you can have some kind of composed annotations. A prominent example is the @SpringBootApplication-annotation, which is a composite of an  @Configuration, @EnableAutoConfiguration and @ComponentScan.

I am trying to get all Beans that are affected by a certain annotation, i.e. ComponentScan.

Following this answer, I am using the following code:

```<code>for (T o : applicationContext.getBeansWithAnnotation(ComponentScan.class).values()) {
    ComponentScan ann = (ComponentScan) o.getClass().getAnnotation(ComponentScan.class);
    ...
}
</code>```

which does not work, since not all beans, returned by getBeansWithAnnotation(ComponentScan.class) are indeed annotated with that annotation, since those that are e.g. annotated with @SpringBootApplication are (usually) not.

Now I am looking for some kind of generic way, to retrieve the value of an annotation, even when it is only added as piece of another annotation.
How can I do this?

答:
it may be CglibProxy. so you can not directly get the Annotation.

```<code>ClassUtils.isCglibProxyClass(o)
</code>```

for more see this

edit,you can add your logic code. find the ComponentScan.

```<code>if (ClassUtils.isCglibProxyClass(o.getClass())) {
            Annotation[] annotations = ClassUtils.getUserClass(o).getAnnotations();
            for (Annotation annotation : annotations) {
                ComponentScan annotation1 = annotation.annotationType().getAnnotation(ComponentScan.class);
// in my test code , ComponentScan can get here.for @SpringBootApplication
                System.out.println(annotation1);
            }

        }
</code>```

Body:
With Spring, you can have some kind of composed annotations. A prominent example is the @SpringBootApplication-annotation, which is a composite of an  @Configuration, @EnableAutoConfiguration and @ComponentScan.

I am trying to get all Beans that are affected by a certain annotation, i.e. ComponentScan.

Following this answer, I am using the following code:

for (T o : applicationContext.getBeansWithAnnotation(ComponentScan.class).values()) {
    ComponentScan ann = (ComponentScan) o.getClass().getAnnotation(ComponentScan.class);
    ...
}

which does not work, since not all beans, returned by getBeansWithAnnotation(ComponentScan.class) are indeed annotated with that annotation, since those that are e.g. annotated with @SpringBootApplication are (usually) not.

Now I am looking for some kind of generic way, to retrieve the value of an annotation, even when it is only added as piece of another annotation.
How can I do this?

Body:
it may be CglibProxy. so you can not directly get the Annotation.

ClassUtils.isCglibProxyClass(o)

for more see this

edit,you can add your logic code. find the ComponentScan.

if (ClassUtils.isCglibProxyClass(o.getClass())) {
            Annotation[] annotations = ClassUtils.getUserClass(o).getAnnotations();
            for (Annotation annotation : annotations) {
                ComponentScan annotation1 = annotation.annotationType().getAnnotation(ComponentScan.class);
// in my test code , ComponentScan can get here.for @SpringBootApplication
                System.out.println(annotation1);
            }

        }


问:
string array to datarow array
I would like to assign string of array to a datarow array

My code is as follows

```<code>protected void btnGenerate_Click(object sender, EventArgs e)
{
    DataRow[] dRow;
    foreach (GridViewRow grRow in grdACH.Rows)
    {
        CheckBox chkItem = (CheckBox)grRow.FindControl("checkRec");
        if (chkItem.Checked)
        {
            chkItm = true;
            chkcnt++;
            strBankTypeID += ((Label)grRow.FindControl("lblBankType")).Text.ToString();
            strBnkArray = strBankTypeID.Split(',');
            foreach (string str in strBnkArray)
            {
                //Here i have to assign my string of array to datarow
            }
        }
    }
}
</code>```

Can any one help me

答:
you'll want to set the GridViewRow.DataItem

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.dataitem.aspx

ContentLicense: CC BY-SA 3.0

Title: string array to datarow array

Body:
I would like to assign string of array to a datarow array

My code is as follows

protected void btnGenerate_Click(object sender, EventArgs e)
{
    DataRow[] dRow;
    foreach (GridViewRow grRow in grdACH.Rows)
    {
        CheckBox chkItem = (CheckBox)grRow.FindControl("checkRec");
        if (chkItem.Checked)
        {
            chkItm = true;
            chkcnt++;
            strBankTypeID += ((Label)grRow.FindControl("lblBankType")).Text.ToString();
            strBnkArray = strBankTypeID.Split(',');
            foreach (string str in strBnkArray)
            {
                //Here i have to assign my string of array to datarow
            }
        }
    }
}

Can any one help me


问:
Read document from list collection mongodb
db(database).listCollection().toArray(function (error, isListCollection){if(error){response.json(error.message)}else if(isListCollection){for(var i = 0; i < isListCollection.length; i++){const listColl = isListcoll.name; db(database).collection(listColl, (error, data) => { if(errr){responden.json(error.message)}else if(data){respons.json(data)});}

How to loop and push the respon data to Json file. Thanks

答: Are you trying to take backup? If yes there is a command mongoexport you can use to get response directly in json format. It is  provided by mongo </p>


问:
What is the different?
I can't find the different between these codes as below:

1. Sample 1

```<code>modules = ["os", "sys", "random"]
def intersection_sets(modules):
    #for module in modules:
    sets = [set(dir(__import__(module))) for module in modules]
    return set.intersection(*sets)

a = intersection_sets(modules)
print(a)
</code>```

2. Sample 2

```<code>print(100*"=")
modules = ['os', 'sys', 'random']

def intersection_sets(modules):
    sets = [set(dir(__import__(module))) for module in modules]
    return set.intersection(*sets)

print(intersection_sets(modules))
</code>```

答:
```<code>a = intersection_sets(modules)
print(a)
</code>```

Above code, set the value returned by intersection_sets to a.

Below code, display the value returned by intersection_sets

```<code>print(intersection_sets(modules))
</code>```

Title: What is the different?

Body:
I can't find the different between these codes as below:

1. Sample 1

modules = ["os", "sys", "random"]
def intersection_sets(modules):
    #for module in modules:
    sets = [set(dir(__import__(module))) for module in modules]
    return set.intersection(*sets)

a = intersection_sets(modules)
print(a)

2. Sample 2

print(100*"=")
modules = ['os', 'sys', 'random']

def intersection_sets(modules):
    sets = [set(dir(__import__(module))) for module in modules]
    return set.intersection(*sets)

print(intersection_sets(modules))

Body:
a = intersection_sets(modules)
print(a)

Above code, set the value returned by intersection_sets to a.

Below code, display the value returned by intersection_sets

print(intersection_sets(modules))


问:
create or add section content at runtime
I want to add / create section content at runtime. I see example from tour de jewel mainContent.mxml but seems it is all section content is loaded when application start.

I want only load the section content when it's needed, not loading at all when application start.

So, when there is an update from individual section content, we don't need to refresh the browser.

```<code><j:ApplicationMainContent localId="main" hasTopAppBar="true" hasFooterBar="true" selectedContent = "welcome_panel">
    <local:WelcomeSection name="welcome_panel"/>
    <local:AlertPlayGround name="alert_panel"/>
    <local:ButtonPlayGround name="button_panel"/>
    <local:ImagePlayGround name="image_panel"/>
    <local:NumericStepperPlayGround name="numericstepper_panel"/>
    <local:DateComponentsPlayGround name="datecomponents_panel"/>
    <local:ComboBoxPlayGround name="combobox_panel"/>
    <local:CheckBoxPlayGround name="checkbox_panel"/>
    <local:MiscelaneaPlayGound name="miscelanea_panel"/>
    <local:HeadingsAndText name="text_panel"/>
    <local:LabelPlayGround name="label_panel"/>
    <local:ListPlayGround name="list_panel"/>
    <local:RadioButtonPlayGround name="radiobutton_panel"/>
    <local:SliderPlayGround name="slider_panel"/>
    <local:TextInputPlayGround name="textinput_panel"/>
    <local:GridPlayGround name="grid_panel"/>
    <local:CardPlayGround name="card_panel"/>
    <local:TablePlayGround name="tables_panel"/>
    <local:FormsValidationPlayGround name="form_validation_panel"/>
    <local:DropDownListPlayGround name="dropdownlist_panel"/>
    <local:SnackbarPlayGround name="snackbar_panel"/>
    <local:TabBarPlayGround name="tabbar_panel"/>
    <local:ViewStatesPlayGround name="viewstates_panel"/>
    <local:LayoutsPlayGround name="layouts_panel"/>
    <local:WizardPlayGround name="wizards_panel"/>
    <local:PopUpPlayGround name="popup_panel"/>
</j:ApplicationMainContent>
</code>```

Please help

答:
Imagine that you don't have declared the button panel in mxml. You can create it with the following code:

// This creates the ButtonPlayGround view
var bp:ButtonPlayGround = new ButtonPlayGround();
// then we need to assign the name
bp.name = "button_panel";
// finally you need to add to the ApplicationMainContent container
main.addElement(bp);
```

Now when you try to show that view, you'll get it since.

Body:
I want to add / create section content at runtime. I see example from tour de jewel mainContent.mxml but seems it is all section content is loaded when application start.

I want only load the section content when it's needed, not loading at all when application start.

So, when there is an update from individual section content, we don't need to refresh the browser.

<j:ApplicationMainContent localId="main" hasTopAppBar="true" hasFooterBar="true" selectedContent = "welcome_panel">
    <local:WelcomeSection name="welcome_panel"/>
    <local:AlertPlayGround name="alert_panel"/>
    <local:ButtonPlayGround name="button_panel"/>
    <local:ImagePlayGround name="image_panel"/>
    <local:NumericStepperPlayGround name="numericstepper_panel"/>
    <local:DateComponentsPlayGround name="datecomponents_panel"/>
    <local:ComboBoxPlayGround name="combobox_panel"/>
    <local:CheckBoxPlayGround name="checkbox_panel"/>
    <local:MiscelaneaPlayGound name="miscelanea_panel"/>
    <local:HeadingsAndText name="text_panel"/>
    <local:LabelPlayGround name="label_panel"/>
    <local:ListPlayGround name="list_panel"/>
    <local:RadioButtonPlayGround name="radiobutton_panel"/>
    <local:SliderPlayGround name="slider_panel"/>
    <local:TextInputPlayGround name="textinput_panel"/>
    <local:GridPlayGround name="grid_panel"/>
    <local:CardPlayGround name="card_panel"/>
    <local:TablePlayGround name="tables_panel"/>
    <local:FormsValidationPlayGround name="form_validation_panel"/>
    <local:DropDownListPlayGround name="dropdownlist_panel"/>
    <local:SnackbarPlayGround name="snackbar_panel"/>
    <local:TabBarPlayGround name="tabbar_panel"/>
    <local:ViewStatesPlayGround name="viewstates_panel"/>
    <local:LayoutsPlayGround name="layouts_panel"/>
    <local:WizardPlayGround name="wizards_panel"/>
    <local:PopUpPlayGround name="popup_panel"/>
</j:ApplicationMainContent>

Please help

Body:
Imagine that you don't have declared the button panel in mxml. You can create it with the following code:

// This creates the ButtonPlayGround view
var bp:ButtonPlayGround = new ButtonPlayGround();
// then we need to assign the name
bp.name = "button_panel";
// finally you need to add to the ApplicationMainContent container
main.addElement(bp);

Now when you try to show that view, you'll get it since.


问:
How to override "Minimum font size" in Firefox affecting text within svg?
When Firefox has "Minimum font size" set to 15, text within a svg becomes super large.

Haven't found anything similar to my problem. Appreciate any insight on this issue!

Note: It's an img where the src is a .svg file. https://codepen.io/amyrlam/pen/QPRmoY

Expected: Text within svg appears as normal.

Actual result: Text within svg is blown up.

How to set minimum font size: Firefox > Preferences > Language and Appearance > Fonts & Colors > Advanced > set Minimum font size to 15

答:
This appears to be an example generated by svg-term-cli.  As Robert Longson indicates in the comments above, this is a Firefox bug/regression to SVG text scaling when minimum font size is set.  If I understand the discussion correctly, FF incorrectly interprets a size of "5px" in the SVG coordinate space, before viewport scaling to final rendered size as being below the minimum font size.  Thus "5px" is scaled up to e.g. "15pt" on the SVG text elements, then scaled again for the actual SVG viewport and BIG LETTERS ENSUE.

Given that the FF bug has had a series of patch attempts that were backed out for causing other intermittent regressions, I'll suggest a workaround from the SVG side: attempt to adjust the scaling in the SVG's coordinate space to prevent the Firefox bug from triggering.  E.g. multiply the SVG coordinate system sizes by some scaling factor, so every text element is always "bigger" than reasonable minimum font size settings.  There's a tracking issue on svg-term-cli; I've added similar details to that discussion.


问:
Test both Handle and Handle<IFailed> methods with 1st level and 2nd Level Retry with Rebus
How to debug both Handle methods below?

I set breakpoints on both Handle method within Visual Studio, and send message to Subscriber1 queue, but both methods are not called under VS.

```<code>public class SomeHandler : IHandleMessages<string>, IHandleMessages<IFailed<string>>
{
    readonly IBus _bus;

    public SomeHandle(IBus bus)
    {
        _bus = bus;
    }

    public async Task Handle(string message)
    {
        // do stuff that can fail here...
    }

    public async Task Handle(IFailed<string> failedMessage)
    {
        await _bus.Advanced.TransportMessage.Defer(TimeSpan.FromSeconds(30));
    }
}
</code>```

Below is the message sent to Subscriber1.

I tried sending the message excluding either rbs2-msg-id or rbs2-msg-type, neither of them triggers the Handle method above.

```<code>{
  "body": "Test",
   //other fields
  "properties": {
    "rbs2-intent": "pub",
    "rbs2-msg-id": "cd57d735-3989-45b5-8a3c-e457fa61dc94",
    "rbs2-return-address": "publisher",
    "rbs2-senttime": "2019-05-27T15:07:25.1770000+01:00",
    "rbs2-sender-address": "publisher",
    "rbs2-msg-type": "System.String, mscorlib",
    "rbs2-corr-id": "cd57d735-3989-45b5-8a3c-e457fa61dc94",
    "rbs2-corr-seq": "0",
    "rbs2-content-type": "application/json;charset=utf-8"
  },
  //other fields
}
</code>```

Update 1

If an exception is thrown within Handle(string message), the method will be retried based on the 1st level try count. This is what we need.

However, Handle(IFailed<string> failedMessage) is not invoked, how to debug Handle(IFailed<string> failedMessage) like abvoe?

One note: when an exception is thrown within Handle(string message), IErrorHandler is NOT called, and AddTransportMessageForwarder is not called either, are these correct?

答:
Could you try and check your logs?

When you remove the rbs2-msg-id header, Rebus will immediately move the message to the dead-letter queue, simply refusing to handle it. This is because a message without a message ID cannot be tracked by Rebus' error tracker.

If you remove the rms2-msg-type header, the serializer will most likely throw an error and not deserialize the incoming message.

In both cases, the error will be output to the logger.

And in both cases, the message body (string in this case, but it could be any message type) cannot be constructed from the incomingbyte[], so Rebus cannot dispatch the message as eitherstringnotIFailed`.

Edit after Update 1:

If your 2nd level retries do not kick in, it's most likely because you haven't enabled them:

Configure.With(...)
    .(...)
    .Options(o => o.SimpleRetryStrategy(secondLevelRetriesEnabled: true))
    .Start();
```

IErrorHandler is called when it is time to move the message to the dead-letter queue. You should see it being called, when all delivery attempts have failed (5 normal delivery attempts + 5 2nd level delivery attempts).

If you've configured things the way I suggested it, AddTransportMessageForwarder is used in another bus instance, which receives messages from the error queue. When IErrorHandler has been called, and the failed messge has been forwarded to the queue error, then your transport message forwarder should be called.

Body:
How to debug both Handle methods below?

I set breakpoints on both Handle method within Visual Studio, and send message to Subscriber1 queue, but both methods are not called under VS.

public class SomeHandler : IHandleMessages<string>, IHandleMessages<IFailed<string>>
{
    readonly IBus _bus;

    public SomeHandle(IBus bus)
    {
        _bus = bus;
    }

    public async Task Handle(string message)
    {
        // do stuff that can fail here...
    }

    public async Task Handle(IFailed<string> failedMessage)
    {
        await _bus.Advanced.TransportMessage.Defer(TimeSpan.FromSeconds(30));
    }
}

Below is the message sent to Subscriber1.

I tried sending the message excluding either rbs2-msg-id or rbs2-msg-type, neither of them triggers the Handle method above.

{
  "body": "Test",
   //other fields
  "properties": {
    "rbs2-intent": "pub",
    "rbs2-msg-id": "cd57d735-3989-45b5-8a3c-e457fa61dc94",
    "rbs2-return-address": "publisher",
    "rbs2-senttime": "2019-05-27T15:07:25.1770000+01:00",
    "rbs2-sender-address": "publisher",
    "rbs2-msg-type": "System.String, mscorlib",
    "rbs2-corr-id": "cd57d735-3989-45b5-8a3c-e457fa61dc94",
    "rbs2-corr-seq": "0",
    "rbs2-content-type": "application/json;charset=utf-8"
  },
  //other fields
}

Update 1

If an exception is thrown within Handle(string message), the method will be retried based on the 1st level try count. This is what we need.

However, Handle(IFailed<string> failedMessage) is not invoked, how to debug Handle(IFailed<string> failedMessage) like abvoe?

One note: when an exception is thrown within Handle(string message), IErrorHandler is NOT called, and AddTransportMessageForwarder is not called either, are these correct?

Body:
Could you try and check your logs?

When you remove the rbs2-msg-id header, Rebus will immediately move the message to the dead-letter queue, simply refusing to handle it. This is because a message without a message ID cannot be tracked by Rebus' error tracker.

If you remove the rms2-msg-type header, the serializer will most likely throw an error and not deserialize the incoming message.

In both cases, the error will be output to the logger.

And in both cases, the message body (string in this case, but it could be any message type) cannot be constructed from the incomingbyte[], so Rebus cannot dispatch the message as eitherstringnotIFailed`.

Edit after Update 1:

If your 2nd level retries do not kick in, it's most likely because you haven't enabled them:

Configure.With(...)
    .(...)
    .Options(o => o.SimpleRetryStrategy(secondLevelRetriesEnabled: true))
    .Start();

IErrorHandler is called when it is time to move the message to the dead-letter queue. You should see it being called, when all delivery attempts have failed (5 normal delivery attempts + 5 2nd level delivery attempts).

If you've configured things the way I suggested it, AddTransportMessageForwarder is used in another bus instance, which receives messages from the error queue. When IErrorHandler has been called, and the failed messge has been forwarded to the queue error, then your transport message forwarder should be called.


问:
Custom transition between two UIViews
I have two views "A" and "B". A floats in the middle of the window (it's not full screen). B, the view which will replace A, is full screen. I'd like to write a custom transition that flips A to reveal B on the back side, but simultaneously scales the flipping rectangle so that when the flip is finished, B is full screen.

I've tried using the flip transitions available with transitionFromView:toView:duration:options:completion, but I can only get it to flip the entire screen instead of starting the flip with A's frame and ending with B's frame.

I know I can do 3D-like transforms to the view's layers, but I'm not sure which set of animation APIs I should use to accomplish this. One thing I tried is to modify the view's layer properties in the animations block of transitionWithView:duration:options:animations:completion: but that didn't work as it only seems to honor view property modifications.

Can someone point me in the right direction? I'd much appreciate it.

UPDATE: Here is my code thus far for this effect. You can see a video of what it does here: http://www.youtube.com/watch?v=-xNMD2fGRwg

```<code>CGRect frame = [[UIApplication easybookDelegate] rootViewController].view.bounds ;
float statusHeight = [UIApplication sharedApplication].statusBarFrame.size.height ;
frame.origin.y = statusHeight ;
frame.size.height -= statusHeight ;
self.view.frame = frame ; // self.view is view "B"

// Put the snapshot as thet topmost view of our view
UIImageView *imageView = [[UIImageView alloc] initWithImage:image] ; // image is a snapshot of view "A"
imageView.frame = self.view.bounds ;
[self.view addSubview:imageView] ;
[self.view bringSubviewToFront:imageView] ;

// Pre-transform our view (s=target/current, d=target-current)
CGAffineTransform transform = CGAffineTransformIdentity ;

// Translate our view
CGPoint center  = CGPointMake(screenOrigin.x + (image.size.width/2.0), screenOrigin.y + (image.size.height/2.0)) ;
float dX = center.x - self.view.center.x ;
float dY = center.y - self.view.center.y ;
NSLog( @"dx: %f, dy: %f" , dX, dY ) ;

transform = CGAffineTransformTranslate(transform, dX, dY) ;

// Scale our view
float scaleWFactor = image.size.width / self.view.frame.size.width ;
float scaleHFactor = image.size.height / self.view.frame.size.height ;
transform = CGAffineTransformScale(transform,scaleWFactor, scaleHFactor) ;

self.view.transform = transform ;

[[[UIApplication easybookDelegate] rootViewController].view addSubview:self.view] ;

// Perform the animation later since implicit animations don't seem to work due to
// view "B" just being added above and hasn't had a chance to become visible. Right now
// this is just on a timer for debugging purposes. It'll probably be moved elsewhere, probably
// to view "B"'s -didMoveToSuperview
double delayInSeconds = 0.3;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [UIView transitionWithView:self.view duration:3 options:UIViewAnimationOptionTransitionFlipFromRight| UIViewAnimationOptionCurveEaseOut animations:^(void)
        {
        [imageView removeFromSuperview] ;
        self.view.transform = CGAffineTransformIdentity ;
        }
        completion:^(BOOL finished){
                [self.view removeFromSuperview] ;
                [navController presentModalViewController:self animated:NO] ;
        }] ;
});

[imageView release];
</code>```

答:
This is an easy example that i made for you :-) Start with it... Try to understand it... Read Documentation and then you will be able to do what you want ;-)

```<code>- (void)moveTable:(UITableView *)table toPoint:(CGPoint)point excursion:(CGFloat)excursion {

[UIView beginAnimations:nil context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.5];
[table setCenter:point];

// scaling
CABasicAnimation *scalingAnimation = (CABasicAnimation *)[table.layer animationForKey:@"scaling"];
if (!scalingAnimation)
{
    scalingAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    scalingAnimation.duration=0.5/2.0f;
    scalingAnimation.autoreverses=YES;
    scalingAnimation.removedOnCompletion = YES;
    scalingAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    scalingAnimation.fromValue=[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0.0, 0.0, 0.0)];
    scalingAnimation.toValue=[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(excursion, 0.0, 0.0)];
}
[table.layer addAnimation:scalingAnimation forKey:@"scaling"];
[UIView commitAnimations];
</code>```

}

Title: Custom transition between two UIViews

Body:
I have two views "A" and "B". A floats in the middle of the window (it's not full screen). B, the view which will replace A, is full screen. I'd like to write a custom transition that flips A to reveal B on the back side, but simultaneously scales the flipping rectangle so that when the flip is finished, B is full screen.

I've tried using the flip transitions available with transitionFromView:toView:duration:options:completion, but I can only get it to flip the entire screen instead of starting the flip with A's frame and ending with B's frame.

I know I can do 3D-like transforms to the view's layers, but I'm not sure which set of animation APIs I should use to accomplish this. One thing I tried is to modify the view's layer properties in the animations block of transitionWithView:duration:options:animations:completion: but that didn't work as it only seems to honor view property modifications.

Can someone point me in the right direction? I'd much appreciate it.

UPDATE: Here is my code thus far for this effect. You can see a video of what it does here: http://www.youtube.com/watch?v=-xNMD2fGRwg

CGRect frame = [[UIApplication easybookDelegate] rootViewController].view.bounds ;
float statusHeight = [UIApplication sharedApplication].statusBarFrame.size.height ;
frame.origin.y = statusHeight ;
frame.size.height -= statusHeight ;
self.view.frame = frame ; // self.view is view "B"

// Put the snapshot as thet topmost view of our view
UIImageView *imageView = [[UIImageView alloc] initWithImage:image] ; // image is a snapshot of view "A"
imageView.frame = self.view.bounds ;
[self.view addSubview:imageView] ;
[self.view bringSubviewToFront:imageView] ;

// Pre-transform our view (s=target/current, d=target-current)
CGAffineTransform transform = CGAffineTransformIdentity ;

// Translate our view
CGPoint center  = CGPointMake(screenOrigin.x + (image.size.width/2.0), screenOrigin.y + (image.size.height/2.0)) ;
float dX = center.x - self.view.center.x ;
float dY = center.y - self.view.center.y ;
NSLog( @"dx: %f, dy: %f" , dX, dY ) ;

transform = CGAffineTransformTranslate(transform, dX, dY) ;

// Scale our view
float scaleWFactor = image.size.width / self.view.frame.size.width ;
float scaleHFactor = image.size.height / self.view.frame.size.height ;
transform = CGAffineTransformScale(transform,scaleWFactor, scaleHFactor) ;

self.view.transform = transform ;

[[[UIApplication easybookDelegate] rootViewController].view addSubview:self.view] ;

// Perform the animation later since implicit animations don't seem to work due to
// view "B" just being added above and hasn't had a chance to become visible. Right now
// this is just on a timer for debugging purposes. It'll probably be moved elsewhere, probably
// to view "B"'s -didMoveToSuperview
double delayInSeconds = 0.3;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [UIView transitionWithView:self.view duration:3 options:UIViewAnimationOptionTransitionFlipFromRight| UIViewAnimationOptionCurveEaseOut animations:^(void)
        {
        [imageView removeFromSuperview] ;
        self.view.transform = CGAffineTransformIdentity ;
        }
        completion:^(BOOL finished){
                [self.view removeFromSuperview] ;
                [navController presentModalViewController:self animated:NO] ;
        }] ;
});

[imageView release];

Body:
This is an easy example that i made for you :-) Start with it... Try to understand it... Read Documentation and then you will be able to do what you want ;-)

- (void)moveTable:(UITableView *)table toPoint:(CGPoint)point excursion:(CGFloat)excursion {

[UIView beginAnimations:nil context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.5];
[table setCenter:point];

// scaling
CABasicAnimation *scalingAnimation = (CABasicAnimation *)[table.layer animationForKey:@"scaling"];
if (!scalingAnimation)
{
    scalingAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    scalingAnimation.duration=0.5/2.0f;
    scalingAnimation.autoreverses=YES;
    scalingAnimation.removedOnCompletion = YES;
    scalingAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    scalingAnimation.fromValue=[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0.0, 0.0, 0.0)];
    scalingAnimation.toValue=[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(excursion, 0.0, 0.0)];
}
[table.layer addAnimation:scalingAnimation forKey:@"scaling"];
[UIView commitAnimations];

}


问:
actionEventListener ("click") does not work after inserting another item
I'm trying to add dynamically div elements inside filtersSpace div element and at the same time add an eventListener for each button inside the div elements but when I insert the second element the first one to be added does not work.

Can anybody help me ?

```<code>case "status":
        filtersSpace.innerHTML +=
            `<div class="card border-dark mx-2 my-3" style="width: 23%;">
                <h5 class="card-header">Status</h5>
                <div class="card-body">
                    <tr>
                        <select class="custom-select mr-sm-2" id="${'statusInput' + statusFilterCounter.toString(10)}">
                            <option selected value="Solved">Solved</option>
                            <option value="Open">Open</option>
                            <option value="Pending">Pending</option>
                        </select>
                    </tr>
                    <tr>
                        <button type="button" class="btn btn-dark my-2" style="width: 100%;"
                        id="${'statusActionButton' + statusFilterCounter.toString(10)}">
                            Filter
                        </button>
                        <button type="button" class="btn btn-outline-dark my-2" style="width: 100%;"
                        id="${'statusCancelButton' + statusFilterCounter.toString(10)}">
                            Cancel
                        </button>
                    </tr>
                </div>
            </div>`;
        defineFilter(
            "status",
            document.getElementById("statusInput" + statusFilterCounter.toString(10)),
            document.getElementById("statusActionButton" + statusFilterCounter.toString(10)),
            document.getElementById("statusCancelButton" + statusFilterCounter.toString(10))
        );
        statusFilterCounter += 1;
        statusLink.disabled = true;
        break;
</code>```

...

```<code>function defineFilter(filterType, input, actionButton, cancelButton) {
actionButton.addEventListener("click",
    function () {
        filters.push({filterType : filterType, value : input.value});
        actionButton.disabled = true;
        print();
        getDataFromJSon();
    }
);
cancelButton.addEventListener("click",
    function () {
        var quantity = this.id.charAt(this.id.length - 1);
        var counter = 0;
        for (var i = 0; i < filters.length; i++){
            if(filters[i].filterType == filterType){
                console.log(">>>");
                if(counter == quantity){
                    filters.splice(i, 1);
                    print();
                    getDataFromJSon();
                    break;
                }
                counter += 1;
            }
        }
        actionButton.disabled = false;
    }
);}
</code>```

答:
Use event delegation for dynamically added elements.

See below how we use e.target.matches([CSS Selector]) to decide what to do.

const newAdd = () => {
  const div = document.createElement('div');
  div.innerHTML = `<button class='btn'>Click Me</button>`;
  document.querySelector('.container').appendChild(div);
}

document.addEventListener('click', (e) => {
  if(e.target.matches('.btn')) {
    console.log('I was clicked !!!');
  }

  if(e.target.matches('#add')) {
    newAdd();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container"></div>
<button id="add">Add</button></code>```

Body:
I'm trying to add dynamically div elements inside filtersSpace div element and at the same time add an eventListener for each button inside the div elements but when I insert the second element the first one to be added does not work.

Can anybody help me ?

case "status":
        filtersSpace.innerHTML +=
            `

Status

                        <select class="custom-select mr-sm-2" id="${'statusInput' + statusFilterCounter.toString(10)}">
                            <option selected value="Solved">Solved</option>
                            <option value="Open">Open</option>
                            <option value="Pending">Pending</option>
                        </select>

                        <button type="button" class="btn btn-dark my-2" style="width: 100%;"
                        id="${'statusActionButton' + statusFilterCounter.toString(10)}">
                            Filter
                        </button>
                        <button type="button" class="btn btn-outline-dark my-2" style="width: 100%;"
                        id="${'statusCancelButton' + statusFilterCounter.toString(10)}">
                            Cancel
                        </button>

`;
        defineFilter(
            "status",
            document.getElementById("statusInput" + statusFilterCounter.toString(10)),
            document.getElementById("statusActionButton" + statusFilterCounter.toString(10)),
            document.getElementById("statusCancelButton" + statusFilterCounter.toString(10))
        );
        statusFilterCounter += 1;
        statusLink.disabled = true;
        break;

...

function defineFilter(filterType, input, actionButton, cancelButton) {
actionButton.addEventListener("click",
    function () {
        filters.push({filterType : filterType, value : input.value});
        actionButton.disabled = true;
        print();
        getDataFromJSon();
    }
);
cancelButton.addEventListener("click",
    function () {
        var quantity = this.id.charAt(this.id.length - 1);
        var counter = 0;
        for (var i = 0; i < filters.length; i++){
            if(filters[i].filterType == filterType){
                console.log(">>>");
                if(counter == quantity){
                    filters.splice(i, 1);
                    print();
                    getDataFromJSon();
                    break;
                }
                counter += 1;
            }
        }
        actionButton.disabled = false;
    }
);}

Body:
Use event delegation for dynamically added elements.

See below how we use e.target.matches([CSS Selector]) to decide what to do.

const newAdd = () => {
  const div = document.createElement('div');
  div.innerHTML = `<button class='btn'>Click Me</button>`;
  document.querySelector('.container').appendChild(div);
}

document.addEventListener('click', (e) => {
  if(e.target.matches('.btn')) {
    console.log('I was clicked !!!');
  }

  if(e.target.matches('#add')) {
    newAdd();
  }
});

<div class="container"></div>
<button id="add">Add</button>


问:
D3, Vue, and Typescript: how to fix common errors for "Expected 1 arguments, but got 0" and "Object is possibly 'null'
Disclaimer: I am new to Typescript. Feel free to link docs to read up more on. I have reviewed the errors in isolation (outside the context of d3) but those solutions did not fix it.

I have a mixin:

```<code>import Vue from 'vue';
import { Component, Mixin, Mixins } from 'vue-mixin-decorator';
import { Prop } from 'vue-property-decorator';

import CoreMixin from './core';
import * as d3 from 'd3';

@Mixin
export default class BandAxis extends Mixins<CoreMixin>(CoreMixin) {
  // relevant props
  @Prop({}) private sizeTo!: string;
  @Prop({default: () => ( ['one', 'two', 'three'] )}) private labels!: string[];
  // lots of other props props

  // relevant code
  get scale() {
    return d3.scaleBand()
      .domain(this.labels)
      .rangeRound([0, this.width])
      .padding(0.1);
  }

  get axis() {
    return d3.axisBottom()
      .scale(this.scale)
      .ticks(this.labels.length);
  }
  private bbox() {
    const sel = d3.select(`#${this.sizeTo}`);
    if (sel.empty()) {
      return {
        width: 0,
        height: 0,
      };
    } else {
      return sel.node().getBoundingClientRect();
    }
  }
  // more stuff that isn't related
}

</code>```

Using this gives me:

```<code> Expected 1 arguments, but got 0.
  get axis() {
>  return d3.axisBottom()
</code>```

and:

```<code>Object is possibly 'null'.
  |       };
  |     } else {
> |       return sel.node().getBoundingClientRect();
  |              ^
  |     }
  |  }
</code>```

Any ideas?

答:
The first message indicates that the call to d3.axisBottom is missing an argument. It expects an AxisScale<Domain> argument.

The second message is warning you that sel can be null. It is treated as an error when compiling with --strictNullChecks (or --strict) enabled. To address that, you could either:

disable strictNullCheck (not recommended)

add a null-check for sel: if (sel) { /* use sel */ }

use the non-null assertion operator: sel!.node().getBoundingClientRect()

Body:
Disclaimer: I am new to Typescript. Feel free to link docs to read up more on. I have reviewed the errors in isolation (outside the context of d3) but those solutions did not fix it.

I have a mixin:

import Vue from 'vue';
import { Component, Mixin, Mixins } from 'vue-mixin-decorator';
import { Prop } from 'vue-property-decorator';

import CoreMixin from './core';
import * as d3 from 'd3';

@Mixin
export default class BandAxis extends Mixins<CoreMixin>(CoreMixin) {
  // relevant props
  @Prop({}) private sizeTo!: string;
  @Prop({default: () => ( ['one', 'two', 'three'] )}) private labels!: string[];
  // lots of other props props

  // relevant code
  get scale() {
    return d3.scaleBand()
      .domain(this.labels)
      .rangeRound([0, this.width])
      .padding(0.1);
  }

  get axis() {
    return d3.axisBottom()
      .scale(this.scale)
      .ticks(this.labels.length);
  }
  private bbox() {
    const sel = d3.select(`#${this.sizeTo}`);
    if (sel.empty()) {
      return {
        width: 0,
        height: 0,
      };
    } else {
      return sel.node().getBoundingClientRect();
    }
  }
  // more stuff that isn't related
}

Using this gives me:

 Expected 1 arguments, but got 0.
  get axis() {
>  return d3.axisBottom()

and:

Object is possibly 'null'.
  |       };
  |     } else {
> |       return sel.node().getBoundingClientRect();
  |              ^
  |     }
  |  }

Any ideas?


问:
expect write to remote file over ssh
I have a script that is parsing a local file and execute remotely a new file created with the content of previous one.

```<code> Just an example: machine1 with the following command file content:
#cmd1
<blank line here>
#cmd5
hostname -f
reboot`
</code>```

Now the script will parse that file, will remove blanks and commented lines and create REMOTELY a new file with the new content:

```<code>proc _command {fh} {
    set fd [open "$fh" r]
    #set fp [open "/tmp/script_${fh}" w+]
    while { [gets $fd data] >= 0 } {
            if { [string length $data] > 0 } {
                    #skip commented & blank lines
                    if {[string match "#*" $data] || [string match "" $data]} {
                            continue
                    }
                    #puts $fp "$data"
                    send  "$data\r"
                    #send [exec echo $data >>/tmp/1.txt]
            }
    }
                    #close $fp
}
...
   spawn -noecho ssh -i $home/.ssh/.id_rsa -q -o StrictHostKeyChecking=no $user@$server
                    expect {
                            -re "($prompt)" {
                                            send "sudo su -\r"
                                            expect {
                                                    -re "# " {
                                                            _command $cfile
                                                            send "exit\r"
</code>```

Well, for now the part of the procedure that is writing to the file is commented as every time when I execute the script the file is created locally and not on remote machine.

It's something that I'm missing but can't figure out what...

答:
Do you really need expect for this? You're already using private key authentication, so I think all you really need is:</p>

```<code>sed -e '/^$/d' -e '/^#/d' local_file | ssh user@host sudo sh -c 'cat > remote_file'
</code>```

Title: expect write to remote file over ssh

Body:
I have a script that is parsing a local file and execute remotely a new file created with the content of previous one.

 Just an example: machine1 with the following command file content:
#cmd1
<blank line here>
#cmd5
hostname -f
reboot`

Now the script will parse that file, will remove blanks and commented lines and create REMOTELY a new file with the new content:

proc _command {fh} {
    set fd [open "$fh" r]
    #set fp [open "/tmp/script_${fh}" w+]
    while { [gets $fd data] >= 0 } {
            if { [string length $data] > 0 } {
                    #skip commented & blank lines
                    if {[string match "#*" $data] || [string match "" $data]} {
                            continue
                    }
                    #puts $fp "$data"
                    send  "$data\r"
                    #send [exec echo $data >>/tmp/1.txt]
            }
    }
                    #close $fp
}
...
   spawn -noecho ssh -i $home/.ssh/.id_rsa -q -o StrictHostKeyChecking=no $user@$server
                    expect {
                            -re "($prompt)" {
                                            send "sudo su -\r"
                                            expect {
                                                    -re "# " {
                                                            _command $cfile
                                                            send "exit\r"

Well, for now the part of the procedure that is writing to the file is commented as every time when I execute the script the file is created locally and not on remote machine.

It's something that I'm missing but can't figure out what...

Body:
Do you really need expect for this? You're already using private key authentication, so I think all you really need is:

sed -e '/^$/d' -e '/^#/d' local_file | ssh user@host sudo sh -c 'cat > remote_file'


问:
Is this program logically wrong or have a syntax that I can't seem to find?
I am helping an ex-teacher of mine and need help with this code. I am writing a python program that makes 30 unique cards. 10 are red, 10 are black and 10 are yellow. I have only used red in the code to make it easier to debug. I need to make them with the function which I believe works but then I need to then distribute them and display them at the end but the player's hands cannot be the same as each other and no duplicates in their own hand (as you would in an actual version of this). So I need to set a check system. I really can't find the problem and would appreciate a fresh set of eyes as this can easily fix it or it's out of my own league. Thanks for reading.

P.S
I know I have two player hands for each but that's to add to when a player wins a battle so I can compare who has the most cards and what ones for the end.

I have tried changing it up using different loops and writing it in pseudo code and comparing but don't know what's happening.

```<code>{import sys, random, time
this = sys.modules[__name__]

def redCardGen():
    for i in range(0,11, 1):
        setattr(this, 'R%s' % i, 'Red Card %s' % i)

def blackCardGen():
    for i in range(0,11, 1):
        setattr(this, 'B%s' % i, 'Black Card %s' % i)

def yellowCardGen():
    for i in range(0,11, 1):
        setattr(this, 'Y%s' % i, 'Yellow Card %s' % i)

redCardGen()

blackCardGen()
yellowCardGen()

breaker = 0

player1Hand = []
player2Hand = []
WinnnerDeck = []
WinnerDeck2 = []

Red = [R1, R2, R3, R4, R5, R6, R7, R8, R9, R10]

play = input("Would you like to play the game?: ")
if(play == "yes"):
    print("Okay, then lets play!")
else:
    exit()
for i in range(0,6, 1):
    player1Hand.append(random.choice(Red))
    player2Hand.append(random.choice(Red))
breaker1 = 0
while(breaker1 == 0):
    if (player1Hand != 5):
        player1Hand.append(random.choice(Red))
        player2Hand.append(random.choice(Red))
    elif ((len(set(player1Hand))==1) and (len(set(player2Hand))==1)):
        player1Hand.pop()
        player2Hand.pop()
        player1Hand.append(random.choice(Red))
        player2Hand.append(random.choice(Red))
    elif ((len(set(player1Hand and player2Hand)) == 1)):
        player1Hand.pop()
        player2Hand.pop()
        player1Hand.append(random.choice(Red))
        player2Hand.append(random.choice(Red))
    else:
        breaker1 = 1

print(player1Hand)
print(player2Hand)}
</code>```

There are no errors so I don't think that it is a syntax problem but rather a logical error.
My expected outcome is to have two player hands with random cards in but none are the same.

答:
If you are going to simulate a deck of cards, it would be best to have a list that represents it so you can shuffle it and use a function that draws a card from from the top (and removes it):

```<code>import random

cardDeck    = [C+str(n+1) for C in "RBY" for n in range(10)]
player1Hand = []
player2Hand = []

# deal cards
random.shuffle(cardDeck)
for _ in range(5):
    player1Hand.append(cardDeck.pop())
    player2Hand.append(cardDeck.pop())

print(player1Hand) # ['Y3', 'B10', 'Y5', 'R2', 'Y8']
print(player2Hand) # ['Y10', 'B6', 'Y1', 'R9', 'R7']
</code>```

This approach will make it easier to draw more cards from the deck without worrying about duplicates.

Body:
I am helping an ex-teacher of mine and need help with this code. I am writing a python program that makes 30 unique cards. 10 are red, 10 are black and 10 are yellow. I have only used red in the code to make it easier to debug. I need to make them with the function which I believe works but then I need to then distribute them and display them at the end but the player's hands cannot be the same as each other and no duplicates in their own hand (as you would in an actual version of this). So I need to set a check system. I really can't find the problem and would appreciate a fresh set of eyes as this can easily fix it or it's out of my own league. Thanks for reading.

P.S
I know I have two player hands for each but that's to add to when a player wins a battle so I can compare who has the most cards and what ones for the end.

I have tried changing it up using different loops and writing it in pseudo code and comparing but don't know what's happening.

{import sys, random, time
this = sys.modules[__name__]

def redCardGen():
    for i in range(0,11, 1):
        setattr(this, 'R%s' % i, 'Red Card %s' % i)

def blackCardGen():
    for i in range(0,11, 1):
        setattr(this, 'B%s' % i, 'Black Card %s' % i)

def yellowCardGen():
    for i in range(0,11, 1):
        setattr(this, 'Y%s' % i, 'Yellow Card %s' % i)

redCardGen()

blackCardGen()
yellowCardGen()

breaker = 0

player1Hand = []
player2Hand = []
WinnnerDeck = []
WinnerDeck2 = []

Red = [R1, R2, R3, R4, R5, R6, R7, R8, R9, R10]

play = input("Would you like to play the game?: ")
if(play == "yes"):
    print("Okay, then lets play!")
else:
    exit()
for i in range(0,6, 1):
    player1Hand.append(random.choice(Red))
    player2Hand.append(random.choice(Red))
breaker1 = 0
while(breaker1 == 0):
    if (player1Hand != 5):
        player1Hand.append(random.choice(Red))
        player2Hand.append(random.choice(Red))
    elif ((len(set(player1Hand))==1) and (len(set(player2Hand))==1)):
        player1Hand.pop()
        player2Hand.pop()
        player1Hand.append(random.choice(Red))
        player2Hand.append(random.choice(Red))
    elif ((len(set(player1Hand and player2Hand)) == 1)):
        player1Hand.pop()
        player2Hand.pop()
        player1Hand.append(random.choice(Red))
        player2Hand.append(random.choice(Red))
    else:
        breaker1 = 1

print(player1Hand)
print(player2Hand)}

There are no errors so I don't think that it is a syntax problem but rather a logical error.
My expected outcome is to have two player hands with random cards in but none are the same.

Body:
If you are going to simulate a deck of cards, it would be best to have a list that represents it so you can shuffle it and use a function that draws a card from from the top (and removes it):

import random

cardDeck    = [C+str(n+1) for C in "RBY" for n in range(10)]
player1Hand = []
player2Hand = []

# deal cards
random.shuffle(cardDeck)
for _ in range(5):
    player1Hand.append(cardDeck.pop())
    player2Hand.append(cardDeck.pop())

print(player1Hand) # ['Y3', 'B10', 'Y5', 'R2', 'Y8']
print(player2Hand) # ['Y10', 'B6', 'Y1', 'R9', 'R7']

This approach will make it easier to draw more cards from the deck without worrying about duplicates.


问:
List imported modules from an imported module in Python 3
I'd like to have a list of the names and files of imported modules form an imported module, like:</p>

```<code>#!/usr/bin/python3

import importlib

module = importlib.import_module('someModule')

for mod in module.modules():
    print(mod.name)
    print(mod.file)
</code>```

答:
Python3 lets us pull in the module with exec(f'import {module_name}'), putting the result in globals()[module_name],
or we can assign mod = importlib.import_module(module_name).

To see what other modules were directly pulled in by that, use:

```<code>def is_module(x):
    return str(type(x)) == "<class 'module'>"

def show_deps(mod):
    for name in dir(mod):
        val = getattr(mod, name)
        if is_module(val):
            print(name, val.__file__)
</code>```

One could recurse through the tree to find transitive deps, if desired.

Body:
I'd like to have a list of the names and files of imported modules form an imported module, like:

#!/usr/bin/python3

import importlib

module = importlib.import_module('someModule')

for mod in module.modules():
    print(mod.name)
    print(mod.file)

Body:
Python3 lets us pull in the module with exec(f'import {module_name}'), putting the result in globals()[module_name],
or we can assign mod = importlib.import_module(module_name).

To see what other modules were directly pulled in by that, use:

def is_module(x):
    return str(type(x)) == "<class 'module'>"

def show_deps(mod):
    for name in dir(mod):
        val = getattr(mod, name)
        if is_module(val):
            print(name, val.__file__)

One could recurse through the tree to find transitive deps, if desired.


问:
How do i find out the Structure of a Java Object?
I am working with the HttpExchange class, and want to use the getAttribute function to get the POST parameters. If i just call the function and print the results it works. But there has to be some better way to access the returned object and get the contained data.

The Manual is here: http://download.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html#getAttribute%28java.lang.String%29

How can i access the Object? Which methods does it have?

答:
I'm not familiar with this API either. The request POST parameters should be available in raw, unparsed form from getResponseBody(). However, if you know that the getAttribute method will contain the data you need, but you don't know which class it will have (I don't know how you would know the former without knowing the latter, but anyway), you can use reflection to print the name of the class:

```<code>System.out.println (foo.getAttribute("name").getClass ());
</code>```

If it turns out to be an internal, undocumented class, you can then use more reflection (or other techniques) to look at the class hierarchy until you find a publicly-documented class or interface that you can use.

But this shouldn't be necessary because what you need should be documented somewhere.

Body:
I'm not familiar with this API either. The request POST parameters should be available in raw, unparsed form from getResponseBody(). However, if you know that the getAttribute method will contain the data you need, but you don't know which class it will have (I don't know how you would know the former without knowing the latter, but anyway), you can use reflection to print the name of the class:

System.out.println (foo.getAttribute("name").getClass ());

If it turns out to be an internal, undocumented class, you can then use more reflection (or other techniques) to look at the class hierarchy until you find a publicly-documented class or interface that you can use.

But this shouldn't be necessary because what you need should be documented somewhere.


问:
How do I redirect from page to page in PHP 7?
I'm making an e-commerce site in PHP 7 and HTML 5. When I enter login details, admin.php just refreshes and does not redirect to index.php, as it should.

I've already tried using actual cookies, although I would prefer to just use session cookies for security reasons.

```<code>ADMIN LOGIN.php CODE
<?php
session_start();
if(isset($_SESSION["manager"])){
  header("location: index.php");
  exit();
}
?>
<?php
if (isset($_POST["username"])&&isset($_POST["password"])){
  $manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]);
  $password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]);

  include "../storescripts/connect_to_mysql.php";
  //$sqlquery =
  $sql = mysqli_query($con, "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1");
  $existCount=mysqli_num_rows($sql);
  if($existCount == 1){
    while($row = mysqli_fetch_array($sql)){
      $id = $row["id"];
    }
    $_SESSION["id"] = $id;
    $_SESION["manager"] = $manager;
    $_SESSION["password"] = $password;
    header("location: index.php");
    exit();
  } else {
    // code...
    echo 'Invalid Log In Credentials<br><br>';
    echo'<a href="index.php">Click Here To Re-Enter Credentials</a>';
    exit();
  }
}
?>

INDEX.php CODE
<?php
session_start();
if (!isset($_SESSION["manager"])){
  header("location: admin_login.php");
  exit();
}

$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]);

include "../storescripts/connect_to_mysql.php";
$sql = mysqli_query($con, "SELECT * FROM admin WHERE id='$managerID' AND     username='$manager' AND password='$password' LIMIT 1");
$existCount = mysqli_num_rows($sql);
if ($existCount == 0){
  header("location: ../index.php");
  exit();
}
?>
</code>```

I expected the page to redirect to index.php once the session cookie was set, but it does not do this.

答:
You must change your redirect calls. I'll recommend you to ecapsulate that logic in a function.

function redirectTo($uri)
{
    header('Location: '.$uri); // Where to redirect.
    http_response_code(301); // The response code to redirection.
    exit(); // End of script
}
```

<p>Then in your client code, to redirect to index.php</p>

<pre class="lang-php prettyprint-override"><code>redirectTo('/index.php'); // Note the removal of the dots. Your file must be relative to your document_root, not your filesystem.
</code>```

Done.

PS: As a side comment, and don't take this as a personal attack; this is not the right way to code in PHP. Please take a look at: https://phptherightway.com/. You must use proper HTTP abstractions nowadays. Check Zend Diactoros. :)

Body:
I'm making an e-commerce site in PHP 7 and HTML 5. When I enter login details, admin.php just refreshes and does not redirect to index.php, as it should.

I've already tried using actual cookies, although I would prefer to just use session cookies for security reasons.

ADMIN LOGIN.php CODE
<?php
session_start();
if(isset($_SESSION["manager"])){
  header("location: index.php");
  exit();
}
?>
<?php
if (isset($_POST["username"])&&isset($_POST["password"])){
  $manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]);
  $password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]);

  include "../storescripts/connect_to_mysql.php";
  //$sqlquery =
  $sql = mysqli_query($con, "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1");
  $existCount=mysqli_num_rows($sql);
  if($existCount == 1){
    while($row = mysqli_fetch_array($sql)){
      $id = $row["id"];
    }
    $_SESSION["id"] = $id;
    $_SESION["manager"] = $manager;
    $_SESSION["password"] = $password;
    header("location: index.php");
    exit();
  } else {
    // code...
    echo 'Invalid Log In Credentials

';
    echo'Click Here To Re-Enter Credentials';
    exit();
  }
}
?>

INDEX.php CODE
<?php
session_start();
if (!isset($_SESSION["manager"])){
  header("location: admin_login.php");
  exit();
}

$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]);

include "../storescripts/connect_to_mysql.php";
$sql = mysqli_query($con, "SELECT * FROM admin WHERE id='$managerID' AND     username='$manager' AND password='$password' LIMIT 1");
$existCount = mysqli_num_rows($sql);
if ($existCount == 0){
  header("location: ../index.php");
  exit();
}
?>

I expected the page to redirect to index.php once the session cookie was set, but it does not do this.

Body:
You must change your redirect calls. I'll recommend you to ecapsulate that logic in a function.

function redirectTo($uri)
{
    header('Location: '.$uri); // Where to redirect.
    http_response_code(301); // The response code to redirection.
    exit(); // End of script
}

Then in your client code, to redirect to index.php

redirectTo('/index.php'); // Note the removal of the dots. Your file must be relative to your document_root, not your filesystem.

Done.

PS: As a side comment, and don't take this as a personal attack; this is not the right way to code in PHP. Please take a look at: https://phptherightway.com/. You must use proper HTTP abstractions nowadays. Check Zend Diactoros. :)


问:
How to perform the dynamic assignment of table name in sql query?
In the express js application, is it possible to assign the name of the table dynamically?

The code is as follows

```<code>let table_name = 'fields'

await connection.query(`INSERT INTO ? (name,description) values ('user','user field')`);

</code>```

This gives an error in the sql syntax as the query which is executed has the quotes around the table name like this.

```<code>INSERT INTO 'fields' (name,description) values ('user','user field');
</code>```

答:
Table names and column names cannot be parameterized for similar reasons that you can't parameterize a variable name in a programming language; they're part of the fixed structure of a program. If table and column names were allowed to be parameterized then several optimisations that are possible to make when you know the structure of input and output data in advance would no longer be viable

The only thing you can do is construct your SQL in a string, using concatenation, and execute it that way. Take great care when doing so; do not allow a potentially hostile user to supply any values that you concatenate into the string without checking their validity first

Body:
In the express js application, is it possible to assign the name of the table dynamically?

The code is as follows

let table_name = 'fields'

await connection.query(`INSERT INTO ? (name,description) values ('user','user field')`);

This gives an error in the sql syntax as the query which is executed has the quotes around the table name like this.

INSERT INTO 'fields' (name,description) values ('user','user field');


问:
Filter dict to contain only certain keys?
I've got a dict that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out?

答:
If we want to make a new dictionary with selected keys removed, we can make use of dictionary comprehension

For example:

```<code>d = {
'a' : 1,
'b' : 2,
'c' : 3
}
x = {key:d[key] for key in d.keys() - {'c', 'e'}} # Python 3
y = {key:d[key] for key in set(d.keys()) - {'c', 'e'}} # Python 2.*
# x is {'a': 1, 'b': 2}
# y is {'a': 1, 'b': 2}
</code>```

Body:
If we want to make a new dictionary with selected keys removed, we can make use of dictionary comprehension

For example:

d = {
'a' : 1,
'b' : 2,
'c' : 3
}
x = {key:d[key] for key in d.keys() - {'c', 'e'}} # Python 3
y = {key:d[key] for key in set(d.keys()) - {'c', 'e'}} # Python 2.*
# x is {'a': 1, 'b': 2}
# y is {'a': 1, 'b': 2}


问:
How can I combine two HashMap objects containing the same types?
I have two HashMap objects defined like so:

```<code>HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
</code>```

I also have a third HashMap object:

```<code>HashMap<String, Integer> map3;
</code>```

How can I merge map1 and map2 together into map3?

答:
```<code>    HashMap<Integer,String> hs1 = new HashMap<>();
    hs1.put(1,"ram");
    hs1.put(2,"sita");
    hs1.put(3,"laxman");
    hs1.put(4,"hanuman");
    hs1.put(5,"geeta");

    HashMap<Integer,String> hs2 = new HashMap<>();
    hs2.put(5,"rat");
    hs2.put(6,"lion");
    hs2.put(7,"tiger");
    hs2.put(8,"fish");
    hs2.put(9,"hen");

    HashMap<Integer,String> hs3 = new HashMap<>();//Map is which we add

    hs3.putAll(hs1);
    hs3.putAll(hs2);

    System.out.println(" hs1 : " + hs1);
    System.out.println(" hs2 : " + hs2);
    System.out.println(" hs3 : " + hs3);
</code>```

Duplicate items will not be added(that is duplicate keys) as when we will print hs3 we will get only one value for key 5 which will be last value added and it will be rat.
**[Set has a property of not allowing the duplicate key but values can be duplicate]

Body:
I have two HashMap objects defined like so:

HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<String, Integer> map2 = new HashMap<String, Integer>();

I also have a third HashMap object:

HashMap<String, Integer> map3;

How can I merge map1 and map2 together into map3?

Body:
    HashMap<Integer,String> hs1 = new HashMap<>();
    hs1.put(1,"ram");
    hs1.put(2,"sita");
    hs1.put(3,"laxman");
    hs1.put(4,"hanuman");
    hs1.put(5,"geeta");

    HashMap<Integer,String> hs2 = new HashMap<>();
    hs2.put(5,"rat");
    hs2.put(6,"lion");
    hs2.put(7,"tiger");
    hs2.put(8,"fish");
    hs2.put(9,"hen");

    HashMap<Integer,String> hs3 = new HashMap<>();//Map is which we add

    hs3.putAll(hs1);
    hs3.putAll(hs2);

    System.out.println(" hs1 : " + hs1);
    System.out.println(" hs2 : " + hs2);
    System.out.println(" hs3 : " + hs3);

Duplicate items will not be added(that is duplicate keys) as when we will print hs3 we will get only one value for key 5 which will be last value added and it will be rat.
**[Set has a property of not allowing the duplicate key but values can be duplicate]


问:
UnboundLocalError: local variable 'zipped' referenced before assignment: Generator Error
I'm trying to build semantic segmentation model in keras. Since I use a custom data, I decided to write a custom generator to feed it to the keras function _.fit_generator and I have reached a dead-end in solving this generator error which says

```<code>UnboundLocalError: local variable 'zipped' referenced before assignment
</code>```

After some github and stackover research, I found that "https://github.com/keras-team/keras/issues/1638#issuecomment-182139908" ans is similar to my issue and even this solution doesn't seem to work throwing the same error again

```<code>def image_segmentation_generator( PROC_DATA, target_size,
batch_size , gen, do_augment=False):
    if gen=='train':
        images_path = PROC_DATA+'/train_images/images'
        segs_path = PROC_DATA+'/train_labels/labels'
    elif 'val':
        images_path = PROC_DATA+'/val_images/images'
        segs_path = PROC_DATA+'/val_labels/labels'

    img_seg_pairs = get_pairs_from_paths( images_path , segs_path)
    random.shuffle( img_seg_pairs )
    zipped = itertools.cycle( img_seg_pairs  )
    while True:

        X = []
        Y = []
        for _ in range( batch_size) :
            im , seg = next(zipped)
            im = cv2.imread(im , 1 )
            im = cv2.resize(im,(target_size[0],target_size[1]))
            seg = cv2.imread(seg , 0 )
            seg = ia.imresize_single_image(seg, (target_size),
interpolation='nearest')
            if do_augment:
                img , seg[:,:,0] = augment_seg( img , seg[:,:,0] )
            X.append( get_image_arr(im )  )
            Y.append( get_segmentation_arr( seg )  )

        yield np.array(X) , np.array(Y)

my_gen = image_segmentation_generator(...)
</code>```

my_gen.next() should give me the image and label frames with given batch size.

stack trace:
im , seg = next(zipped)
UnboundLocalError: local variable 'zipped' referenced before assignment

How can I fix this?

答:
For future reference.
I have found the workaround for this. It looks like the function object when created as a generator should be self-sustainable with no dependency on extra arguments. Hence the iterator's object with address should be passed along the function.

Zipped = object created before calling image_segmentation_generator_1

def image_segmentation_generator_1(zipped = Zipped, target_size=(1242, 378), batch_size=4, do_augment=False):
    while True:

```<code>    image_list = []
    label_list = []
    _image_list = []
    _label_list = []
    for _ in range((batch_size/2)) :
        im , seg = next(zipped)
        im = cv2.imread(im , 1 )
        im = cv2.resize(im,(target_size[0],target_size[1]))
        seg = cv2.imread(seg , 0 )
        seg = ia.imresize_single_image(seg, (target_size[0],target_size[1]), interpolation='nearest')
        if do_augment:
            _image_list , _label_list = augment_seg( im , seg)
        else :
            _image_list = im
            _label_list = seg
        _image_list = get_image_arr(_image_list)
        image_list = image_list + _image_list
        label_list = label_list + _label_list

    yield np.array(image_list) , np.array(label_list)
</code>```

Body:
I'm trying to build semantic segmentation model in keras. Since I use a custom data, I decided to write a custom generator to feed it to the keras function _.fit_generator and I have reached a dead-end in solving this generator error which says

UnboundLocalError: local variable 'zipped' referenced before assignment

After some github and stackover research, I found that "https://github.com/keras-team/keras/issues/1638#issuecomment-182139908" ans is similar to my issue and even this solution doesn't seem to work throwing the same error again

def image_segmentation_generator( PROC_DATA, target_size,
batch_size , gen, do_augment=False):
    if gen=='train':
        images_path = PROC_DATA+'/train_images/images'
        segs_path = PROC_DATA+'/train_labels/labels'
    elif 'val':
        images_path = PROC_DATA+'/val_images/images'
        segs_path = PROC_DATA+'/val_labels/labels'

    img_seg_pairs = get_pairs_from_paths( images_path , segs_path)
    random.shuffle( img_seg_pairs )
    zipped = itertools.cycle( img_seg_pairs  )
    while True:

        X = []
        Y = []
        for _ in range( batch_size) :
            im , seg = next(zipped)
            im = cv2.imread(im , 1 )
            im = cv2.resize(im,(target_size[0],target_size[1]))
            seg = cv2.imread(seg , 0 )
            seg = ia.imresize_single_image(seg, (target_size),
interpolation='nearest')
            if do_augment:
                img , seg[:,:,0] = augment_seg( img , seg[:,:,0] )
            X.append( get_image_arr(im )  )
            Y.append( get_segmentation_arr( seg )  )

        yield np.array(X) , np.array(Y)

my_gen = image_segmentation_generator(...)

my_gen.next() should give me the image and label frames with given batch size.

stack trace:
im , seg = next(zipped)
UnboundLocalError: local variable 'zipped' referenced before assignment

How can I fix this?

Body:
For future reference.
I have found the workaround for this. It looks like the function object when created as a generator should be self-sustainable with no dependency on extra arguments. Hence the iterator's object with address should be passed along the function.

Zipped = object created before calling image_segmentation_generator_1

def image_segmentation_generator_1(zipped = Zipped, target_size=(1242, 378), batch_size=4, do_augment=False):
    while True:

    image_list = []
    label_list = []
    _image_list = []
    _label_list = []
    for _ in range((batch_size/2)) :
        im , seg = next(zipped)
        im = cv2.imread(im , 1 )
        im = cv2.resize(im,(target_size[0],target_size[1]))
        seg = cv2.imread(seg , 0 )
        seg = ia.imresize_single_image(seg, (target_size[0],target_size[1]), interpolation='nearest')
        if do_augment:
            _image_list , _label_list = augment_seg( im , seg)
        else :
            _image_list = im
            _label_list = seg
        _image_list = get_image_arr(_image_list)
        image_list = image_list + _image_list
        label_list = label_list + _label_list

    yield np.array(image_list) , np.array(label_list)


问:
Sending and receiving protobuf data over Socket via boost asio
I want to send Protobuf data from my server to my client thanks to a TCP socket.

I tested my client and my server and the TCP connexion works.

So I try to serialize my data and send it by using a streambuf.

In my server :

```<code>void SendData(protobufType data){
        std::ostream ostream(&this->m_streambuf);
        data.SerializeToOstream(&ostream);

        std::cout<<"Send data"<< std::endl;
        boost::asio::write(this->m_socket, this->m_streambuf);
}

</code>```

In my client :

```<code>boost::asio::streambuf response;
boost::asio::read(socket, response);
std::cout<<"Data received"<< std::endl;
</code>```

I run 3 times my send function (I guess my data seams to be sent) but myclient seams to never get data ...

答:
Your client hangs on this line

```<code>boost::asio::read(socket, response);
</code>```

because above is the same as

```<code>boost::asio::read(socket, response, boost::asio::tranfer_all());
</code>```

what is described in the documentation.

You use read overload which takes completion condition. There are three kinds of these functors: transfer_all_t, transfer_exactly_t and transfer_at_least_t. Each of them has operator()() which returns 0 if read operation is completion - see reference.

The code for transfer_all_t::opeator()() is:

```<code>  template <typename Error>
  std::size_t operator()(const Error& err, std::size_t)
  {
    return !!err ? 0 : default_max_transfer_size;
  }
</code>```

so 0 is returned only if an error occurres.

transfer_at_least_t::operator()() is:

```<code>  template <typename Error>
  std::size_t operator()(const Error& err, std::size_t bytes_transferred)
  {
    return (!!err || bytes_transferred >= minimum_)
      ? 0 : default_max_transfer_size;
  }
</code>```

as you can see 0 is returned if either an error occurred or at least minimum_ bytes were transferred.

If you know that read with transfer_all ends when an error occurres, you can create this error to see read data. You can shutdown socket (for sending operation) on the server side or just close this socket. Then you can change read call to get error_code and you should see End of file as error:

```<code>boost::system::error_code ec;
boost::asio::read(socket,response,ec);
if (ec)
{
   cout << ec.message() << endl; // End of file
   // if ec is End of file you can see what data was read into streambuf
}
</code>```

You send a serialized object, so you know the size of this object, why not use the approach where you are sending the size of object (for example on 4 bytes) then after this header the content of object is sent later.

At the client side:

```<code>array<char,4> length;
boost::asio::read(socket,boost::asio::buffer(length));
int contentLen = /*conversion from length array into integer */
vector<char> content( contentLen );
boost::asio::read(socket,boost::asio::buffer(content));
</code>```

Body:
I want to send Protobuf data from my server to my client thanks to a TCP socket.

I tested my client and my server and the TCP connexion works.

So I try to serialize my data and send it by using a streambuf.

In my server :

void SendData(protobufType data){
        std::ostream ostream(&this->m_streambuf);
        data.SerializeToOstream(&ostream);

        std::cout<<"Send data"<< std::endl;
        boost::asio::write(this->m_socket, this->m_streambuf);
}

In my client :

boost::asio::streambuf response;
boost::asio::read(socket, response);
std::cout<<"Data received"<< std::endl;

I run 3 times my send function (I guess my data seams to be sent) but myclient seams to never get data ...

Body:
Your client hangs on this line

boost::asio::read(socket, response);

because above is the same as

boost::asio::read(socket, response, boost::asio::tranfer_all());

what is described in the documentation.

You use read overload which takes completion condition. There are three kinds of these functors: transfer_all_t, transfer_exactly_t and transfer_at_least_t. Each of them has operator()() which returns 0 if read operation is completion - see reference.

The code for transfer_all_t::opeator()() is:

  template <typename Error>
  std::size_t operator()(const Error& err, std::size_t)
  {
    return !!err ? 0 : default_max_transfer_size;
  }

so 0 is returned only if an error occurres.

transfer_at_least_t::operator()() is:

  template <typename Error>
  std::size_t operator()(const Error& err, std::size_t bytes_transferred)
  {
    return (!!err || bytes_transferred >= minimum_)
      ? 0 : default_max_transfer_size;
  }

as you can see 0 is returned if either an error occurred or at least minimum_ bytes were transferred.

If you know that read with transfer_all ends when an error occurres, you can create this error to see read data. You can shutdown socket (for sending operation) on the server side or just close this socket. Then you can change read call to get error_code and you should see End of file as error:

boost::system::error_code ec;
boost::asio::read(socket,response,ec);
if (ec)
{
   cout << ec.message() << endl; // End of file
   // if ec is End of file you can see what data was read into streambuf
}

You send a serialized object, so you know the size of this object, why not use the approach where you are sending the size of object (for example on 4 bytes) then after this header the content of object is sent later.

At the client side:

array<char,4> length;
boost::asio::read(socket,boost::asio::buffer(length));
int contentLen = /*conversion from length array into integer */
vector<char> content( contentLen );
boost::asio::read(socket,boost::asio::buffer(content));


问:
Unobtrusive, realtime notifications of new RSS entries
First, why I ask:  Now that reputation points on StackOverflow have real value (you can spend them on damn good answers by offering bounties) I'd like to monitor questions I might be able to answer and pounce on them!  (Also the fact that others answer my questions in real time makes StackOverflow amazingly handy, so it would be nice to reciprocate.)

To ask this as a more general question, not specific to StackOverflow:

What kind of delay will there typically be in an RSS feed vs polling and scraping?

What's a good way to display the notifications in a not-too-distracting way, such as Growl on Mac?  (It should also be easy to turn on and off, if it does get too distracting.)

(Or, for StackOverflow addicts, what's your setup for pouncing on new questions and can you generalize it for monitoring other web content in real time?)

答:
you could use a tcp-style backoff to handle feed polling. The more often someone posts, the more often you poll.

Google reader does this; the more I post on my blog, the faster each post shows up.

OwnerDisplayName: dreeves

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Ry


问:
How can I implement polymorphic decoding of JSON data in Swift 4?
I am attempting to render a view from data returned from an API endpoint. My JSON looks (roughly) like this:

```<code>{
  "sections": [
    {
      "title": "Featured",
      "section_layout_type": "featured_panels",
      "section_items": [
        {
          "item_type": "foo",
          "id": 3,
          "title": "Bisbee1",
          "audio_url": "http://example.com/foo1.mp3",
          "feature_image_url" : "http://example.com/feature1.jpg"
        },
        {
          "item_type": "bar",
          "id": 4,
          "title": "Mortar8",
          "video_url": "http://example.com/video.mp4",
          "director" : "John Smith",
          "feature_image_url" : "http://example.com/feature2.jpg"
        }
      ]
    }
  ]
}
</code>```

I have an object that represents how to layout a view in my UI. It looks like this:

```<code>public struct ViewLayoutSection : Codable {
    var title: String = ""
    var sectionLayoutType: String
    var sectionItems: [ViewLayoutSectionItemable] = []
}
</code>```

ViewLayoutSectionItemable is a protocol that includes, among other things, a title and a URL to an image to use in the layout.

However, the sectionItems array is actually made up of different types. What I'd like to do is instantiate each section item as an instance of its own class.

How do I setup the init(from decoder: Decoder) method for the ViewLayoutSection to let me iterate over the items in that JSON array and create an instance of the proper class in each case?

答:
A simpler version of @CodeDifferent's response, which addresses @JRG-Developer's comment. There is no need to rethink your JSON API; this is a common scenario. For each new ViewLayoutSectionItem you create, you only need to add one case and one line of code to the PartiallyDecodedItem.ItemKind enum and PartiallyDecodedItem.init(from:) method respectively.

This is not only the least amount of code compared to the accepted answer, it is more performant. In @CodeDifferent's option, you are required to initialize 2 arrays with 2 different representations of the data to get your array of ViewLayoutSectionItems. In this option, you still need to initialize 2 arrays, but get to only have one representation of the data by taking advantage of copy-on-write semantics.

Also note that it is not necessary to include ItemType in the protocol or the adopting structs (it doesn't make sense to include a string describing what type a type is in a statically typed language).

protocol ViewLayoutSectionItem {
    var id: Int { get }
    var title: String { get }
    var imageURL: URL { get }
}

struct Foo: ViewLayoutSectionItem {
    let id: Int
    let title: String
    let imageURL: URL

    let audioURL: URL
}

struct Bar: ViewLayoutSectionItem {
    let id: Int
    let title: String
    let imageURL: URL

    let videoURL: URL
    let director: String
}

private struct PartiallyDecodedItem: Decodable {
    enum ItemKind: String, Decodable {
        case foo, bar
    }
    let kind: Kind
    let item: ViewLayoutSectionItem

    private enum DecodingKeys: String, CodingKey {
        case kind = "itemType"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: DecodingKeys.self)
        self.kind = try container.decode(Kind.self, forKey: .kind)
        self.item = try {
            switch kind {
            case .foo: return try Foo(from: decoder)
            case .number: return try Bar(from: decoder)
        }()
    }
}

struct ViewLayoutSection: Decodable {
    let title: String
    let sectionLayoutType: String
    let sectionItems: [ViewLayoutSectionItem]

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.title = try container.decode(String.self, forKey: .title)
        self.sectionLayoutType = try container.decode(String.self, forKey: .sectionLayoutType)
        self.sectionItems = try container.decode([PartiallyDecodedItem].self, forKey: .sectionItems)
            .map { $0.item }
    }
}
```

<p>To handle the snake case -> camel case conversion, rather than manually type out all of the keys, you can simply set a property on <code>JSONDecoder</code></p>

<pre class="lang-swift prettyprint-override"><code>struct Sections: Decodable {
    let sections: [ViewLayoutSection]
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let sections = try decode(Sections.self, from: json)
    .sections
</code>```

Body:
I am attempting to render a view from data returned from an API endpoint. My JSON looks (roughly) like this:

{
  "sections": [
    {
      "title": "Featured",
      "section_layout_type": "featured_panels",
      "section_items": [
        {
          "item_type": "foo",
          "id": 3,
          "title": "Bisbee1",
          "audio_url": "http://example.com/foo1.mp3",
          "feature_image_url" : "http://example.com/feature1.jpg"
        },
        {
          "item_type": "bar",
          "id": 4,
          "title": "Mortar8",
          "video_url": "http://example.com/video.mp4",
          "director" : "John Smith",
          "feature_image_url" : "http://example.com/feature2.jpg"
        }
      ]
    }
  ]
}

I have an object that represents how to layout a view in my UI. It looks like this:

public struct ViewLayoutSection : Codable {
    var title: String = ""
    var sectionLayoutType: String
    var sectionItems: [ViewLayoutSectionItemable] = []
}

ViewLayoutSectionItemable is a protocol that includes, among other things, a title and a URL to an image to use in the layout.

However, the sectionItems array is actually made up of different types. What I'd like to do is instantiate each section item as an instance of its own class.

How do I setup the init(from decoder: Decoder) method for the ViewLayoutSection to let me iterate over the items in that JSON array and create an instance of the proper class in each case?

Body:
A simpler version of @CodeDifferent's response, which addresses @JRG-Developer's comment. There is no need to rethink your JSON API; this is a common scenario. For each new ViewLayoutSectionItem you create, you only need to add one case and one line of code to the PartiallyDecodedItem.ItemKind enum and PartiallyDecodedItem.init(from:) method respectively.

This is not only the least amount of code compared to the accepted answer, it is more performant. In @CodeDifferent's option, you are required to initialize 2 arrays with 2 different representations of the data to get your array of ViewLayoutSectionItems. In this option, you still need to initialize 2 arrays, but get to only have one representation of the data by taking advantage of copy-on-write semantics.

Also note that it is not necessary to include ItemType in the protocol or the adopting structs (it doesn't make sense to include a string describing what type a type is in a statically typed language).

protocol ViewLayoutSectionItem {
    var id: Int { get }
    var title: String { get }
    var imageURL: URL { get }
}

struct Foo: ViewLayoutSectionItem {
    let id: Int
    let title: String
    let imageURL: URL

    let audioURL: URL
}

struct Bar: ViewLayoutSectionItem {
    let id: Int
    let title: String
    let imageURL: URL

    let videoURL: URL
    let director: String
}

private struct PartiallyDecodedItem: Decodable {
    enum ItemKind: String, Decodable {
        case foo, bar
    }
    let kind: Kind
    let item: ViewLayoutSectionItem

    private enum DecodingKeys: String, CodingKey {
        case kind = "itemType"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: DecodingKeys.self)
        self.kind = try container.decode(Kind.self, forKey: .kind)
        self.item = try {
            switch kind {
            case .foo: return try Foo(from: decoder)
            case .number: return try Bar(from: decoder)
        }()
    }
}

struct ViewLayoutSection: Decodable {
    let title: String
    let sectionLayoutType: String
    let sectionItems: [ViewLayoutSectionItem]

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.title = try container.decode(String.self, forKey: .title)
        self.sectionLayoutType = try container.decode(String.self, forKey: .sectionLayoutType)
        self.sectionItems = try container.decode([PartiallyDecodedItem].self, forKey: .sectionItems)
            .map { $0.item }
    }
}

To handle the snake case -> camel case conversion, rather than manually type out all of the keys, you can simply set a property on JSONDecoder

struct Sections: Decodable {
    let sections: [ViewLayoutSection]
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let sections = try decode(Sections.self, from: json)
    .sections


问:
How to use NetworKit as a library in OMNeT++?
I am trying to build the C++ Core of NetworKit and I would like to use it as a library in OMNeT++. I followed the instructions from the README file to build the code with cmake and make all. Then, I tried to follow the instructions from the Use NetworKit as a library section, but the examples presented there are not consistent with the source code. In particular, the directory NetworKit/graph does not contain the Graph.h file. There is a Graph.hpp file, but in another directory. Also, the LibDemo.cpp file is missing. Is the README file outdated or I am missing something here?

EDIT

This is an update to my post above. Apparently the README file is not up to date. In any case, I built the C++ Core of NetworKit. I included the library in my OMNeT++ application as follows:

#include <graph/Graph.hpp>

In OMNeT++, in my project Properties | OMNeT++ | Makemake, and then selecting src | Options | Custom, I added the following:

```<code>INCLUDE_PATH += -I/path/to/networkit/include/networkit
LIBS += -L/path/to/networkit/build_lib -lnetworkit
</code>```

When I build my OMNeT++ project, I get the following error:

```<code>/path/to/networkit/include/networkit/graph/../Globals.hpp:42:14: error: expected unqualified-id
const double PI = 2.0*std::acos(0);
             ^
/path/to/omnetpp-5.4.1/include/omnetpp/simkerneldefs.h:47:19: note: expanded from macro 'PI'
#define PI        3.141592653589793
                  ^
</code>```

Can anyone help me with this? Thank you in advance!

答:
You're correct, the documentation is out of date, LibDemo.cpp was deleted here: https://github.com/kit-parco/networkit/commit/a5b2c1f0c9336e783c8fb0cd956326d960451914

If you want an older version where this part of the doc is still valid, that would be version 4.2 which is the last version with this file. Somebody made a clone of that version here for some reason: https://github.com/SharafMohamed/NetworKit

Body:
I am trying to build the C++ Core of NetworKit and I would like to use it as a library in OMNeT++. I followed the instructions from the README file to build the code with cmake and make all. Then, I tried to follow the instructions from the Use NetworKit as a library section, but the examples presented there are not consistent with the source code. In particular, the directory NetworKit/graph does not contain the Graph.h file. There is a Graph.hpp file, but in another directory. Also, the LibDemo.cpp file is missing. Is the README file outdated or I am missing something here?

EDIT

This is an update to my post above. Apparently the README file is not up to date. In any case, I built the C++ Core of NetworKit. I included the library in my OMNeT++ application as follows:

#include <graph/Graph.hpp>

In OMNeT++, in my project Properties | OMNeT++ | Makemake, and then selecting src | Options | Custom, I added the following:

INCLUDE_PATH += -I/path/to/networkit/include/networkit
LIBS += -L/path/to/networkit/build_lib -lnetworkit

When I build my OMNeT++ project, I get the following error:

/path/to/networkit/include/networkit/graph/../Globals.hpp:42:14: error: expected unqualified-id
const double PI = 2.0*std::acos(0);
             ^
/path/to/omnetpp-5.4.1/include/omnetpp/simkerneldefs.h:47:19: note: expanded from macro 'PI'
#define PI        3.141592653589793
                  ^

Can anyone help me with this? Thank you in advance!