问:
How would I overwrite the fav_genre of the user in this code
So I'm developing a code for a very basic music app, Every users information is saved into the database using the following format:

```<code>usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n' )
</code>```

now I want to read the existing information of a particular user and allow them to change their fav_genre. Below is my failed attempt to do so:

```<code>textfile = 'user_DB.txt'
def a():
    username = input('name?: ')
    with open(textfile, 'r+') as textIn:
        for line in textIn:
            information = line.split(" : ")
            if information[0] == username:
                print('Your current genre is:',information[5])
                new_genre = input('what would you like your new genre to be?')
                information[5] = new_genre
                textIn.write(information[5]=new_genre)#this line
                print('new genre is saved to',information[5])
                break
            elif information != username:
                print('Name not found, Please try again')
                a()
            else:print('invalid')
            break
    textIn.close()

a()
</code>```

The line with the comment #this line is where I think the error is occouring as I want to overwrite the previous value of fav_genre for that specific user with the new one.Any ideas on what I could do different to make this work?

答:
Basically change that line to:

```<code>textfile.write(' : '.join(information.values()) + '\n' )
</code>```

So full code:

```<code>textfile = 'user_DB.txt'
updated_textfile = 'user_DB_Updated.txt'
def a():
    username = input('name?: ')
    updated_lines = []
    with open(textfile, 'r+') as textIn:
        for line in textIn:
            information = line.split(" : ")
            updated_lines.append(line)
            if information[0] == username:
                print('Your current genre is:',information[5])
                new_genre = input('what would you like your new genre to be?')
                information[5] = new_genre
                updated_lines[-1] = ' : '.join(information) + '\n'
                print('new genre is saved to ',information[5])
                break
            elif information != username:
                print('Name not found, Please try again')
                a()
            else:print('invalid')
            break
    with open(updated_textfile, 'w+') as out_text:
        out_text.write(''.join(updated_lines))
    textfile.close()

a()
</code>```

Body:
So I'm developing a code for a very basic music app, Every users information is saved into the database using the following format:

usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n' )

now I want to read the existing information of a particular user and allow them to change their fav_genre. Below is my failed attempt to do so:

textfile = 'user_DB.txt'
def a():
    username = input('name?: ')
    with open(textfile, 'r+') as textIn:
        for line in textIn:
            information = line.split(" : ")
            if information[0] == username:
                print('Your current genre is:',information[5])
                new_genre = input('what would you like your new genre to be?')
                information[5] = new_genre
                textIn.write(information[5]=new_genre)#this line
                print('new genre is saved to',information[5])
                break
            elif information != username:
                print('Name not found, Please try again')
                a()
            else:print('invalid')
            break
    textIn.close()

a()

The line with the comment #this line is where I think the error is occouring as I want to overwrite the previous value of fav_genre for that specific user with the new one.Any ideas on what I could do different to make this work?

Body:
Basically change that line to:

textfile.write(' : '.join(information.values()) + '\n' )

So full code:

textfile = 'user_DB.txt'
updated_textfile = 'user_DB_Updated.txt'
def a():
    username = input('name?: ')
    updated_lines = []
    with open(textfile, 'r+') as textIn:
        for line in textIn:
            information = line.split(" : ")
            updated_lines.append(line)
            if information[0] == username:
                print('Your current genre is:',information[5])
                new_genre = input('what would you like your new genre to be?')
                information[5] = new_genre
                updated_lines[-1] = ' : '.join(information) + '\n'
                print('new genre is saved to ',information[5])
                break
            elif information != username:
                print('Name not found, Please try again')
                a()
            else:print('invalid')
            break
    with open(updated_textfile, 'w+') as out_text:
        out_text.write(''.join(updated_lines))
    textfile.close()

a()


来源: stackexchange

问:
Filtering a SelectList based on a User's Role
When assigning a user to a certain project, I'd like to limit the list of available users to people with the role "Project Manager". I could use some help with the syntax because I can't seem to get the LINQ syntax right for the Where method.

Create Action (GET)

```<code>// This is the unfiltered version
ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");
// Attempt to filter
ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")), "Id", "FullName");
</code>```

Create View

```<code><div class="form-group">
     @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })
         <div class="col-md-10">
             @Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })
         </div>
</div>
</code>```

I'm getting an error on the DropDownList saying

cannot compare elements of type 'System.Collections.Generic.ICollection'. Only primitive types, enumeration types and entity types are supported.

答:
Assuming this is Entity Framework you're using, you will notice that db.Users is of type DbSet, whereas db.Users.Where(...) is of type IQueryable. I should imagine you will achieve the desired result if you add .ToList(), like so:</p>

```<code>ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")).ToList(), "Id", "FullName");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When assigning a user to a certain project, I'd like to limit the list of available users to people with the role "Project Manager". I could use some help with the syntax because I can't seem to get the LINQ syntax right for the Where method.

Create Action (GET)

// This is the unfiltered version
ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");
// Attempt to filter
ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")), "Id", "FullName");

Create View

     @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })

             @Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })

I'm getting an error on the DropDownList saying

cannot compare elements of type 'System.Collections.Generic.ICollection'. Only primitive types, enumeration types and entity types are supported.

Body:
Assuming this is Entity Framework you're using, you will notice that db.Users is of type DbSet, whereas db.Users.Where(...) is of type IQueryable. I should imagine you will achieve the desired result if you add .ToList(), like so:

ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")).ToList(), "Id", "FullName");


问:
Ordering fields from find query with projection
I have a Mongo find query that works well to extract specific fields from a large document like...

```<code>db.profiles.find(
  { "profile.ModelID" : 'LZ241M4' },
  {
    _id : 0,
    "profile.ModelID" : 1,
    "profile.AVersion" : 2,
    "profile.SVersion" : 3
  }
);
</code>```

...this produces the following output.  Note how the SVersion comes before the AVersion in the document even though my projection asked for AVersion before SVersion.

```<code>{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "3.5", "AVersion" : "4.0.3" } }
{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "4.0", "AVersion" : "4.0.3" } }
</code>```

...the problem is that I want the output to be...

```<code>{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "3.5" } }
{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "4.0" } }
</code>```

What do I have to do get the Mongo JavaScript shell to present the results of my query in the field order that I specify?

答:
I have achieved it by projecting the fields using aliases, instead of including and excluding by 0 and 1s.
Try this:</p>

```<code>{
_id : 0,
"profile.ModelID" :"$profile.ModelID",
"profile.AVersion":"$profile.AVersion",
"profile.SVersion":"$profile.SVersion"
}
</code>```

Body:
I have a Mongo find query that works well to extract specific fields from a large document like...

db.profiles.find(
  { "profile.ModelID" : 'LZ241M4' },
  {
    _id : 0,
    "profile.ModelID" : 1,
    "profile.AVersion" : 2,
    "profile.SVersion" : 3
  }
);

...this produces the following output.  Note how the SVersion comes before the AVersion in the document even though my projection asked for AVersion before SVersion.

{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "3.5", "AVersion" : "4.0.3" } }
{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "4.0", "AVersion" : "4.0.3" } }

...the problem is that I want the output to be...

{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "3.5" } }
{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "4.0" } }

What do I have to do get the Mongo JavaScript shell to present the results of my query in the field order that I specify?

Body:
I have achieved it by projecting the fields using aliases, instead of including and excluding by 0 and 1s.
Try this:

{
_id : 0,
"profile.ModelID" :"$profile.ModelID",
"profile.AVersion":"$profile.AVersion",
"profile.SVersion":"$profile.SVersion"
}


问:
How to filter a sequence and retain evaluated pred values?
This is a scenario I encountered many times, yet didn't find an idiomatic approach for it...

Suppose one would like to use a self-defined self-pred function to filter a seq. This self-pred function returns nil for unwanted elements, and useful information for wanted elements. It is desirable to keep the evaluated self-pred values for these wanted elements.

My general solution is:

```<code>;; self-pred is a pred function which returns valuable info
;; in general, they are unique and can be used as key
(let [new-seq (filter self-pred aseq)]
   (zipmap (map self-pred new-seq) new-seq))
</code>```

Basically, it is to call self-pred twice on all wanted elements. I feel it is so ugly...

Wonder if there is any better ways. Much appreciated for any input!

答:
If self-pred guarantees no duplicate key creation for differing values then I'd reach for reduce (since assoc the same key twice will override the original key value pair):

```<code>(reduce #(if-let [k (self-pred %2)]
          (assoc %1 k %2)
          %1)
 {}
 aseq)
</code>```

Else we can use group-by to drive a similar result:

```<code>(dissoc (group-by self-pred aseq) nil)
</code>```

Although not the same since the values will be in vectors: {k1 [v1 ..], k2 [..], ..}. but this guarantees all values are kept.

Body:
This is a scenario I encountered many times, yet didn't find an idiomatic approach for it...

Suppose one would like to use a self-defined self-pred function to filter a seq. This self-pred function returns nil for unwanted elements, and useful information for wanted elements. It is desirable to keep the evaluated self-pred values for these wanted elements.

My general solution is:

;; self-pred is a pred function which returns valuable info
;; in general, they are unique and can be used as key
(let [new-seq (filter self-pred aseq)]
   (zipmap (map self-pred new-seq) new-seq))

Basically, it is to call self-pred twice on all wanted elements. I feel it is so ugly...

Wonder if there is any better ways. Much appreciated for any input!

Body:
If self-pred guarantees no duplicate key creation for differing values then I'd reach for reduce (since assoc the same key twice will override the original key value pair):

(reduce #(if-let [k (self-pred %2)]
          (assoc %1 k %2)
          %1)
 {}
 aseq)

Else we can use group-by to drive a similar result:

(dissoc (group-by self-pred aseq) nil)

Although not the same since the values will be in vectors: {k1 [v1 ..], k2 [..], ..}. but this guarantees all values are kept.


问:
How to check the type of a many-to-many-field in django?
How can you check the type of a many-to-many-field in django?

I wanted to do it this way:

```<code>import django
field.__class__ == django.db.models.fields.related.ManyRelatedManager
</code>```

This doesn't work, because the class ManyRelatedManager can't be found.
But if i do field.__class__ the output is django.db.models.fields.related.ManyRelatedManager

Why does it refer to a class that doesn't seem to exist and how can i bring it to work?

Many thanks for your help.

答:
(Using Django 1.11)

This question has become confusing, because the reported behavior is not the modern behavior for a related field. Example here, where JobTemplate is the model class, and credentials is a many-to-many related field:

```<code>>>> JobTemplate._meta.get_field('credentials').__class__
 django.db.models.fields.related.ManyToManyField
</code>```

Is it different if we inspect the _meta of an object?

```<code>>>> JobTemplate.objects.first()._meta.get_field('credentials').__class__
django.db.models.fields.related.ManyToManyField
</code>```

no.

So here's when I insert what I think is the most likely scenario of someone coming here. You have this:

```<code>>>> JobTemplate.objects.first().credentials
<django.db.models.fields.related_descriptors.ManyRelatedManager at 0x6f9b390>
</code>```

Note, this is what the OP had.

I will stipulate that the related model is Credential. I can check if this is a related credential manager!

```<code>>>> isinstance(JobTemplate.objects.first().credentials, Credential.objects.__class__)
True
</code>```

ManyToMany fields can be very hard to process, because the attribute kills itself and replaces itself with the manager sub-class. You could also cross-reference this information with the field obtained from get_field('credentials') to be extra sure. The above isinstance check could also erroneously pick up other managers that you have set on the model. However, this is still a valuable test to see if the attribute you have "quacks" how a ManyToMany field of that particular related model should.

Body:
How can you check the type of a many-to-many-field in django?

I wanted to do it this way:

import django
field.__class__ == django.db.models.fields.related.ManyRelatedManager

This doesn't work, because the class ManyRelatedManager can't be found.
But if i do field.__class__ the output is django.db.models.fields.related.ManyRelatedManager

Why does it refer to a class that doesn't seem to exist and how can i bring it to work?

Many thanks for your help.

Body:
(Using Django 1.11)

This question has become confusing, because the reported behavior is not the modern behavior for a related field. Example here, where JobTemplate is the model class, and credentials is a many-to-many related field:

>>> JobTemplate._meta.get_field('credentials').__class__
 django.db.models.fields.related.ManyToManyField

Is it different if we inspect the _meta of an object?

>>> JobTemplate.objects.first()._meta.get_field('credentials').__class__
django.db.models.fields.related.ManyToManyField

no.

So here's when I insert what I think is the most likely scenario of someone coming here. You have this:

>>> JobTemplate.objects.first().credentials
<django.db.models.fields.related_descriptors.ManyRelatedManager at 0x6f9b390>

Note, this is what the OP had.

I will stipulate that the related model is Credential. I can check if this is a related credential manager!

>>> isinstance(JobTemplate.objects.first().credentials, Credential.objects.__class__)
True

ManyToMany fields can be very hard to process, because the attribute kills itself and replaces itself with the manager sub-class. You could also cross-reference this information with the field obtained from get_field('credentials') to be extra sure. The above isinstance check could also erroneously pick up other managers that you have set on the model. However, this is still a valuable test to see if the attribute you have "quacks" how a ManyToMany field of that particular related model should.


问:
Excel VBA to split cell into multiple cells
Good afternoon,

I am having a big issue in my quest to learn VBA. Currently, my data is (as below) in a structure that sometimes contains multiple serial numbers belonging to a single part.

I have a VBA macro that I wrote which imports this data and formats it appropriately for a separate program. However, I am working on a sub that will allow me to go through and separate these serial numbers that are delimited by a comma.

For example:

But, I want it to look like this:

I found some code on this site (Split Cells Into Multiple Rows using Vb Code) which has helped, but I am having trouble with it: Here is what I have

```<code>Sub SplitSerial()
    Dim SN As String
    Dim i As Integer
    Dim numArray()

    SN = ActiveCell.Value
    numArray = Split(SN, " ")
    For LBound(numArray) To UBound(numArray)
        Cells(1, i + 1).Value = numArray(i)
        MsgBox numArray(i)
    Next i
End Sub
</code>```

The problem is, this spreadsheet can get pretty large (5,000+) rows, so I don't know how to have it loop through the column, and if it has a ",', split the serial numbers but copy the values from the remaining cells.

Any guidance, advice, or coaching would be greatly appreciated. I am trying very hard to learn VBA.

答:
Try this, which uses arrays so should speed things up. Have added some comments to briefly explain what the code is doing.</p>

```<code>Sub x()

Dim v, vOut(), i As Long, j As Long, k As Long, w

v = Sheet1.Range("A1").CurrentRegion.Value  'assumes starting data in A1 of sheet1
ReDim vOut(1 To UBound(v, 1) * 10, 1 To 3)  'output array, assumes no more than 10 serial numbers for each part

For i = LBound(v, 1) To UBound(v, 1)
    w = Split(v(i, 2), ",")         'split serial number by comma
    For j = LBound(w) To UBound(w)  'for each serial number
        k = k + 1
        vOut(k, 1) = v(i, 1)        'repeat part number
        vOut(k, 2) = w(j)           'add particular serial number
        vOut(k, 3) = v(i, 3)        'repeat price
    Next j
Next i

Sheet2.Range("A1").Resize(k, 3) = vOut  'output to A1 of sheet2.

End Sub
</code>```

Body:
Good afternoon,

I am having a big issue in my quest to learn VBA. Currently, my data is (as below) in a structure that sometimes contains multiple serial numbers belonging to a single part.

I have a VBA macro that I wrote which imports this data and formats it appropriately for a separate program. However, I am working on a sub that will allow me to go through and separate these serial numbers that are delimited by a comma.

For example:

But, I want it to look like this:

I found some code on this site (Split Cells Into Multiple Rows using Vb Code) which has helped, but I am having trouble with it: Here is what I have

Sub SplitSerial()
    Dim SN As String
    Dim i As Integer
    Dim numArray()

    SN = ActiveCell.Value
    numArray = Split(SN, " ")
    For LBound(numArray) To UBound(numArray)
        Cells(1, i + 1).Value = numArray(i)
        MsgBox numArray(i)
    Next i
End Sub

The problem is, this spreadsheet can get pretty large (5,000+) rows, so I don't know how to have it loop through the column, and if it has a ",', split the serial numbers but copy the values from the remaining cells.

Any guidance, advice, or coaching would be greatly appreciated. I am trying very hard to learn VBA.

Body:
Try this, which uses arrays so should speed things up. Have added some comments to briefly explain what the code is doing.

Sub x()

Dim v, vOut(), i As Long, j As Long, k As Long, w

v = Sheet1.Range("A1").CurrentRegion.Value  'assumes starting data in A1 of sheet1
ReDim vOut(1 To UBound(v, 1) * 10, 1 To 3)  'output array, assumes no more than 10 serial numbers for each part

For i = LBound(v, 1) To UBound(v, 1)
    w = Split(v(i, 2), ",")         'split serial number by comma
    For j = LBound(w) To UBound(w)  'for each serial number
        k = k + 1
        vOut(k, 1) = v(i, 1)        'repeat part number
        vOut(k, 2) = w(j)           'add particular serial number
        vOut(k, 3) = v(i, 3)        'repeat price
    Next j
Next i

Sheet2.Range("A1").Resize(k, 3) = vOut  'output to A1 of sheet2.

End Sub


问:
ClearCase: change branch type name?
I used mkbrtype BRANCH_NAME, checked out a few files, had some check-ins, etc. Now I discovered I had a typo in the branch name, and it looks pretty ugly. Is there a way I can change the branch name and still have all the versions/checkouts under it? I'm the only one using it.

答:
Following command may be useful</p>

```<code>$ cleartool rename brtype:OLD brtype:NEW
</code>```

ContentLicense: CC BY-SA 2.5

Title: ClearCase: change branch type name?

Body:
Following command may be useful

$ cleartool rename brtype:OLD brtype:NEW


问:
How to modify the behavior of a node in ns2 simulator?
I want to modify the behavior of a node in ns2 simulator. In particular, I have to modify a routing of a node inside a simulation of the dsr protocol.
I know that dsragent.cc is the class that manages the routing of this protocol. But if I have a tcl script with 10 nodes, called $node1,$node2...node$10, how to modify the behavior of $node5 in the dsr protocol? How to find the single behavior of that node?</p>

答:
i had worked with other routing protocol but i will mention some points ..may it be useful.

in order to access specific node object in c++  you need to know its address in tcl. then you may need to make modification in forward or recv function..
you can extract all  information you need form common,IP,DSR headers

```<code>DSRAgent::recv(Packet* packet, Handler*)
  /* handle packets with a MAC destination address of this host, or
     the MAC broadcast addr */
{
       hdr_sr *srh =  hdr_sr::access(packet);
      hdr_ip *iph =  hdr_ip::access(packet);
      hdr_cmn *cmh =  hdr_cmn::access(packet);
      p.dest = ID((Address::instance().get_nodeaddr(iph->daddr())),::IP);
      p.src = ID((Address::instance().get_nodeaddr(iph->saddr())),::IP);
</code>```

the following means.. if current node is the generator of the packet

```<code> if (p.src == net_id) {code}
</code>```

to select specific node object

```<code> if (net_id==ID("put the node address here", ::IP))     \\ notice net_id is a struct
     {
       your code here
     }
</code>```

you can assign node address from tcl
and this address will be passed to c++ by command function

```<code>DSRAgent::command(int argc, const char*const* argv)
.
.
 if (strcasecmp(argv[1], "addr") == 0)
    {
      int temp;
      temp = Address::instance().str2addr(argv[2]);
     net_id = ID(temp, ::IP);
     flow_table.setNetAddr(net_id.addr);
.
}
</code>```

regards

Body:
i had worked with other routing protocol but i will mention some points ..may it be useful.

in order to access specific node object in c++  you need to know its address in tcl. then you may need to make modification in forward or recv function..
you can extract all  information you need form common,IP,DSR headers

DSRAgent::recv(Packet* packet, Handler*)
  /* handle packets with a MAC destination address of this host, or
     the MAC broadcast addr */
{
       hdr_sr *srh =  hdr_sr::access(packet);
      hdr_ip *iph =  hdr_ip::access(packet);
      hdr_cmn *cmh =  hdr_cmn::access(packet);
      p.dest = ID((Address::instance().get_nodeaddr(iph->daddr())),::IP);
      p.src = ID((Address::instance().get_nodeaddr(iph->saddr())),::IP);

the following means.. if current node is the generator of the packet

 if (p.src == net_id) {code}

to select specific node object

 if (net_id==ID("put the node address here", ::IP))     \\ notice net_id is a struct
     {
       your code here
     }

you can assign node address from tcl
and this address will be passed to c++ by command function

DSRAgent::command(int argc, const char*const* argv)
.
.
 if (strcasecmp(argv[1], "addr") == 0)
    {
      int temp;
      temp = Address::instance().str2addr(argv[2]);
     net_id = ID(temp, ::IP);
     flow_table.setNetAddr(net_id.addr);
.
}

regards


问:
Angular 5 Child routing empty path overrides root empty path?
i tried the following setup.

The routing for the root:

```<code>const routes: Routes = [
    {path: 'home', loadChildren: 'app/home/home.module#HomeModule'},
    {path: 'note', loadChildren: 'app/note/note.module#NoteModule'},
    ...
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: '**', redirectTo: 'home', pathMatch: 'full'}
];

export const Routing: ModuleWithProviders = RouterModule.forRoot(routes);
</code>```

The routing for one child:

```<code>const routes: Routes = [
    {path: '', component: NoteContainerComponent},
    ...
];

export const NoteRouting: ModuleWithProviders = RouterModule.forChild(routes);
</code>```

So if i navigate to localhost:4200 i would expect to be redirected to localhost:4200/home but instead there is no url redirect happening but The note route is loaded. Shouldn't the empty note route only match if i do something like localhost:4200/note ? All routes in child routing should only apply if the parent of the child is loaded.

Is it not possible to have empty path on child routes?

答: So i finally found the issue, i had the modules wich i wanted to load lazy imported in my root module. This caused the issue, because the RouterModule.forChild was applied as it was .forRoot</p>

Body:
i tried the following setup.

The routing for the root:

const routes: Routes = [
    {path: 'home', loadChildren: 'app/home/home.module#HomeModule'},
    {path: 'note', loadChildren: 'app/note/note.module#NoteModule'},
    ...
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: '**', redirectTo: 'home', pathMatch: 'full'}
];

export const Routing: ModuleWithProviders = RouterModule.forRoot(routes);

The routing for one child:

const routes: Routes = [
    {path: '', component: NoteContainerComponent},
    ...
];

export const NoteRouting: ModuleWithProviders = RouterModule.forChild(routes);

So if i navigate to localhost:4200 i would expect to be redirected to localhost:4200/home but instead there is no url redirect happening but The note route is loaded. Shouldn't the empty note route only match if i do something like localhost:4200/note ? All routes in child routing should only apply if the parent of the child is loaded.

Is it not possible to have empty path on child routes?


问:
Java stream. Sum two fields in a stream of objects
I have something like this:

```<code>Integer totalIncome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getIncome()).sum();
Integer totalOutcome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getOutcome()).sum();
</code>```

How could I write that in one stream ? to collect f.e. Pair<Integer, Integer> with totalIncome and totalOutcome ?

EDITED:

Thank you guys for your comments, answers, and involvment. I would have a question about different approach to that problem using streams. What do you think about that:

```<code>final IncomeAndOutcome incomeAndOutcome = carDealer.getBrands()
                    .stream()
                    .map(Brand::getManufacturer)
                    .map(IncomeAndOutcome::of)
                    .reduce(IncomeAndOutcome.ZERO, IncomeAndOutcome::sum);

static class IncomeAndOutcome {

    private static final IncomeAndOutcome ZERO = of(0, 0);

    @Getter
    private final int income;

    @Getter
    private final int outcome;

    public static IncomeAndOutcome of(final int income, final int outcome) {
        return new IncomeAndOutcome(income, outcome);
    }

    public static IncomeAndOutcome of(final Manufacturer manufacturer) {
        return new IncomeAndOutcome(manufacturer.getIncome(), manufacturer.getOutcome());
    }

    IncomeAndOutcome(final int income, final int outcome) {
        this.income = income;
        this.outcome = outcome;
    }

    IncomeAndOutcome sum(final IncomeAndOutcome incomeAndOutcome) {
        return of(this.income + incomeAndOutcome.getIncome(), this.outcome + incomeAndOutcome.getOutcome());
    }
}
</code>```

答:
Without measuring correctly - everything is guessing. The only argument I do agree with is about readability - this is hardly the case here; but in case you wanted to know this for academic purposes, you can do it:

```<code>int[] result = carDealer.getBrands()
         .stream()
         .map(brand -> new int[]{brand.getManufacturer().getIncome(),
                                 brand.getManufacturer().getOutcome()})
         .collect(Collector.of(
                    () -> new int[2],
                    (left, right) -> {
                        left[0] += right[0];
                        left[1] += right[1];
                    },
                    (left, right) -> {
                        left[0] += right[0];
                        left[1] += right[1];
                        return left;
                    }));
</code>```

Body:
I have something like this:

Integer totalIncome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getIncome()).sum();
Integer totalOutcome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getOutcome()).sum();

How could I write that in one stream ? to collect f.e. Pair<Integer, Integer> with totalIncome and totalOutcome ?

EDITED:

Thank you guys for your comments, answers, and involvment. I would have a question about different approach to that problem using streams. What do you think about that:

final IncomeAndOutcome incomeAndOutcome = carDealer.getBrands()
                    .stream()
                    .map(Brand::getManufacturer)
                    .map(IncomeAndOutcome::of)
                    .reduce(IncomeAndOutcome.ZERO, IncomeAndOutcome::sum);

static class IncomeAndOutcome {

    private static final IncomeAndOutcome ZERO = of(0, 0);

    @Getter
    private final int income;

    @Getter
    private final int outcome;

    public static IncomeAndOutcome of(final int income, final int outcome) {
        return new IncomeAndOutcome(income, outcome);
    }

    public static IncomeAndOutcome of(final Manufacturer manufacturer) {
        return new IncomeAndOutcome(manufacturer.getIncome(), manufacturer.getOutcome());
    }

    IncomeAndOutcome(final int income, final int outcome) {
        this.income = income;
        this.outcome = outcome;
    }

    IncomeAndOutcome sum(final IncomeAndOutcome incomeAndOutcome) {
        return of(this.income + incomeAndOutcome.getIncome(), this.outcome + incomeAndOutcome.getOutcome());
    }
}

Body:
Without measuring correctly - everything is guessing. The only argument I do agree with is about readability - this is hardly the case here; but in case you wanted to know this for academic purposes, you can do it:

int[] result = carDealer.getBrands()
         .stream()
         .map(brand -> new int[]{brand.getManufacturer().getIncome(),
                                 brand.getManufacturer().getOutcome()})
         .collect(Collector.of(
                    () -> new int[2],
                    (left, right) -> {
                        left[0] += right[0];
                        left[1] += right[1];
                    },
                    (left, right) -> {
                        left[0] += right[0];
                        left[1] += right[1];
                        return left;
                    }));


问:
Flexbox align center
I have a side nav-bar. I want the items to be evenly spaced so that it fills out the whole 'bar'.

I've tried making my 'container' have justify-content: space-between. However, it's not taking the flex attribute.

I'll post my code as it'll show what I mean.

I also would like it that it stays 'fixed' but doing so cuts the 'container' to about 50% height.

https://codepen.io/azhorabai/pen/MOOwrJ

* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  font-family: "Dosis", sans-serif;
}

body {
  display: flex;
  min-height: 100vh;
  flex-flow: row wrap;
  margin: auto;
  background-color: black;
}

.side-menu {
  background-color: lightcoral;
  font-size: 2em;
  text-transform: uppercase;
  justify-content: space-between;
}

.side-menu ol {
  list-style-type: none;
  max-width: 100%;
  padding: 0px 30px;
}

.side-menu li {
  line-height: 5em;
}

#projects {}

.top-header {
  background-color: lightgreen;
  height: 20vh;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">
</head>

<body>
  <title>X. Quisite</title>
  <nav class="side-menu">
    <ol>
      <li class="about-me">About</li>
      <li class="projects">Projects
        <li>
          <li class="skills">Services</li>
          <li class="contact">Contact</li>
    </ol>
  </nav>
</body>

</html></code>```

答:
The justify-content property applies only to flex containers. So it must apply to an element that also has display: flex or display: inline-flex (read more).

body {
  display: flex;
  height: 100vh;
  margin: 0;
  background-color: black;
}

.side-menu {
  background-color: lightcoral;
  font-size: 2em;
  text-transform: uppercase;
  justify-content: space-between;
  display: flex;           /* new */
  flex-direction: column;  /* new */
}

a {
  padding: 0px 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="side-menu">
  About
  Projects
  Services
  Contact
</nav></code>```

Title: Flexbox align center

Body:
I have a side nav-bar. I want the items to be evenly spaced so that it fills out the whole 'bar'.

I've tried making my 'container' have justify-content: space-between. However, it's not taking the flex attribute.

I'll post my code as it'll show what I mean.

I also would like it that it stays 'fixed' but doing so cuts the 'container' to about 50% height.

https://codepen.io/azhorabai/pen/MOOwrJ

* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  font-family: "Dosis", sans-serif;
}

body {
  display: flex;
  min-height: 100vh;
  flex-flow: row wrap;
  margin: auto;
  background-color: black;
}

.side-menu {
  background-color: lightcoral;
  font-size: 2em;
  text-transform: uppercase;
  justify-content: space-between;
}

.side-menu ol {
  list-style-type: none;
  max-width: 100%;
  padding: 0px 30px;
}

.side-menu li {
  line-height: 5em;
}

#projects {}

.top-header {
  background-color: lightgreen;
  height: 20vh;
  box-sizing: border-box;
}

  <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">

  <title>X. Quisite</title>

About

Projects

Services

Contact

Body:
The justify-content property applies only to flex containers. So it must apply to an element that also has display: flex or display: inline-flex (read more).

body {
  display: flex;
  height: 100vh;
  margin: 0;
  background-color: black;
}

.side-menu {
  background-color: lightcoral;
  font-size: 2em;
  text-transform: uppercase;
  justify-content: space-between;
  display: flex;           /* new */
  flex-direction: column;  /* new */
}

a {
  padding: 0px 30px;
}

<nav class="side-menu">
  <a class="about-me">About</a>
  <a class="projects">Projects</a>
  <a class="skills">Services</a>
  <a class="contact">Contact</a>
</nav>


问:
Shopify Carrier Service Callback doesn't send information
I'm doing a Shopify App with Rails and I've created a new Carrier service with a requestbin callback:

```<code>def crearcarrier
carrier_service = {
                name: 'Test Carrier',
                callback_url:"https://requestb.in/tfxxxxx",
                service_discovery: true
              }
ShopifyAPI::CarrierService.create(carrier_service)
end
</code>```

But I don't receive anything in requestbin when I'm doing an order on the checkout.

How can I receive the information of the callback_url on my app?

答: If you setup a checkout, when you transition to the shipping screen, your callback will get a payload from Shopify with the origin, destination and items to be shipped. If you do not get a payload to your endpoint, check if your carrier service was actually created. Otherwise, your problem is likely with requestbin. </p>

Body:
I'm doing a Shopify App with Rails and I've created a new Carrier service with a requestbin callback:

def crearcarrier
carrier_service = {
                name: 'Test Carrier',
                callback_url:"https://requestb.in/tfxxxxx",
                service_discovery: true
              }
ShopifyAPI::CarrierService.create(carrier_service)
end

But I don't receive anything in requestbin when I'm doing an order on the checkout.

How can I receive the information of the callback_url on my app?


问:
Filter card list with Razor View
Im trying to make a filter like in AngularJS when u use:

ng-repeat="u in users | filter:searchBar">

And your input filter looks like

<input type="text" id="searchBar" placeholder="start typing" ng-model="searchBar">

But the things its that im working on MVC with Razor View and I do not know how to approach this filter.

The list of cards is made with a foreachlike this:

```<code>@foreach{ var item in Models){
<div class="card">
  <div class="card-container">
    some content
  </div>

</div>

}
</code>```

Any ideas?

答:
You can do the filtering with ajax. Here is a server side filtering solution.

First, you should move the code which renders the result to a partial view. Let's say you created a partial view called CustomerList.cshtml. Move the list code to that.

```<code>@model IEnumerable<Customer>
@foreach (var item in Model)
{
    <div class="card">
        <div class="card-container">
            @item.Name
        </div>
    </div>
}
</code>```

Now in your main view, you can call this partial view and pass the data to it. Wrap the call to the partial view in a container div. Add a input element for user to enter the search key. Assuming your main view is also strongly typed to IEnumerable<Customer>

```<code>@model IEnumerable<Customer>
<input type="text" id="search" data-url="@Url.Action("Index")" />
<div id="div-items">
    @Html.Partial("CustomerList",Model)
</div>
</code>```

Now we need to have some javascript code which listen to the keyup event on the search input, read the value of it and make an ajax call to the server where it uses the search key and get the filtered set of data, pass that to the same partial view and return the partial view result.

You can use jQuery $.get method

```<code>$(document).ready(function () {

    $("#search").keyup(function() {
        var v = $(this).val();

        $.get($(this).data("url"), { searchKey: v }).done(function(res) {
            $("#div-items").html(res);
        });
    });
});
</code>```

Now make sure your server action method returns the filtered data like this

```<code>public ActionResult Index(string serchKey="")
{
    var items = db.Customers.AsQueryable();
    if (!String.IsNullOrEmpty(searchKey))
    {
        items = items.Where(a => a.Name.StartsWith(searchKey));
    }
    var t = items.ToList();
    if (Request.IsAjaxRequest())
    {
        return PartialView("CustomerList",t );
    }
    return View(t);
}
</code>```

Another option is to do client side filtering. on the items. But if i am going that direction, i would choose a client side MVC framework like angular to do that for me

Title: Filter card list with Razor View

Body:
Im trying to make a filter like in AngularJS when u use:

ng-repeat="u in users | filter:searchBar">

And your input filter looks like

<input type="text" id="searchBar" placeholder="start typing" ng-model="searchBar">

But the things its that im working on MVC with Razor View and I do not know how to approach this filter.

The list of cards is made with a foreachlike this:

@foreach{ var item in Models){

    some content

}

Any ideas?

Body:
You can do the filtering with ajax. Here is a server side filtering solution.

First, you should move the code which renders the result to a partial view. Let's say you created a partial view called CustomerList.cshtml. Move the list code to that.

@model IEnumerable<Customer>
@foreach (var item in Model)
{
    <div class="card">
        <div class="card-container">
            @item.Name
        </div>
    </div>
}

Now in your main view, you can call this partial view and pass the data to it. Wrap the call to the partial view in a container div. Add a input element for user to enter the search key. Assuming your main view is also strongly typed to IEnumerable<Customer>

@model IEnumerable<Customer>
<input type="text" id="search" data-url="@Url.Action("Index")" />
<div id="div-items">
    @Html.Partial("CustomerList",Model)
</div>

Now we need to have some javascript code which listen to the keyup event on the search input, read the value of it and make an ajax call to the server where it uses the search key and get the filtered set of data, pass that to the same partial view and return the partial view result.

You can use jQuery $.get method

$(document).ready(function () {

    $("#search").keyup(function() {
        var v = $(this).val();

        $.get($(this).data("url"), { searchKey: v }).done(function(res) {
            $("#div-items").html(res);
        });
    });
});

Now make sure your server action method returns the filtered data like this

public ActionResult Index(string serchKey="")
{
    var items = db.Customers.AsQueryable();
    if (!String.IsNullOrEmpty(searchKey))
    {
        items = items.Where(a => a.Name.StartsWith(searchKey));
    }
    var t = items.ToList();
    if (Request.IsAjaxRequest())
    {
        return PartialView("CustomerList",t );
    }
    return View(t);
}

Another option is to do client side filtering. on the items. But if i am going that direction, i would choose a client side MVC framework like angular to do that for me


问:
Data for sunburst charts with d3.hierarchy using D3js v4
I am trying to get a sunburst chart using d3.hierarchy with d3js v4 . I did the same as an example  here. But since the data I was getting as an array of objects and not the same as used in the example I did add a small function so that the data would be the same as from the example. Below is the function

```<code>const arrayToObject = (array) =>
    array.reduce((obj, item) => {
        obj[item.name] = item
        return obj
}, {})
</code>```

Here is the link for the fiddle:  https://jsfiddle.net/snt1/mbszu1u5/8/

Thank You.

答:
I'm not sure if this is an answer (I think it is) or I should post this as a comment BUT here's the thing with your code:

d3.hierarchy() looks for an object with "name" and "children" and manipulates the data which is then used by partition(root).

If you debug the code at https://bl.ocks.org/maybelinot/5552606564ef37b5de7e47ed2b7dc099, you'll see that d3.hierarchy() receives an object as {name: "flare", children: Array[15]}

In your code, if I just wrap the data array in an object, say:
{name: "test", children: data}, it creates a sunburst with colors and appropriate titles.

Here's a FIDDLE with the changes. (btw I've commented arrayToObject)

Hope this helps. :)

Body:
I am trying to get a sunburst chart using d3.hierarchy with d3js v4 . I did the same as an example  here. But since the data I was getting as an array of objects and not the same as used in the example I did add a small function so that the data would be the same as from the example. Below is the function

const arrayToObject = (array) =>
    array.reduce((obj, item) => {
        obj[item.name] = item
        return obj
}, {})

Here is the link for the fiddle:  https://jsfiddle.net/snt1/mbszu1u5/8/

Thank You.


问:
Pandas: append row to DataFrame with multiindex in columns
I have a DataFrame with a multiindex in the columns and would like to use dictionaries to append new rows.

Let's say that each row in the DataFrame is a city. The columns contains "distance" and "vehicle". And each cell would be the percentage of the population that chooses this vehicle for this distance.

I'm constructing an index like this:

```<code>index_tuples=[]

for distance in ["near", "far"]:
    for vehicle in ["bike", "car"]:
        index_tuples.append([distance, vehicle])

index = pd.MultiIndex.from_tuples(index_tuples, names=["distance", "vehicle"])
</code>```

Then I'm creating a dataframe:

```<code>dataframe = pd.DataFrame(index=["city"], columns = index)
</code>```

The structure of the dataframe looks good. Although pandas has added Nans as default values ?

Now I would like to set up a dictionary for the new city and add it:

```<code>my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe["my_home_city"] = my_home_city
</code>```

But this fails:

ValueError: Length of values does not match length of index

Here is the complete error message (pastebin)

UPDATE:

Thank you for all the good answers. I'm afraid I've oversimplified the problem in my example. Actually my index is nested with 3 levels (and it could become more).

So I've accepted the universal answer of converting my dictionary into a list of tuples. This might not be as clean as the other approaches but works for any multiindex setup.

答:
Initialize your empty dataframe using MultiIndex.from_product.

```<code>distances = ['near', 'far']
vehicles = ['bike', 'car']
df = pd.DataFrame([], columns=pd.MultiIndex.from_product([distances, vehicles]),
                  index=pd.Index([], name='city'))
</code>```

Your dictionary results in a square matrix (distance by vehicle), so unstack it (which will result in a Series), then convert it into a dataframe row by calling (to_frame) using the relevant city name and transposing the column into a row.

```<code>>>> df.append(pd.DataFrame(my_home_city).unstack().to_frame('my_home_city').T)
              far     near
             bike car bike car
city
my_home_city    0   1    1   0
</code>```

Body:
I have a DataFrame with a multiindex in the columns and would like to use dictionaries to append new rows.

Let's say that each row in the DataFrame is a city. The columns contains "distance" and "vehicle". And each cell would be the percentage of the population that chooses this vehicle for this distance.

I'm constructing an index like this:

index_tuples=[]

for distance in ["near", "far"]:
    for vehicle in ["bike", "car"]:
        index_tuples.append([distance, vehicle])

index = pd.MultiIndex.from_tuples(index_tuples, names=["distance", "vehicle"])

Then I'm creating a dataframe:

dataframe = pd.DataFrame(index=["city"], columns = index)

The structure of the dataframe looks good. Although pandas has added Nans as default values ?

Now I would like to set up a dictionary for the new city and add it:

my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe["my_home_city"] = my_home_city

But this fails:

ValueError: Length of values does not match length of index

Here is the complete error message (pastebin)

UPDATE:

Thank you for all the good answers. I'm afraid I've oversimplified the problem in my example. Actually my index is nested with 3 levels (and it could become more).

So I've accepted the universal answer of converting my dictionary into a list of tuples. This might not be as clean as the other approaches but works for any multiindex setup.

Body:
Initialize your empty dataframe using MultiIndex.from_product.

distances = ['near', 'far']
vehicles = ['bike', 'car']
df = pd.DataFrame([], columns=pd.MultiIndex.from_product([distances, vehicles]),
                  index=pd.Index([], name='city'))

Your dictionary results in a square matrix (distance by vehicle), so unstack it (which will result in a Series), then convert it into a dataframe row by calling (to_frame) using the relevant city name and transposing the column into a row.

>>> df.append(pd.DataFrame(my_home_city).unstack().to_frame('my_home_city').T)
              far     near
             bike car bike car
city
my_home_city    0   1    1   0


问:
Exported terraform path (~/.profile) is not working properly
I am attempting to install terraform and export the path in my ~/.profile and it does not seem t be doing anything as is get the following message when trying to run terraform:

```<code>terraform -version
-bash: terraform: command not found
</code>```

My ~/,profile entry looks like this:

```<code>export PATH="$PATH:~/usr/local/terraform"
</code>```

NOTE: this is from a Mac.

答:
Looks weird for me about the path, should it be /usr/local/bin/terraform ?

anyway, copy the line to ~/.bash_profile. stop and start your xterm, then try again.

Body:
I am attempting to install terraform and export the path in my ~/.profile and it does not seem t be doing anything as is get the following message when trying to run terraform:

terraform -version
-bash: terraform: command not found

My ~/,profile entry looks like this:

export PATH="$PATH:~/usr/local/terraform"

NOTE: this is from a Mac.


问:
Is it possible to have an if function use pattern matching in Haskell?
I know that a method that takes a list input can use pattern matching like so:

```<code>testingMethod [] = "Blank"
testingMethod (x:xs) = show x
</code>```

My question is, can I do this with an if function? For example, if I have a function1 that needs to check the pattern of the output from function2, how would I go about doing this? I am looking for something like this:

```<code>if (function2 inputInt == pattern((x:xs), [1,2,3])) then
</code>```

Is this possible to do in haskell?

答:
The syntax you are looking for is that of a case statement or a guard:

You said:

```<code>if (function2 inputInt == pattern((x:xs), [1,2,3])) then
</code>```

In Haskell:

```<code>testingMethod inputInt | (x:xs, [1,2,3]) <- function2 inputInt = expr
                       | otherwise = expr2
</code>```

Or using case and let (or you could inline things or use where):

```<code>testingMethod inputInt =
    let res = function2 inputInt
    in case res of
         (x:xs, [1,2,3]) -> expr
         _ -> expr2
</code>```

Or using view patterns:

```<code>{-# LANGUAGE ViewPatterns #-}
testingMethod (function2 -> (x:xs,[1,2,3])) = expr
testingMethod _ = expr2
</code>```

Body:
I know that a method that takes a list input can use pattern matching like so:

testingMethod [] = "Blank"
testingMethod (x:xs) = show x

My question is, can I do this with an if function? For example, if I have a function1 that needs to check the pattern of the output from function2, how would I go about doing this? I am looking for something like this:

if (function2 inputInt == pattern((x:xs), [1,2,3])) then

Is this possible to do in haskell?

Body:
The syntax you are looking for is that of a case statement or a guard:

You said:

if (function2 inputInt == pattern((x:xs), [1,2,3])) then

In Haskell:

testingMethod inputInt | (x:xs, [1,2,3]) <- function2 inputInt = expr
                       | otherwise = expr2

Or using case and let (or you could inline things or use where):

testingMethod inputInt =
    let res = function2 inputInt
    in case res of
         (x:xs, [1,2,3]) -> expr
         _ -> expr2

Or using view patterns:

{-# LANGUAGE ViewPatterns #-}
testingMethod (function2 -> (x:xs,[1,2,3])) = expr
testingMethod _ = expr2


问:
how to get multiple columns using HBase shell
I have Randonnee Table with 2 family columns

```<code>Info: Name, region, suite
Tech: distance, denivele
</code>```

I have this Data on my Table Randonnee

```<code>      (id, Name, region, distance, denivele, suite)

      (1, 'Monts du Djurdjura', 'Tizi Ouzou', 35, 1000, NULL);

      (2, 'Circuit de Misserghin', 'Oran', 25 , 514, NULL);

      (3, 'Montagne de Murdjadju', 'Oran', 31, 1100, NULL);

      (4, 'Canastel', 'Oran', 18, 890, 3);

      (5, 'Yama Gouraya', 'Bejaia', 19, 900, NULL);

      (6, 'Sidi Makhlouf', 'Blida', 8, 165, 8);

      (7, 'Tikjda', 'Tizi Ouzou', 10, 1900, NULL);

      (8, 'Feroukha', 'Blida', 14.18, 454, NULL);

      (9, 'Chrea Azzazga', 'Tizi Ouzou', 6.23, 1548, 11);
</code>```

I want to get the distance of randonne where Name is 'Montagne de Murdjadu'

I tryed this query :

```<code>scan 'randonnee',{COLUMN=>'info:Name',FILTER=>"ValueFilter(=, 'binary:Montagne de Murdjadju')"}
</code>```

but the problem that she gives me the id in return, not the distance

```<code>ROW                   COLUMN+CELL
  3                    column=info:nom, timestamp=1509960875652, value=Montagne de Murdjadju
</code>```

How I get the distance?

答:
this Query give me the distance fo randonnee where Name is 'Montagne de Murdjadu'

```<code>scan 'randonnee',{FILTER=>"SingleColumnValueFilter('info', 'Name', =,'binary:Montagne de Murdjadju') AND ColumnPrefixFilter ('distance')"}
</code>```

or

```<code>scan 'randonnee',{FILTER=>"SingleColumnValueFilter('info', 'Name', =,'binary:Montagne de Murdjadju') AND QualifierFilter(=,'binary:distance') "}
</code>```

result :

```<code>ROW  COLUMN+CELL
3    column=tech:dist, timestamp=1509961960359, value=31
</code>```

Body:
I have Randonnee Table with 2 family columns

Info: Name, region, suite
Tech: distance, denivele

I have this Data on my Table Randonnee

      (id, Name, region, distance, denivele, suite)

      (1, 'Monts du Djurdjura', 'Tizi Ouzou', 35, 1000, NULL);

      (2, 'Circuit de Misserghin', 'Oran', 25 , 514, NULL);

      (3, 'Montagne de Murdjadju', 'Oran', 31, 1100, NULL);

      (4, 'Canastel', 'Oran', 18, 890, 3);

      (5, 'Yama Gouraya', 'Bejaia', 19, 900, NULL);

      (6, 'Sidi Makhlouf', 'Blida', 8, 165, 8);

      (7, 'Tikjda', 'Tizi Ouzou', 10, 1900, NULL);

      (8, 'Feroukha', 'Blida', 14.18, 454, NULL);

      (9, 'Chrea Azzazga', 'Tizi Ouzou', 6.23, 1548, 11);

I want to get the distance of randonne where Name is 'Montagne de Murdjadu'

I tryed this query :

scan 'randonnee',{COLUMN=>'info:Name',FILTER=>"ValueFilter(=, 'binary:Montagne de Murdjadju')"}

but the problem that she gives me the id in return, not the distance

ROW                   COLUMN+CELL
  3                    column=info:nom, timestamp=1509960875652, value=Montagne de Murdjadju

How I get the distance?

Body:
this Query give me the distance fo randonnee where Name is 'Montagne de Murdjadu'

scan 'randonnee',{FILTER=>"SingleColumnValueFilter('info', 'Name', =,'binary:Montagne de Murdjadju') AND ColumnPrefixFilter ('distance')"}

or

scan 'randonnee',{FILTER=>"SingleColumnValueFilter('info', 'Name', =,'binary:Montagne de Murdjadju') AND QualifierFilter(=,'binary:distance') "}

result :

ROW  COLUMN+CELL
3    column=tech:dist, timestamp=1509961960359, value=31


问:
VBA Match function using today's date to search for last year's entry
So say I got Today's date =TODAY() and two matrixes with sales arranged by date.

```<code>Date      Store1  Store2
1/11/2017  800    2000
2/11/2017  500    3000
</code>```

and

```<code>Date       Store1  Store2
1/11/2016   400     5000
2/11/2016   2000    6000
</code>```

I'm trying to calculate how much sales increased on a date compared to last year's but I cant find any way that works.

```<code>Date       IncreaseStore1 IncreaseStore2
1/11
2/11
</code>```

I found this Function to get last year's date but it gives me the date as text and I cant find a way to fix it with VBA.

```<code>Function PrevYear(XYear As Date) As String

    PrevYear = Format(Format(XYear, "dd/mm") & "/" & Format(XYear, "yyyy") - 1, "dd/mm/yyyy")

End Function
</code>```

Any help would be appreciated since I'm all out of ideas

答:
Any reason why you want to use VBA? You can do this easily enough with formulas using this:

```<code> =DATE(YEAR(A2)-1,MONTH(A2),DAY(A2))
</code>```

Using VBA:

```<code>DateAdd("YYYY",-1,Range("A2"))
</code>```

Body:
So say I got Today's date =TODAY() and two matrixes with sales arranged by date.

Date      Store1  Store2
1/11/2017  800    2000
2/11/2017  500    3000

and

Date       Store1  Store2
1/11/2016   400     5000
2/11/2016   2000    6000

I'm trying to calculate how much sales increased on a date compared to last year's but I cant find any way that works.

Date       IncreaseStore1 IncreaseStore2
1/11
2/11

I found this Function to get last year's date but it gives me the date as text and I cant find a way to fix it with VBA.

Function PrevYear(XYear As Date) As String

    PrevYear = Format(Format(XYear, "dd/mm") & "/" & Format(XYear, "yyyy") - 1, "dd/mm/yyyy")

End Function

Any help would be appreciated since I'm all out of ideas

Body:
Any reason why you want to use VBA? You can do this easily enough with formulas using this:

 =DATE(YEAR(A2)-1,MONTH(A2),DAY(A2))

Using VBA:

DateAdd("YYYY",-1,Range("A2"))


问:
The "XamlCTask" task failed unexpectedly. What to do?
I am getting this error:

The "XamlCTask" task failed unexpectedly.
  System.ArgumentException: An item with the same key has already been added.

```<code>Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()
</code>```

I know that it is saying that the item is duplicated but I scanned whole project with Total Commander and I didn't find any duplicated file.

答: Consolidate your nuGet-packages and make sure all Xamarin.Forms referencing projects uses the same Xamarin.Forms version. After that empty the packages folder, clean and rebuild your solution.</p>

Body:
I am getting this error:

The "XamlCTask" task failed unexpectedly.
  System.ArgumentException: An item with the same key has already been added.

Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()

I know that it is saying that the item is duplicated but I scanned whole project with Total Commander and I didn't find any duplicated file.


问:
How to split the first directory out of the path (such as home/tom/cat >> tom/cat >> cat) in python?
As example from the title, I want the result:

Dir : home/tom/cat

first cut : tom/cat

second cut: /cat

last cut: /

How to do it in python?

答:
Here's a clean answer I haven't seen elsewhere:

```<code>>>> mypath="first/second/third/fourth/fifth.txt"
>>> mypath.split('/',1)
['first', 'second/third/fourth/fifth.txt']
>>> mypath.split('/',1)[1]
'second/third/fourth/fifth.txt'
</code>```

Split can split a string at the first split.

Body:
Here's a clean answer I haven't seen elsewhere:

>>> mypath="first/second/third/fourth/fifth.txt"
>>> mypath.split('/',1)
['first', 'second/third/fourth/fifth.txt']
>>> mypath.split('/',1)[1]
'second/third/fourth/fifth.txt'

Split can split a string at the first split.


问:
JavaScript checkbox dropdown style not working
Beginner here.

My functionality is working, but at the moment it shows the checkboxes already dropped down.

I want to hit the drop down in order to see the boxes.

Help!

```<code><style>
  .multiselect {
    width: 450px;
  }

  .selectBox {
    position: relative;
  }

  .selectBox select {
    width: 100%;
    font-weight: bold;
  }

  .overSelect {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }

  #checkboxes {
    display: none;
    border: 1px #dadada solid;
  }

  #checkboxes label {
    display: block;
  }

  #checkboxes label:hover {
    background-color: #1e90ff;
  }
</style>
</code>```

And here is the second part, I'm not sure what I'm doing wrong any help would be highly appreciated.
This is the HTML.

```<code><div class="multiselect">
  <div class="selectBox" onclick="showCheckboxes(0)">
    <select>
      <option>Select an option</option>
    </select>
    <div class="overSelect"></div>
  </div>
  <div id="checkboxes-0">
    <input type="checkbox" name="at0[]" id="one" value="red" />red
    <input type="checkbox" name="at0[]" id="two" value="blue" />blue
    <input type="checkbox" name="at0[]" id="three" value="green" />green

<script>
  var cbOneExpanded = false;
  var cbTwoExpanded = false;

  function showCheckboxes(id) {
    var checkboxes = document.getElementById('checkboxes-' + id);

    if (id > 0) {
      if (!cbTwoExpanded) {
        checkboxes.style.display = 'block';
        cbTwoExpanded = true;
      } else {
        checkboxes.style.display = 'none';
        cbTwoExpanded = false;
      }
    } else {
      if (!cbOneExpanded) {
        checkboxes.style.display = 'block';
        cbOneExpanded = true;
      } else {
        checkboxes.style.display = 'none';
        cbOneExpanded = false;
      }
    }
  }
</script>
</code>```

Thanks again.

答:
You are almost there.  First just hide the div that contains the boxes and then in your js function display the div.

  var cbOneExpanded = false;
  var cbTwoExpanded = false;

  function showCheckboxes(id) {
    var checkboxes = document.getElementById('checkboxes-' + id);
    var x = document.getElementById('checkboxes-0');
    x.style.display = "block";

    if (id > 0) {
      if (!cbTwoExpanded) {
        checkboxes.style.display = 'block';
        cbTwoExpanded = true;
      } else {
        checkboxes.style.display = 'none';
        cbTwoExpanded = false;
      }
    } else {
      if (!cbOneExpanded) {
        checkboxes.style.display = 'block';
        cbOneExpanded = true;
      } else {
        checkboxes.style.display = 'none';
        cbOneExpanded = false;
      }
    }
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .multiselect {
    width: 450px;
  }

  .selectBox {
    position: relative;
  }

  .selectBox select {
    width: 100%;
    font-weight: bold;
  }

  .overSelect {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }

  #checkboxes {
    display: none;
    border: 1px #dadada solid;
  }

  #checkboxes label {
    display: block;
  }

  #checkboxes label:hover {
    background-color: #1e90ff;
  }</code>```

                        <select>
                          <option>Select an option</option>
                        </select>

                        <input type="checkbox" name="at0[]" id="one" value="red"/>red
                        <input type="checkbox" name="at0[]" id="two" value="blue"/>blue
                        <input type="checkbox" name="at0[]" id="three" value="green"/>green
And here is the rest```

Body:
Beginner here.

My functionality is working, but at the moment it shows the checkboxes already dropped down.

I want to hit the drop down in order to see the boxes.

Help!

And here is the second part, I'm not sure what I'm doing wrong any help would be highly appreciated.
This is the HTML.

    <select>
      <option>Select an option</option>
    </select>

    <input type="checkbox" name="at0[]" id="one" value="red" />red
    <input type="checkbox" name="at0[]" id="two" value="blue" />blue
    <input type="checkbox" name="at0[]" id="three" value="green" />green

Thanks again.

Body:
You are almost there.  First just hide the div that contains the boxes and then in your js function display the div.

  var cbOneExpanded = false;
  var cbTwoExpanded = false;

  function showCheckboxes(id) {
    var checkboxes = document.getElementById('checkboxes-' + id);
    var x = document.getElementById('checkboxes-0');
    x.style.display = "block";

    if (id > 0) {
      if (!cbTwoExpanded) {
        checkboxes.style.display = 'block';
        cbTwoExpanded = true;
      } else {
        checkboxes.style.display = 'none';
        cbTwoExpanded = false;
      }
    } else {
      if (!cbOneExpanded) {
        checkboxes.style.display = 'block';
        cbOneExpanded = true;
      } else {
        checkboxes.style.display = 'none';
        cbOneExpanded = false;
      }
    }
  }

 .multiselect {
    width: 450px;
  }

  .selectBox {
    position: relative;
  }

  .selectBox select {
    width: 100%;
    font-weight: bold;
  }

  .overSelect {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }

  #checkboxes {
    display: none;
    border: 1px #dadada solid;
  }

  #checkboxes label {
    display: block;
  }

  #checkboxes label:hover {
    background-color: #1e90ff;
  }

                    <div class="multiselect">
                      <div class="selectBox" onclick="showCheckboxes(0)">
                        <select>
                          <option>Select an option</option>
                        </select>
                        <div class="overSelect"></div>
                      </div>
                      <div id="checkboxes-0" style='display:none'>
                        <input type="checkbox" name="at0[]" id="one" value="red"/>red
                        <input type="checkbox" name="at0[]" id="two" value="blue"/>blue
                        <input type="checkbox" name="at0[]" id="three" value="green"/>green
And here is the rest


问:
Creating a 2D array of strings in C?
Could also be called a 3D array, as each string is essentially it's own array.

Would be in the following format, each row = a new 'order'.

[ [FirstName, SecondName, DOB, Newspaper] ]

[ [FirstName, SecondName, DOB, Newspaper] ]

The contents of the array will be all strings (even though DOB would be in the format "23012017" and then converted to integer if necessary

Tried to use this "pointer arrays", but am not sure about how to use it.

char *bookings[][2];

char firstname[20], secondname[20], dob[8];

char *bookings[][0]=firstname, *bookings[][1]=secondname, *bookings[][2]=dob;

答:
I think what you need is a struct and a normal 1D array. Like:

```<code>struct order {
    char FirstName[42];
    char SecondName[42];
    char DOB[42];
    char Newspaper[42];
}
</code>```

and in your code (e.g. in main)

```<code>struct order[42];
</code>```

Then you do:

```<code>strcpy(order[0].FirstName, "Donald");
strcpy(order[0].SecondName, "Duck");
... and so on
</code>```

Title: Creating a 2D array of strings in C?

Body:
I think what you need is a struct and a normal 1D array. Like:

struct order {
    char FirstName[42];
    char SecondName[42];
    char DOB[42];
    char Newspaper[42];
}

and in your code (e.g. in main)

struct order[42];

Then you do:

strcpy(order[0].FirstName, "Donald");
strcpy(order[0].SecondName, "Duck");
... and so on


问:
Incorrect stacktrace by rethrow
I rethrow an exception with "throw;", but the stacktrace is incorrect:

```<code>static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}
</code>```

The right stacktrace should be:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12
</code>```

But I get:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15
</code>```

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.

答:
How can I preserve the REAL stacktrace?

You throw a new exception, and include the original exception as the inner exception.

but that's Ugly... Longer... Makes you choice the rigth exception to throw....

You are wrong about the ugly but right about the other two points. The rule of thumb is: don't catch unless you are going to do something with it, like wrap it, modify it, swallow it, or log it. If you decide to catch and then throw again, make sure you are doing something with it, otherwise just let it bubble up.

You may also be tempted to put a catch simply so you can breakpoint within the catch, but the Visual Studio debugger has enough options to make that practice unnecessary, try using first chance exceptions or conditional breakpoints instead.

Title: Incorrect stacktrace by rethrow

Body:
I rethrow an exception with "throw;", but the stacktrace is incorrect:

static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}

The right stacktrace should be:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12

But I get:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.


问:
How to show a <tag> inside a text tag e.g
,
,etc?
I want to show

答:
Just encode the opening bracket like < so that your browser doesn't interpret it as a tag. You can do the closing bracket too with > but it's unnecessary. e.g.

  a

Title: How to show a <tag> inside a text tag e.g <p>,<div>,etc?

Body: I want to show

Body:
Just encode the opening bracket like &lt; so that your browser doesn't interpret it as a tag. You can do the closing bracket too with &gt; but it's unnecessary. e.g.

 <p id="demo">  a &lt;script> tag </p>


问:
SAS: Variable list contains names with '-' symbol, resulting in error during keep= statement
I have SAS datasets with multiple variables like H9999-999-999-999. However, I need to drop the unnecessary columns and am using a variable list(ParamList) to do that:

```<code>proc sql;
select _NAME_ into :ParamList separated by ' '
from uniquePlanList;
quit;
%put ParamList = &ParamList.;

proc sql;
create table test as
select * from out.seq_summ(keep=BPT_Cat &ParamList.);
run;
</code>```

Because my variables contain '-' symbols I receive the following errors:

ERROR 214-322: Variable name - is not valid.

ERROR 214-322: Variable name 000 is not valid.

ERROR 80-322: Expecting a variable name.

ERROR: Invalid value for the KEEP option.

ERROR: Invalid option name -000.

ERROR: Some options for file OUT.SEQ_SUMM were not processed because of errors or warnings noted above.

I know if I were to list out the variables like this:

(keep=BPT_Cat 'H9999-999-999-999'n 'H9999-999-999-998'n)

Then the code would work. But I have some datasets with hundreds of variables. Is there a better way to drop the unnecessary columns than using a variable list? Or is there some clever way to read in the variable list as a string?
I tried using this:

(keep=BPT_Cat %str(&ParamList.)) but that gave me the same errors as above.

答:
Use the NLITERAL() function to generate names in a form that you can use in code.

```<code>proc sql noprint;
select nliteral(_NAME_)
  into :ParamList separated by ' '
  from uniquePlanList
;
quit;
</code>```

Body:
I have SAS datasets with multiple variables like H9999-999-999-999. However, I need to drop the unnecessary columns and am using a variable list(ParamList) to do that:

proc sql;
select _NAME_ into :ParamList separated by ' '
from uniquePlanList;
quit;
%put ParamList = &ParamList.;

proc sql;
create table test as
select * from out.seq_summ(keep=BPT_Cat &ParamList.);
run;

Because my variables contain '-' symbols I receive the following errors:

ERROR 214-322: Variable name - is not valid.

ERROR 214-322: Variable name 000 is not valid.

ERROR 80-322: Expecting a variable name.

ERROR: Invalid value for the KEEP option.

ERROR: Invalid option name -000.

ERROR: Some options for file OUT.SEQ_SUMM were not processed because of errors or warnings noted above.

I know if I were to list out the variables like this:

(keep=BPT_Cat 'H9999-999-999-999'n 'H9999-999-999-998'n)

Then the code would work. But I have some datasets with hundreds of variables. Is there a better way to drop the unnecessary columns than using a variable list? Or is there some clever way to read in the variable list as a string?
I tried using this:

(keep=BPT_Cat %str(&ParamList.)) but that gave me the same errors as above.

Body:
Use the NLITERAL() function to generate names in a form that you can use in code.

proc sql noprint;
select nliteral(_NAME_)
  into :ParamList separated by ' '
  from uniquePlanList
;
quit;


问:
Array of objects length
I am reading a file which have the following data. And i am assigning it to arr.

```<code>[
    {
        "data": {
            "One": {
                "One one": [
                    "Hello"
                ]
            }
        },
        "name": "1898061c-bd49-4e35-bfb6-6514fbe9c5c4"
    }
]
</code>```

When i access the first element like console.log(arr.length) it gives me 1 in chrome console (manually declaring array there). which is fine.

But when i console log to actual terminal it gives me 209.

答:
Make sure that the "arr" object is an array and not a string.

The array has length one, the stringified JSON of the array has length 209:

```<code>JSON.stringify(arr, null, 4).length; // => 209
</code>```

Title: Array of objects length

Body:
I am reading a file which have the following data. And i am assigning it to arr.

[
    {
        "data": {
            "One": {
                "One one": [
                    "Hello"
                ]
            }
        },
        "name": "1898061c-bd49-4e35-bfb6-6514fbe9c5c4"
    }
]

When i access the first element like console.log(arr.length) it gives me 1 in chrome console (manually declaring array there). which is fine.

But when i console log to actual terminal it gives me 209.

Body:
Make sure that the "arr" object is an array and not a string.

The array has length one, the stringified JSON of the array has length 209:

JSON.stringify(arr, null, 4).length; // => 209


问:
creating new column by running a function with input from several datasets on each row
I want to aggregate som data, combining two datasets lsr and adherence (examples for reproducability):

```<code>adherence <- cbind.data.frame(c("1", "2", "3", "1", "2", "3"), c("2013.1", "2013.1", "2013.1", "2013.2", "2013.2", "2013.2"))
library(dplyr)
library(tidyr)
names(adherence)[1] <- "ID"
names(adherence)[2] <- "year"
adherence$year <- as.numeric(as.character(adherence$year))

lsr <- cbind.data.frame(
        c("1", "1", "1", "2", "2", "2", "3", "3"), #ID
        c("2012.3", "2012.8", "2013.1","2012.8", "2013.3", "2013.9", "2011", "2013"), #eksd
        c("60", "90", "90", "60", "120", "60", "30", "90") # DDD
        )
names(lsr)[1] <- "ID"
names(lsr)[2] <- "eksd"
names(lsr)[3] <- "DDD"

lsr$eksd <- as.numeric(as.character(lsr$eksd))
lsr$DDD <- as.numeric(as.character(lsr$DDD))
lsr$ENDDATE <- lsr$eksd + lsr$DDD/365.25
</code>```

So in the adherence dataset I want a new column, containing information from the lsr dataset depending on the ID variable and year variable of each row in the adherence dataset. I made this function that I thinks does just that:

```<code>function.DDAV <- function() {
        Y <- lsr %>% #dummy variable
          filter(., .$ID == adherence$ID) %>% #filters lsr by ID from relevant row in adherence dataset
          filter(., .$eksd <= adherence$year & adherence$year <= .$ENDDATE) # filters further to include relevant time period
          Y$DIFF <- (Y$ENDDATE - adherence$year)*365.25 # calculates relevant drug dosage available for implementation of dosis regimen at time = adhererence$year i.e. uses the time from adherence dataset and compares with time until dose runs out
          z <- sum(Y$DIFF) #sum available drugs doses
          return(z) # returns sum to be inputted in one row in new column in adherence dataset
      }
</code>```

and the I want to apply this once for every row in the adherence dataset, creating a new column using the relevant row values.

I tried using the apply family functions, and aggregate function. I've struggling with this for a few days, and I get different errors, that I haven't shown, because I think that I may be thinking about using the problem all wrong ? When searching for it I only find questions about applying over the entire row or column in one single dataset.

EDIT I show the ideal output below:
The ideal output looks like this:

adherence$adherence <- as.numeric(c("90","0","53.475","16.95","120","0"))

In essense the calculation is simple after filtering: if a row is included after filtering the values are calculated as this example from first row with adherence$ID = 1 and adherence$year = 2013.1. only the last row of ID=1 remains, the sum is (2013.1 (adherence$year)-2013.346 (lsr$ENDDATE))*365.25 = 90.

答:
I'm not 100% sure this is what you are after, but hopefully it's a starting point.

My understanding is that for each occurrence of ID in acceptance you want to compare it with all like ID's in lsr and if the year is greater than or equal to eksd and less than ENDDATE you want to do a calculation with the remaining ENDDATEs.

The below should work to do that, the results in newVariable are slightly different than those in your ideal output, in that for the value related to ID=2 and year=2013.2 there isn't an eksd value for ID=2 in lsr that is less than or equal to year so instead of 120 I get 0.

```<code> adherence <- cbind.data.frame(c("1", "2", "3", "1", "2", "3"), c("2013.1", "2013.1", "2013.1", "2013.2", "2013.2", "2013.2"))
library(dplyr)
library(tidyr)
names(adherence)[1] <- "ID"
names(adherence)[2] <- "year"
adherence$year <- as.numeric(as.character(adherence$year))

lsr <- cbind.data.frame(
     c("1", "1", "1", "2", "2", "2", "3", "3"), #ID
     c("2012.3", "2012.8", "2013.1","2012.8", "2013.3", "2013.9", "2011", "2013"), #eksd
     c("60", "90", "90", "60", "120", "60", "30", "90") # DDD
)
names(lsr)[1] <- "ID"
names(lsr)[2] <- "eksd"
names(lsr)[3] <- "DDD"

lsr$eksd <- as.numeric(as.character(lsr$eksd))
lsr$DDD <- as.numeric(as.character(lsr$DDD))
lsr$ENDDATE <- lsr$eksd + lsr$DDD/365.25

adherence %>% full_join(lsr, by = 'ID')  %>% mutate(newVariable = ifelse(eksd <= year & year <= ENDDATE, (ENDDATE - year) * 365.25, 0)) %>%
     group_by(ID, year) %>% summarize(newVariable = sum(newVariable))

      ID   year newVariable
  <fctr>  <dbl>       <dbl>
1      1 2013.1      90.000
2      1 2013.2      53.475
3      2 2013.1       0.000
4      2 2013.2       0.000
5      3 2013.1      53.475
6      3 2013.2      16.950
</code>```

Body:
I want to aggregate som data, combining two datasets lsr and adherence (examples for reproducability):

adherence <- cbind.data.frame(c("1", "2", "3", "1", "2", "3"), c("2013.1", "2013.1", "2013.1", "2013.2", "2013.2", "2013.2"))
library(dplyr)
library(tidyr)
names(adherence)[1] <- "ID"
names(adherence)[2] <- "year"
adherence$year <- as.numeric(as.character(adherence$year))

lsr <- cbind.data.frame(
        c("1", "1", "1", "2", "2", "2", "3", "3"), #ID
        c("2012.3", "2012.8", "2013.1","2012.8", "2013.3", "2013.9", "2011", "2013"), #eksd
        c("60", "90", "90", "60", "120", "60", "30", "90") # DDD
        )
names(lsr)[1] <- "ID"
names(lsr)[2] <- "eksd"
names(lsr)[3] <- "DDD"

lsr$eksd <- as.numeric(as.character(lsr$eksd))
lsr$DDD <- as.numeric(as.character(lsr$DDD))
lsr$ENDDATE <- lsr$eksd + lsr$DDD/365.25

So in the adherence dataset I want a new column, containing information from the lsr dataset depending on the ID variable and year variable of each row in the adherence dataset. I made this function that I thinks does just that:

function.DDAV <- function() {
        Y <- lsr %>% #dummy variable
          filter(., .$ID == adherence$ID) %>% #filters lsr by ID from relevant row in adherence dataset
          filter(., .$eksd <= adherence$year & adherence$year <= .$ENDDATE) # filters further to include relevant time period
          Y$DIFF <- (Y$ENDDATE - adherence$year)*365.25 # calculates relevant drug dosage available for implementation of dosis regimen at time = adhererence$year i.e. uses the time from adherence dataset and compares with time until dose runs out
          z <- sum(Y$DIFF) #sum available drugs doses
          return(z) # returns sum to be inputted in one row in new column in adherence dataset
      }

and the I want to apply this once for every row in the adherence dataset, creating a new column using the relevant row values.

I tried using the apply family functions, and aggregate function. I've struggling with this for a few days, and I get different errors, that I haven't shown, because I think that I may be thinking about using the problem all wrong ? When searching for it I only find questions about applying over the entire row or column in one single dataset.

EDIT I show the ideal output below:
The ideal output looks like this:

adherence$adherence <- as.numeric(c("90","0","53.475","16.95","120","0"))

In essense the calculation is simple after filtering: if a row is included after filtering the values are calculated as this example from first row with adherence$ID = 1 and adherence$year = 2013.1. only the last row of ID=1 remains, the sum is (2013.1 (adherence$year)-2013.346 (lsr$ENDDATE))*365.25 = 90.

Body:
I'm not 100% sure this is what you are after, but hopefully it's a starting point.

My understanding is that for each occurrence of ID in acceptance you want to compare it with all like ID's in lsr and if the year is greater than or equal to eksd and less than ENDDATE you want to do a calculation with the remaining ENDDATEs.

The below should work to do that, the results in newVariable are slightly different than those in your ideal output, in that for the value related to ID=2 and year=2013.2 there isn't an eksd value for ID=2 in lsr that is less than or equal to year so instead of 120 I get 0.

 adherence <- cbind.data.frame(c("1", "2", "3", "1", "2", "3"), c("2013.1", "2013.1", "2013.1", "2013.2", "2013.2", "2013.2"))
library(dplyr)
library(tidyr)
names(adherence)[1] <- "ID"
names(adherence)[2] <- "year"
adherence$year <- as.numeric(as.character(adherence$year))

lsr <- cbind.data.frame(
     c("1", "1", "1", "2", "2", "2", "3", "3"), #ID
     c("2012.3", "2012.8", "2013.1","2012.8", "2013.3", "2013.9", "2011", "2013"), #eksd
     c("60", "90", "90", "60", "120", "60", "30", "90") # DDD
)
names(lsr)[1] <- "ID"
names(lsr)[2] <- "eksd"
names(lsr)[3] <- "DDD"

lsr$eksd <- as.numeric(as.character(lsr$eksd))
lsr$DDD <- as.numeric(as.character(lsr$DDD))
lsr$ENDDATE <- lsr$eksd + lsr$DDD/365.25

adherence %>% full_join(lsr, by = 'ID')  %>% mutate(newVariable = ifelse(eksd <= year & year <= ENDDATE, (ENDDATE - year) * 365.25, 0)) %>%
     group_by(ID, year) %>% summarize(newVariable = sum(newVariable))

      ID   year newVariable
  <fctr>  <dbl>       <dbl>
1      1 2013.1      90.000
2      1 2013.2      53.475
3      2 2013.1       0.000
4      2 2013.2       0.000
5      3 2013.1      53.475
6      3 2013.2      16.950


问:
Changing Spring containers log level setting
How do i change the log level of a spring container which does not run in an appserver?</p>

答:
in your log4j.properties (if using log4j):

```<code>log4j.logger.org.springframework=INFO
</code>```

Body:
in your log4j.properties (if using log4j):

log4j.logger.org.springframework=INFO


问:
CSS style effect involving z-index and transparency
I'm trying to achieve a design close to the snippet here. My problem is that I can't find a way to replace the blue background of .title by a simple transparency (so that the container's background stays visible). If I simply remove the blue background, the border becomes visible where .title is.

Also the "title" is generated by JS so I can't reliably predict the length of div as it may slightly vary depending on the situation.

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title span {
  display: inline-flex;
 align-items: center;
 justify-content: center;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
 background: hsla(200, 70%, 55%, 1);
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border: 0.1rem solid hsla(200, 70%, 20%, 1);
 border-radius: 0rem;
 margin-top: 10px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="zone">
    <div class="title">
      <span>Text Title</span>
    </div>
    <div class="content"></div>
  </div>
</div></code>```

Does anyone have an idea how to achieve what I'm trying to do ? Please let me know if my explanation is too brief or unclear.

Thank you !

答:
You can achieve that with pseudo elements. Take a look at this:

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title span {
  display: inline-flex;
 align-items: center;
 justify-content: center;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
}

.title span::before,
.title span::after{
  content: "";
  height: 2px;
  position: absolute;
  background: hsla(200, 70%, 20%, 1);
  width: calc(50% - 40px);
  top: 9px;
}

.title span::before{
  left: 0;
}

.title span::after{
  right: 0;
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border-right: 0.1rem solid hsla(200, 70%, 20%, 1);
  border-left: 0.1rem solid hsla(200, 70%, 20%, 1);
  border-bottom: 0.1rem solid hsla(200, 70%, 20%, 1);
 border-radius: 0rem;
 margin-top: 10px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="zone">
    <div class="title">
      <span>Text Title</span>
    </div>
    <div class="content"></div>
  </div>
</div></code>```

Body:
I'm trying to achieve a design close to the snippet here. My problem is that I can't find a way to replace the blue background of .title by a simple transparency (so that the container's background stays visible). If I simply remove the blue background, the border becomes visible where .title is.

Also the "title" is generated by JS so I can't reliably predict the length of div as it may slightly vary depending on the situation.

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title span {
  display: inline-flex;
 align-items: center;
 justify-content: center;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
 background: hsla(200, 70%, 55%, 1);
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border: 0.1rem solid hsla(200, 70%, 20%, 1);
 border-radius: 0rem;
 margin-top: 10px;
 }

      Text Title

Does anyone have an idea how to achieve what I'm trying to do ? Please let me know if my explanation is too brief or unclear.

Thank you !

Body:
You can achieve that with pseudo elements. Take a look at this:

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title span {
  display: inline-flex;
 align-items: center;
 justify-content: center;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
}

.title span::before,
.title span::after{
  content: "";
  height: 2px;
  position: absolute;
  background: hsla(200, 70%, 20%, 1);
  width: calc(50% - 40px);
  top: 9px;
}

.title span::before{
  left: 0;
}

.title span::after{
  right: 0;
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border-right: 0.1rem solid hsla(200, 70%, 20%, 1);
  border-left: 0.1rem solid hsla(200, 70%, 20%, 1);
  border-bottom: 0.1rem solid hsla(200, 70%, 20%, 1);
 border-radius: 0rem;
 margin-top: 10px;
 }

<div class="container">
  <div class="zone">
    <div class="title">
      <span>Text Title</span>
    </div>
    <div class="content"></div>
  </div>
</div>


问:
WPF ListBox change onMouseOver and SelectedItem color
I have created a simple WPF form and added a listbox with some items on it. By default when i run the application on Windows 10 the mouseover effect is blue (the listitems background color changes) and for the selected item the same.

How can i change this color for mousover and selected item to lets say red ?

答:
You can change the styles of Listbox directly (which Ayyappann's comment refers to).
Another way you can change the highlight color, if you would like it to be global, is to change the system colors.
So in your App.xaml you could put something like this:

```<code><SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red" />
</code>```

I prefer this way if i want certain actions to stay consistent (mouse over any object), OR if i would like to allow styles to be changed dynamically. I will customize the individual styles of local objects if i am looking for that object to have a typical behavior.
A list of the system colors can be found Here

Body:
You can change the styles of Listbox directly (which Ayyappann's comment refers to).
Another way you can change the highlight color, if you would like it to be global, is to change the system colors.
So in your App.xaml you could put something like this:

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red" />

I prefer this way if i want certain actions to stay consistent (mouse over any object), OR if i would like to allow styles to be changed dynamically. I will customize the individual styles of local objects if i am looking for that object to have a typical behavior.
A list of the system colors can be found Here


问:
Parsing JPEG bytestream markers with regex
I am working on writing a python program to manipulate information in a JPEG image. I am however having trouble getting my regular expression to look for the byte marker codes used in JPEG images.

For example: the start of image marker is \xFF\xD8 and the end of image marker is \xFF\xD9. The pattern I tried using was: rb'\xFF\xD8(.+?)\xFF\xD9'. No success there. What should my pattern be if I want to find everything in between specific byte markers in a byte array?

答:
The 'r' prefix on a string says "ignore backslash escapes" so it's ignoring them.

This means you are looking for a string with the first four characters literally r'\', 'x', 'F', and 'F'

Remove the r and double any backslashes that are part of the regular expression rather than escapes to represent binary characters.


答:
Pattern matching in a function definition is simply syntactic sugar for the "fundamental" pattern matching provided by case. For example, let's desugar your first function:

```<code>testingMethod [] = "Blank"
testingMethod (x:xs) = show x
</code>```

Can be rewritten to:

```<code>testingMethod arg = case arg of
  [] -> "Blank"
  (x:xs) -> show x
</code>```

It's not so clear what you intend your second snippet to do, so I can't really show you how it would look with a case expression. But one possible interpretation would be something like this:

```<code>case function2 inputInt of
  ((x:xs), [1,2,3]) -> -- ...
  (_, _) -> -- ...
</code>```

This supposes that your function2 returns a tuple of two lists.

Title: Is it possible to have an if function use pattern matching in Haskell?

Body:
I know that a method that takes a list input can use pattern matching like so:

testingMethod [] = "Blank"
testingMethod (x:xs) = show x

My question is, can I do this with an if function? For example, if I have a function1 that needs to check the pattern of the output from function2, how would I go about doing this? I am looking for something like this:

if (function2 inputInt == pattern((x:xs), [1,2,3])) then

Is this possible to do in haskell?

Body:
Pattern matching in a function definition is simply syntactic sugar for the "fundamental" pattern matching provided by case. For example, let's desugar your first function:

testingMethod [] = "Blank"
testingMethod (x:xs) = show x

Can be rewritten to:

testingMethod arg = case arg of
  [] -> "Blank"
  (x:xs) -> show x

It's not so clear what you intend your second snippet to do, so I can't really show you how it would look with a case expression. But one possible interpretation would be something like this:

case function2 inputInt of
  ((x:xs), [1,2,3]) -> -- ...
  (_, _) -> -- ...

This supposes that your function2 returns a tuple of two lists.


问:
For images, what is the benefit of using the name element? name="...."
I want to know what the difference is between alt="" and name=""

Would it be better to put the filename within the alt tag, or the description of the photo?

What makes better sense, both from SEO and validation stand-point?

答:
I'd be a little wary of putting the file name in the ALT tag, since it would be displayed if images are turned off. Typically you set the ALT tag to server as a place holder with something like "Site Logo" or something else to indicate what the image is.

The NAME tag is used for anchoring and the like. If you wanted to create a link that scrolled a long page to your image, you would reference it through this.

OwnerDisplayName: Brad

OwnerDisplayName: Dillie-O