问:
What part of this code brings up the msg box for selecting an item
I have paid a person to help me write a macro to populate tables in my spreadsheet.  I feel like I can usually understand some of the code that is written, but this is beyond me.  I'm just trying to learn how to do this for myself.</p>

```<code>Option Explicit
Option Base 1
Dim s_no() As String
Sub createReport()
start_win.Show
End Sub

Sub ook()

Dim last As Integer

ReDim s_no(1 To 1)

If Not Sheet1.Range("A2").Value = "" Then
    s_no(1) = Sheet1.Range("A2").Value
Else
    MsgBox "Empty sheet"
End If

last = Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
Dim i As Integer
For i = 2 To last
    If already_exists(Sheet1.Range("A" & CStr(i)).Value) = False Then
        ReDim Preserve s_no(1 To UBound(s_no) + 1)
        s_no(UBound(s_no)) = Sheet1.Range("A" & CStr(i)).Value
    End If
Next

For i = 1 To UBound(s_no)
    Debug.Print s_no(i)
Next
End Sub

Function already_exists(trial)
already_exists = False
Dim i As Integer
For i = 1 To UBound(s_no)
    If s_no(i) = trial Then
        already_exists = True
        Exit Function
    End If
Next
End Function
</code>```

答:
You paid someone to write that?  I'd ask for my money back.

If you supply the code within the start_win form I can rip that apart to if you want.

I've added comments to each line explaining.

```<code>Option Explicit                 'All variables must be declared first.
Option Base 1                   'Arrays start at 1 rather than 0.
Dim s_no() As String            'Global array variable.
                                'Available to all procedures in the module.

Sub createReport()
start_win.Show                  'Open and display a form called `start_win`.
                                'Form will likely contain code as well.
End Sub

Sub ook()                       'Reference to disc-worlds librarian?
                                '(and the name of this procedure)

Dim last As Integer             'The 'last' variable will hold values between
                                '–32,768 to 32,767.
                                'Terrible for holding row numbers.

ReDim s_no(1 To 1)              'The global variable is reassigned as an
                                'array containing 1 element.

If Not Sheet1.Range("A2").Value = "" Then   'Sheet1 is the sheet codename
                                            '(name not in brackets in Project explorer).
                                            'If cell A2 is an empty string then go to
                                            'next line, otherwise message box.

    s_no(1) = Sheet1.Range("A2").Value      'Place value from A2 into "s_no(1)"
                                            'element of variable.
Else
    MsgBox "Empty sheet"                    'If cell A2 was an empty string then
                                            'jump to this line.
End If

last = Cells(Sheet1.Rows.Count, 1).End(xlUp).Row    'Get the last row number from the
                                                    'sheet with codename Sheet1 and
                                                    'store in 'last' variable.
                                                    'Didn't I say that was a terrible idea?
                                                    'This line will fail if the last
                                                    'row is >32,767 (Overflow error).

Dim i As Integer                                    'Again, terrible idea - integer for row
                                                    'numbers... no.  Use LONG instead.

For i = 2 To last                                   'Step from row 2 to last row
                                                    '(providing error hasn't happened).

    If already_exists(Sheet1.Range("A" & CStr(i)).Value) = False Then   'Pass the value from
                                                                        'row number 'i' in column A
                                                                        'to the 'already_exists' procedure
                                                                        'where it will be called 'trial'
                                                                        '"Sheet1.Cells(i,2)" would be better.

        ReDim Preserve s_no(1 To UBound(s_no) + 1)                      'Increase the size of the 's_no'
                                                                        'array while keeping an values it
                                                                        'already holds.

        s_no(UBound(s_no)) = Sheet1.Range("A" & CStr(i)).Value          'Place the value from column A
                                                                        'in the array.
    End If
Next

For i = 1 To UBound(s_no)   'Cycle through the array.
    Debug.Print s_no(i)     'Place the value from the array in the immediate window.
Next
End Sub

Function already_exists(trial)      'Function to return a variant value
                                    '(should specify the return type).

already_exists = False              'Start as False.. so it's a boolean.
                                    'Be better to declare that in the function name.

Dim i As Integer                    'There's that integer again.  Just stop...

For i = 1 To UBound(s_no)           'Cycle through each element in 's_no' array.

    If s_no(i) = trial Then         'Does that element equal the one passed
                                    'from the main procedure?

        already_exists = True       'If it does then return TRUE to the main procedure.

        Exit Function               'Exit the function and jump back to the main procedure.
                                    'Would be the better to exit the loop and have one
                                    'exit point for the function.
    End If
Next
End Function
</code>```

Edit:

As a follow on this is how I'd write the ook procedure and do away with the already_exists function.

```<code>Sub ook()

    Dim lLast As Long      'Holds last row number.
    Dim i As Long          'Holds current row number.
    Dim s_no As Object     'Define an object.
    Dim key As Variant     'Use this to step through the populated dictionary.

    Set s_no = CreateObject("Scripting.Dictionary") 'Define it as a dictionary.

    With Sheet1
        lLast = .Cells(.Rows.Count, 1).End(xlUp).Row

        'Previously assumed that A2 would hold a value,
        'so if last row in column A is 1 then A2 will be blank
        'and the sheet is empty.
        If lLast <> 1 Then

            For i = 2 To lLast
                'Does the value already exist in the dictionary object?
                If Not s_no.exists(.Cells(i, 1).Value) Then
                    s_no.Add .Cells(i, 1).Value, .Cells(i, 1).Value 'It doesn't, so add it.
                End If
            Next i

            For Each key In s_no
                Debug.Print s_no(key)
            Next key

        Else
            'Nothing else should happen if the sheet is empty.
            MsgBox "Empty sheet", vbCritical + vbOKOnly

        End If
    End With

End Sub
</code>```

Another edit:  Dictionaries - sorry, don't usually link outside this site but it is a good tutorial.

Body:
I have paid a person to help me write a macro to populate tables in my spreadsheet.  I feel like I can usually understand some of the code that is written, but this is beyond me.  I'm just trying to learn how to do this for myself.

Option Explicit
Option Base 1
Dim s_no() As String
Sub createReport()
start_win.Show
End Sub

Sub ook()

Dim last As Integer

ReDim s_no(1 To 1)

If Not Sheet1.Range("A2").Value = "" Then
    s_no(1) = Sheet1.Range("A2").Value
Else
    MsgBox "Empty sheet"
End If

last = Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
Dim i As Integer
For i = 2 To last
    If already_exists(Sheet1.Range("A" & CStr(i)).Value) = False Then
        ReDim Preserve s_no(1 To UBound(s_no) + 1)
        s_no(UBound(s_no)) = Sheet1.Range("A" & CStr(i)).Value
    End If
Next

For i = 1 To UBound(s_no)
    Debug.Print s_no(i)
Next
End Sub

Function already_exists(trial)
already_exists = False
Dim i As Integer
For i = 1 To UBound(s_no)
    If s_no(i) = trial Then
        already_exists = True
        Exit Function
    End If
Next
End Function

Body:
You paid someone to write that?  I'd ask for my money back.

If you supply the code within the start_win form I can rip that apart to if you want.

I've added comments to each line explaining.

Option Explicit                 'All variables must be declared first.
Option Base 1                   'Arrays start at 1 rather than 0.
Dim s_no() As String            'Global array variable.
                                'Available to all procedures in the module.

Sub createReport()
start_win.Show                  'Open and display a form called `start_win`.
                                'Form will likely contain code as well.
End Sub

Sub ook()                       'Reference to disc-worlds librarian?
                                '(and the name of this procedure)

Dim last As Integer             'The 'last' variable will hold values between
                                '–32,768 to 32,767.
                                'Terrible for holding row numbers.

ReDim s_no(1 To 1)              'The global variable is reassigned as an
                                'array containing 1 element.

If Not Sheet1.Range("A2").Value = "" Then   'Sheet1 is the sheet codename
                                            '(name not in brackets in Project explorer).
                                            'If cell A2 is an empty string then go to
                                            'next line, otherwise message box.

    s_no(1) = Sheet1.Range("A2").Value      'Place value from A2 into "s_no(1)"
                                            'element of variable.
Else
    MsgBox "Empty sheet"                    'If cell A2 was an empty string then
                                            'jump to this line.
End If

last = Cells(Sheet1.Rows.Count, 1).End(xlUp).Row    'Get the last row number from the
                                                    'sheet with codename Sheet1 and
                                                    'store in 'last' variable.
                                                    'Didn't I say that was a terrible idea?
                                                    'This line will fail if the last
                                                    'row is >32,767 (Overflow error).

Dim i As Integer                                    'Again, terrible idea - integer for row
                                                    'numbers... no.  Use LONG instead.

For i = 2 To last                                   'Step from row 2 to last row
                                                    '(providing error hasn't happened).

    If already_exists(Sheet1.Range("A" & CStr(i)).Value) = False Then   'Pass the value from
                                                                        'row number 'i' in column A
                                                                        'to the 'already_exists' procedure
                                                                        'where it will be called 'trial'
                                                                        '"Sheet1.Cells(i,2)" would be better.

        ReDim Preserve s_no(1 To UBound(s_no) + 1)                      'Increase the size of the 's_no'
                                                                        'array while keeping an values it
                                                                        'already holds.

        s_no(UBound(s_no)) = Sheet1.Range("A" & CStr(i)).Value          'Place the value from column A
                                                                        'in the array.
    End If
Next

For i = 1 To UBound(s_no)   'Cycle through the array.
    Debug.Print s_no(i)     'Place the value from the array in the immediate window.
Next
End Sub

Function already_exists(trial)      'Function to return a variant value
                                    '(should specify the return type).

already_exists = False              'Start as False.. so it's a boolean.
                                    'Be better to declare that in the function name.

Dim i As Integer                    'There's that integer again.  Just stop...

For i = 1 To UBound(s_no)           'Cycle through each element in 's_no' array.

    If s_no(i) = trial Then         'Does that element equal the one passed
                                    'from the main procedure?

        already_exists = True       'If it does then return TRUE to the main procedure.

        Exit Function               'Exit the function and jump back to the main procedure.
                                    'Would be the better to exit the loop and have one
                                    'exit point for the function.
    End If
Next
End Function

Edit:

As a follow on this is how I'd write the ook procedure and do away with the already_exists function.

Sub ook()

    Dim lLast As Long      'Holds last row number.
    Dim i As Long          'Holds current row number.
    Dim s_no As Object     'Define an object.
    Dim key As Variant     'Use this to step through the populated dictionary.

    Set s_no = CreateObject("Scripting.Dictionary") 'Define it as a dictionary.

    With Sheet1
        lLast = .Cells(.Rows.Count, 1).End(xlUp).Row

        'Previously assumed that A2 would hold a value,
        'so if last row in column A is 1 then A2 will be blank
        'and the sheet is empty.
        If lLast <> 1 Then

            For i = 2 To lLast
                'Does the value already exist in the dictionary object?
                If Not s_no.exists(.Cells(i, 1).Value) Then
                    s_no.Add .Cells(i, 1).Value, .Cells(i, 1).Value 'It doesn't, so add it.
                End If
            Next i

            For Each key In s_no
                Debug.Print s_no(key)
            Next key

        Else
            'Nothing else should happen if the sheet is empty.
            MsgBox "Empty sheet", vbCritical + vbOKOnly

        End If
    End With

End Sub

Another edit:  Dictionaries - sorry, don't usually link outside this site but it is a good tutorial.


来源: stackexchange

问:
Session / Log tables keys design question
I have almost always heard people say not to use FKs with user session and any log tables as those are usually High write tables and once written data almost always tays forever without any updates or deletes.

But the question is I have colunms like these:
User_id (link a session or activity log to the user)
activity_id (linking the log activity table to the system activity lookup table)
session_id (linking the user log table with the parent session)
... and there are 4-5 more colunms.

So if I dont use FKs then how will i "relate" these colunms? Can i join tables and get the user info without FKs? Can i write correct data without FKs? Any performance impact or do people just talk and say this is a no no?

Another question I have is if i dont use FKs can i still connect my data with lookup tables?

答:
In fact, you can build the whole database without real FKs in mysql. If you're using MyISAM as a storage engine, the FKs aren't real anyway.
You can nevertheless do all the joins you like, as long as the join keys match.

Performance impact depends on how much data you stuff into a referenced table. It takes extra time if you have a FK in a table and insert data into it, or update a FK value. Upon insertion or modification, the FK needs to be looked up in the referenced table to ensure the reference integrity.

On highly used tables which don't really need reference integrity, I'd just stick with loose columns instead of FKs.

AFAIK InnoDB is currently the only one supporting real foreign keys (unless MySQL 5.5 got new or updated storage engines which support them as well). Storage engines like MyISAM do support the syntax, but don't actually validate the referential integrity.

ContentLicense: CC BY-SA 2.5


问:
Big perfect rectangle from small rectangles with subjectivities
I want to arrange rectangles which will form a big perfect rectangle with no spaces- big rectangle size known.

I prefer to do it in Excel but even python could be a good solution. - for starting idea of algorithms is also welcome.

Each rectangle has a size length and width ( no flipping allowed)and a Y level.

I know for sure that there is a solution and I know exactly the big rectangle size.

If I will put the big rectangle on axis, the Y axis will have few (3-10) levels for example the points (0,100) (0,250) (0,1000).

The bottom of each small rectangle should start on a level pre-defined (Y axis)
So actually for each level I have the specific rectangles the I need to decide the order.

My input looks like:

rec. number

Width

Hight

starting level (Y axis)

Expected output if the big rectangle bottom left point will be on (0,0) axis:

Rec. No.

bottom left point where the rec. should start

Any Ideas ? I know that it is a hard problem but I have small number of rectangle ..

Thank you

答:
You can in numpy first initialize an empty grid and then access the different entries individually

```<code>grid=np.zeros(1000,1000)
for in range(phases)
grid[startx[i]:startx[i]+with,starty[i]:starty[i]+Hight[i]==rec_number[i]
</code>```

startx is the array including the starting points in x direction
the other just follow the same principle of your input

ContentLicense: CC BY-SA 3.0

Body:
You can in numpy first initialize an empty grid and then access the different entries individually

grid=np.zeros(1000,1000)
for in range(phases)
grid[startx[i]:startx[i]+with,starty[i]:starty[i]+Hight[i]==rec_number[i]

startx is the array including the starting points in x direction
the other just follow the same principle of your input


问:
Javascript function not working after validation
Currently doing a function whereby users can input their enquiries which will be sent to the database and retrieved by the admin, but the function of adding enquiry stopped working after i added a validation code, the problem lies in the validation but i cant seem to find the error.

My js code:

```<code>var userid = localStorage.getItem("userid");
var Texttitle;
var Textenquiry;

function validate() {
    var validate = true;

    if (Texttitle == "") {
        alert("Title cannot be empty");
        $("#Texttitle").focus();
        validate = false;
    }

    if (Textenquiry == "") {
        alert("Enquiry cannot be empty");
        $("#Textenquiry").focus();
        validate = false;
    }

    return validate;
}

function addenquiry() {

    Texttitle = $("#Texttitle").val();
    Textenquiry = $("#Textenquiry").val();

    if (validate()) {

        var xmlhttp = new XMLHttpRequest();
        var url = serverURL() + "/addenquiry.php";
        url += "?userid=" + userid + "&Texttitle=" + Texttitle + "&Textenquiry=" + Textenquiry;
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            addEnquiry(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

function addEnquiry(response) {
    var arr = JSON.parse(response);
    if (arr[0].result == 1) {
        alert("Thank You for your enquiry!")
    }
    else {
        alert("Sorry please try again");
    }

}
</code>```

My Html:

```<code> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
     <label class="mdl-textfield__label" for="Texttitle">Title</label>
       <input class="mdl-textfield__input" rows="2" type="text" id="Texttitle">
 </div>
    <br>
    <br>
 <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
       <label class="mdl-textfield__label" for="Textenquiry">Message</label>
         <input class="mdl-textfield__input" rows="2" type="text" id="Textenquiry">
 </div>
    <br>
    <br>
    <button class="mdl-button mdl-color--primary mdl-js-button mdl-color-text--white full-width" onclick="addenquiry()">Submit</button>
 <div class="material-icons mdl-badge mdl-badge--overlap">�</div>
</code>```

My function was running well previously before i entered the validation codes in, after my attempt at validating, the function is unable to send enquiries into my database, would appreciate some help :).

答:
In your validate function, why have you duplicated your logic? You have:

```<code>if (Texttitle == "") {
    alert("Title cannot be empty");
    $("#Texttitle").focus();
    validate = false;

} if (Textenquiry == "") {
    alert("Enquiry cannot be empty");
    $("#Textenquiry").focus();
    validate = false;
}
</code>```

twice.

Also, your issue may be the */ at the end of your validate function

Body:
Currently doing a function whereby users can input their enquiries which will be sent to the database and retrieved by the admin, but the function of adding enquiry stopped working after i added a validation code, the problem lies in the validation but i cant seem to find the error.

My js code:

var userid = localStorage.getItem("userid");
var Texttitle;
var Textenquiry;

function validate() {
    var validate = true;

    if (Texttitle == "") {
        alert("Title cannot be empty");
        $("#Texttitle").focus();
        validate = false;
    }

    if (Textenquiry == "") {
        alert("Enquiry cannot be empty");
        $("#Textenquiry").focus();
        validate = false;
    }

    return validate;
}

function addenquiry() {

    Texttitle = $("#Texttitle").val();
    Textenquiry = $("#Textenquiry").val();

    if (validate()) {

        var xmlhttp = new XMLHttpRequest();
        var url = serverURL() + "/addenquiry.php";
        url += "?userid=" + userid + "&Texttitle=" + Texttitle + "&Textenquiry=" + Textenquiry;
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            addEnquiry(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

function addEnquiry(response) {
    var arr = JSON.parse(response);
    if (arr[0].result == 1) {
        alert("Thank You for your enquiry!")
    }
    else {
        alert("Sorry please try again");
    }

}

My Html:

     Title
       <input class="mdl-textfield__input" rows="2" type="text" id="Texttitle">

       Message
         <input class="mdl-textfield__input" rows="2" type="text" id="Textenquiry">

    <button class="mdl-button mdl-color--primary mdl-js-button mdl-color-text--white full-width" onclick="addenquiry()">Submit</button>

�

My function was running well previously before i entered the validation codes in, after my attempt at validating, the function is unable to send enquiries into my database, would appreciate some help :).

Body:
In your validate function, why have you duplicated your logic? You have:

if (Texttitle == "") {
    alert("Title cannot be empty");
    $("#Texttitle").focus();
    validate = false;

} if (Textenquiry == "") {
    alert("Enquiry cannot be empty");
    $("#Textenquiry").focus();
    validate = false;
}

twice.

Also, your issue may be the */ at the end of your validate function


问:
Access request.format from Rails ApplicationController
I have a before_action filter in my ApplicationController. If the format of the request is 'application/json', I'd like to put an additional check requiring an API key. How do I check the request.format from the application controller? The line in question is:

```<code>  before_action :check_api_access, if: request.format.json?
</code>```

The error I'm getting is

undefined local variable or method `request' for ApplicationController:Class

答:
You need to use a lambda:</p>

```<code>before_action :check_api_access, if: -> { request.format.json? }
</code>```

Body:
I have a before_action filter in my ApplicationController. If the format of the request is 'application/json', I'd like to put an additional check requiring an API key. How do I check the request.format from the application controller? The line in question is:

  before_action :check_api_access, if: request.format.json?

The error I'm getting is

undefined local variable or method `request' for ApplicationController:Class

Body:
You need to use a lambda:

before_action :check_api_access, if: -> { request.format.json? }


问:
Oracle Enterprise Manager Cloud Control 12c RAC
We've just provisioned a 2 node Oracle 12c RAC with the help of an outside vendor, and we have very little internal knowledge or experience of Oracle (2 guys used to use Oracle 9i elsewhere).

I've been asked to setup Enterprise Manager to make the system easier to administer and monitor by our Service Desk as I've used Enterprise Manager on an 11g database at my previous employment.

So, here I am, researching and investigating and being baffled by what's required as far as Enterprise Manager which has moved on from Grid Control to Cloud Control, and is now supposed to be installed onto a separate server to either of the RAC nodes, and do I need to install Web Logic server etc.

I have a separate server ready to go, could someone give me some guidance on what exactly I need to install and in what ordert so we have a console that can administer this and any future Oracle systems we roll out.

Appreciate any and all replies.

答:
The Oracle Enterprise Manager transition from Grid Control to Cloud Control was done to make the enterprise monitoring functionality more robust.  The transition allowed them to incorporate more Oracle products into the suite through various licenses and updates, and also add more flexibility in reporting (through the addition of BI Publisher addons) and custom monitoring (via metric extensions).  The Incident Management suite has also been completely revamped.

Aside from that, the installation is fairly straightforward, especially when concerning an Oracle RAC as it's primary repository.  The new version of OEM sits as an application layer on top of an Oracle Web Logic cluster.  What this means is that the installation INCLUDES Web Logic.  It is not necessary to install this at all.  The installation will build a Web Logic cluster based on the high availability configuration you choose during setup and will point to the repository you choose.

Upon installation, you can access OEM in the method that is described during installation.  You will also see a Web logic console access URL that allows you to manipulate and configure the backend WebLogic instance that runs the application.  If you are not very familiar with the architecture, I would leave the WebLogic portion alone.

I would suggest using blogs or videos of actual customers running the installation.  The Oracle Documentation is robust, but can also be very cumbersome.  Without knowing your full environment (Linux version, Windows version, etc?) I wouldn't be able to provide direct assistance.  Here is an example of a solid installation guide:

OEM Installation


问:
What is the work flow of this Spring Boot program
I am a beginner in spring boot application and I recently came across this project having following 3 packages

com.packagename.controller

com.packagname.domain

com.packagename.service

In domain package, there is a single class named Student
having the following code

```<code>private String name;

public Student() {
}

public Student(String name) {
        this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
        this.name = name;
}

@Override
public String toString() {
        return "Student [name=" + name + "]";
}
</code>```

Then in Service package,
  class StudentService

```<code>package com.javTpoint.service;

import org.springframework.stereotype.Service;

import com.javTpoint.domain.Student;

@Service
public class StudentService {

    public Student saveStudent(Student student) {
        student.setName(student.getName() + "123");
        return student;
    }
}
</code>```

And finally in Controller package,
Student class

```<code>package com.javTpoint.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.javTpoint.domain.Student;
import com.javTpoint.service.StudentService;

@RestController
public class StudentController {
@Autowired
private StudentService studentService;

    @RequestMapping(value = "/student", method = RequestMethod.POST)
    Student saveStuden(@RequestBody Student student) {
    System.out.println(student);
        return studentService.saveStudent(student);
    }
}
</code>```

The program asked to use this is Postman
I just want to understand the how the workflow is taking place like
why @RequestBody is used inside saveStuden() method in controller.

答:
The @RequestBody annotation just before the student parameter means the student object will handle data you will send to /student uri via a POST request.

The data should be sent in JSON format:

for example:

```<code>{
    name: "Joe Doe"
}
</code>```

The studentService.saveStudent(student)will alter the data of the student object and the output would be.

```<code>{
    name: "Joe Doe123"
}
</code>```

Body:
I am a beginner in spring boot application and I recently came across this project having following 3 packages

com.packagename.controller

com.packagname.domain

com.packagename.service

In domain package, there is a single class named Student
having the following code

private String name;

public Student() {
}

public Student(String name) {
        this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
        this.name = name;
}

@Override
public String toString() {
        return "Student [name=" + name + "]";
}

Then in Service package,
  class StudentService

package com.javTpoint.service;

import org.springframework.stereotype.Service;

import com.javTpoint.domain.Student;

@Service
public class StudentService {

    public Student saveStudent(Student student) {
        student.setName(student.getName() + "123");
        return student;
    }
}

And finally in Controller package,
Student class

package com.javTpoint.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.javTpoint.domain.Student;
import com.javTpoint.service.StudentService;

@RestController
public class StudentController {
@Autowired
private StudentService studentService;

    @RequestMapping(value = "/student", method = RequestMethod.POST)
    Student saveStuden(@RequestBody Student student) {
    System.out.println(student);
        return studentService.saveStudent(student);
    }
}

The program asked to use this is Postman
I just want to understand the how the workflow is taking place like
why @RequestBody is used inside saveStuden() method in controller.

Body:
The @RequestBody annotation just before the student parameter means the student object will handle data you will send to /student uri via a POST request.

The data should be sent in JSON format:

for example:

{
    name: "Joe Doe"
}

The studentService.saveStudent(student)will alter the data of the student object and the output would be.

{
    name: "Joe Doe123"
}


问:
Run Watir on a client browser
I wish to develop a browser extension that receives voice command input and simulates users' actions such as link clicking/following, button pushing, etc. I found that Watir might be useful for this task, but is it possible to run Watir on a client browser?

In my understanding, we cannot execute Ruby on a client directly, right?
Is there any Watir clone for Javascript?

答: Watir requires that both it and Ruby be installed on the client machine. This cannot be done through a browser extension.</p>

Title: Run Watir on a client browser


问:
Creating a new column with 0 and 1 values based on regex result
My dataframe has values:

```<code>data_df

0         student
1         sample text
2         student
3         no students
4         sample texting
5         random sample
</code>```

I use regex to extract rows with word 'student' and my result is as below:

```<code>regexdf
0         student
2         student
</code>```

I aim to create a new column in the main dataframe with 0 and 1 values. i.e. row 0 should be 1, row 5 should have zero.(As the 'regexdf' has 'student' in row 0 and 2) How do I match the indexes in both and create a column?

答:
Using regex:

```<code>data_df = data_df.assign(regexdf = data_df[1].str.extract(r'(student)\b', expand=False))
data_df['student'] = data_df['regexdf'].notnull().mul(1)
print(data_df)
</code>```

Output:

```<code>                 1  regexdf  student
0         student  student        1
1     sample text      NaN        0
2         student  student        1
3     no students      NaN        0
4  sample texting      NaN        0
5   random sample      NaN        0
</code>```

Edit

```<code>df_out = data_df.join(regexdf, rsuffix='regex')

df_out['pattern'] = df_out['1regex'].notnull().mul(1)

df_out['Count_Pattern'] = df_out['pattern'].cumsum()

print(df_out)
</code>```

Output:

```<code>                1   1regex  pattern  Count_Pattern
0         student  student        1              1
1     sample text      NaN        0              1
2         student  student        1              2
3     no students      NaN        0              2
4  sample texting      NaN        0              2
5   random sample      NaN        0              2
</code>```

Body:
My dataframe has values:

data_df

0         student
1         sample text
2         student
3         no students
4         sample texting
5         random sample

I use regex to extract rows with word 'student' and my result is as below:

regexdf
0         student
2         student

I aim to create a new column in the main dataframe with 0 and 1 values. i.e. row 0 should be 1, row 5 should have zero.(As the 'regexdf' has 'student' in row 0 and 2) How do I match the indexes in both and create a column?

Body:
Using regex:

data_df = data_df.assign(regexdf = data_df[1].str.extract(r'(student)\b', expand=False))
data_df['student'] = data_df['regexdf'].notnull().mul(1)
print(data_df)

Output:

                 1  regexdf  student
0         student  student        1
1     sample text      NaN        0
2         student  student        1
3     no students      NaN        0
4  sample texting      NaN        0
5   random sample      NaN        0

Edit

df_out = data_df.join(regexdf, rsuffix='regex')

df_out['pattern'] = df_out['1regex'].notnull().mul(1)

df_out['Count_Pattern'] = df_out['pattern'].cumsum()

print(df_out)

Output:

                1   1regex  pattern  Count_Pattern
0         student  student        1              1
1     sample text      NaN        0              1
2         student  student        1              2
3     no students      NaN        0              2
4  sample texting      NaN        0              2
5   random sample      NaN        0              2


问:
Overriding bootstrap styles, not working
I'm trying to make a simple CSS file to make my app look decently, but I have a problem with it

```<code><div class='container-fluid'>
<div id="nav">
        <div class='col-sm-6' align="center">
                <h2>Utwórz nową sesje</h2>
                <br><br>
                <input class="form-control mr-sm-2" type="text" aria-label="Search"><br>
                <a class="btn btn-primary btn-md" href="#" role="button">Stwórz</a>
            </div>

        <div  class='col-sm-6' align="center">
            <h2>Dołącz do istniejącej sesji</h2>
            <br><br>
            <input class="form-control mr-sm-2" type="text" aria-label="Search"><br>
            <a class="btn btn-primary btn-ms" href="#" role="button">Dołącz</a>
        </div>

</div>
</code>```

And no matter if I make it

```<code>#bootstap-overrides  .container-fluid {
    background-color: #3b5998;
}
</code>```

Or

```<code>.container-fluid {
    background-color: #3b5998;
}
</code>```

or

```<code>.nav {
    background-color: #3b5998;
}
</code>```

Background is still white, as if bootstrap was overrding it. I'm a beggineer at CSS.

EDIT:

```<code>@Component({
selector: 'home',
templateUrl: './home.component.css'})
</code>```

The templateUrl field was wrong, so i fixed it. However, now the entire site appears white.

答:
If you want to change the whole class as example '.container-fluid', you could add the tag !important.

e.g.:

```<code>.container-fluid {
background-color: #3b5998 !important;
}
</code>```

But in most cases it is more recommended to create child elements as you did.
You have to use your 'nav'-element as follows in your css:

```<code>#nav {
background-color: #3b5998;
}
</code>```

You have to use '#' instead of '.', because you declared it as an ID- not a CLASS-element

Body:
I'm trying to make a simple CSS file to make my app look decently, but I have a problem with it

Utwórz nową sesje

                <input class="form-control mr-sm-2" type="text" aria-label="Search">

                Stwórz

Dołącz do istniejącej sesji

            <input class="form-control mr-sm-2" type="text" aria-label="Search">

            Dołącz

And no matter if I make it

#bootstap-overrides  .container-fluid {
    background-color: #3b5998;
}

Or

.container-fluid {
    background-color: #3b5998;
}

or

.nav {
    background-color: #3b5998;
}

Background is still white, as if bootstrap was overrding it. I'm a beggineer at CSS.

EDIT:

@Component({
selector: 'home',
templateUrl: './home.component.css'})

The templateUrl field was wrong, so i fixed it. However, now the entire site appears white.

Body:
If you want to change the whole class as example '.container-fluid', you could add the tag !important.

e.g.:

.container-fluid {
background-color: #3b5998 !important;
}

But in most cases it is more recommended to create child elements as you did.
You have to use your 'nav'-element as follows in your css:

#nav {
background-color: #3b5998;
}

You have to use '#' instead of '.', because you declared it as an ID- not a CLASS-element


问:
Global Cordova 7.1.0 fails to build for iOS remote device
To reproduce my issue follow these steps:

Visual Studio 2017 Community - version 15.4.4

Visual Studio Tools for Apache Cordova - version 15.120.6728.2

Create a Blank App (Apache Cordova)

Changed config.xml -> Cordova Toolset -> Global Cordova 7.1.0

Install all the required software on MAC

Configure Remote Agent Configuration in VS Options

Start Debugging - Debug mode - iOS platform - Remote Device

This is the result:

Sending the build to the remote build server

Incremental Build: False

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018: The "VsTac" task failed unexpectedly.

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018: System.IO.FileNotFoundException: Could not find file 'C:\Users\uadmin\AppData\Local\Temp\appAsTgz.tgz'.

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018: File name: 'C:\Users\uadmin\AppData\Local\Temp\appAsTgz.tgz'

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at System.IO.FileStream..ctor(String path, FileMode mode)

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.RemoteBuild.AppAsTgzStream(String changeTimeFile, JObject lastChangeTimesMap)

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.RemoteBuild.Build()

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.VsTac.BuildPlatform()

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.VsTac.Execute()

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()

1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(256,5): error MSB4018:    at Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext()

1>Done building project "BlankCordovaApp1.jsproj" -- FAILED.

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========

Can anyone from the Cordova development team look into this issue please?

This is a screenshot of the full Build output:
https://i.stack.imgur.com/oyPW1.jpg

答: Downgrade from node 8.x+ to node 6.x and try again.</p>


问:
Read a php table on my page and put the data in a pdf file
I try to use fpdf to take the data from my table and put it a PDF file, but I don't have any ideas to solve that.

Anyone have an example or any way to do it?

答:
Use tcpdf instead

Here is an example by Nicola Asuni:

```<code>//============================================================+
// File name   : example_045.php
// Begin       : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 045 for TCPDF class
//               Bookmarks and Table of Content
//
/ / Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               www.tecnick.com
//               info@tecnick.com
 //============================================================+

 /**
 * Creates an example PDF TEST document using TCPDF
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Example: Bookmarks and Table of Content
 * @author Nicola Asuni
 * @since 2008-03-04
 */

 // Include the main TCPDF library (search for installation path).
  require_once('tcpdf_include.php');

 // create new PDF document
 $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

 // set document information
 $pdf->SetCreator(PDF_CREATOR);
 $pdf->SetAuthor('Nicola Asuni');
 $pdf->SetTitle('TCPDF Example 045');
 $pdf->SetSubject('TCPDF Tutorial');
 $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

  // set default header data
  $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH,
  PDF_HEADER_TITLE.' 045', PDF_HEADER_STRING);

  // set header and footer fonts
   $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
   $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

   // set default monospaced font
   $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

   // set margins
  $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
  $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
   $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

  // set auto page breaks
  $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

  // set image scale factor
  $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

  // set some language-dependent strings (optional)
  if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
  }

  // ---------------------------------------------------------

  // set font
  $pdf->SetFont('times', 'B', 20);

  // add a page
  $pdf->AddPage();

   // set a bookmark for the current position
  $pdf->Bookmark('Chapter 1', 0, 0, '', 'B', array(0,64,128));

  // print a line using Cell()
   $pdf->Cell(0, 10, 'Chapter 1', 0, 1, 'L');

  // Create a fixed link to the first page using the * character
   $index_link = $pdf->AddLink();
    $pdf->SetLink($index_link, 0, '*1');
    $pdf->Cell(0, 10, 'Link to INDEX', 0, 1, 'R', false, $index_link);

    $pdf->AddPage();
    $pdf->Bookmark('Paragraph 1.1', 1, 0, '', '', array(128,0,0));
    $pdf->Cell(0, 10, 'Paragraph 1.1', 0, 1, 'L');

    $pdf->AddPage();
    $pdf->Bookmark('Paragraph 1.2', 1, 0, '', '', array(128,0,0));
    $pdf->Cell(0, 10, 'Paragraph 1.2', 0, 1, 'L');

    $pdf->AddPage();
    $pdf->Bookmark('Sub-Paragraph 1.2.1', 2, 0, '', 'I', array(0,128,0));
    $pdf->Cell(0, 10, 'Sub-Paragraph 1.2.1', 0, 1, 'L');

     $pdf->AddPage();
     $pdf->Bookmark('Paragraph 1.3', 1, 0, '', '', array(128,0,0));
     $pdf->Cell(0, 10, 'Paragraph 1.3', 0, 1, 'L');

      // fixed link to the first page using the * character
      $html = '<a href="#*1" style="color:blue;">link to INDEX (page 1)</a>';
     $pdf->writeHTML($html, true, false, true, false, '');

    // add some pages and bookmarks
     for ($i = 2; $i < 12; $i++) {
        $pdf->AddPage();
        $pdf->Bookmark('Chapter '.$i, 0, 0, '', 'B', array(0,64,128));
         $pdf->Cell(0, 10, 'Chapter '.$i, 0, 1, 'L');
      }

      // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

       // add a new page for TOC
       $pdf->addTOCPage();

      // write the TOC title
      $pdf->SetFont('times', 'B', 16);
       $pdf->MultiCell(0, 0, 'Table Of Content', 0, 'C', 0, 1, '', '', true, 0);
       $pdf->Ln();

      $pdf->SetFont('dejavusans', '', 12);

      // add a simple Table Of Content at first page
       // (check the example n. 59 for the HTML version)
        $pdf->addTOC(1, 'courier', '.', 'INDEX', 'B', array(128,0,0));

           // end of TOC page
            $pdf->endTOCPage();

        // ---------------------------------------------------------

     //Close and output PDF document
     $pdf->Output('example_045.pdf', 'I');

          //============================================================+
       // END OF FILE
         //============================================================+
</code>```

Body:
Use tcpdf instead

Here is an example by Nicola Asuni:

//============================================================+
// File name   : example_045.php
// Begin       : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 045 for TCPDF class
//               Bookmarks and Table of Content
//
/ / Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               www.tecnick.com
//               info@tecnick.com
 //============================================================+

 /**
 * Creates an example PDF TEST document using TCPDF
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Example: Bookmarks and Table of Content
 * @author Nicola Asuni
 * @since 2008-03-04
 */

 // Include the main TCPDF library (search for installation path).
  require_once('tcpdf_include.php');

 // create new PDF document
 $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

 // set document information
 $pdf->SetCreator(PDF_CREATOR);
 $pdf->SetAuthor('Nicola Asuni');
 $pdf->SetTitle('TCPDF Example 045');
 $pdf->SetSubject('TCPDF Tutorial');
 $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

  // set default header data
  $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH,
  PDF_HEADER_TITLE.' 045', PDF_HEADER_STRING);

  // set header and footer fonts
   $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
   $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

   // set default monospaced font
   $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

   // set margins
  $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
  $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
   $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

  // set auto page breaks
  $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

  // set image scale factor
  $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

  // set some language-dependent strings (optional)
  if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
  }

  // ---------------------------------------------------------

  // set font
  $pdf->SetFont('times', 'B', 20);

  // add a page
  $pdf->AddPage();

   // set a bookmark for the current position
  $pdf->Bookmark('Chapter 1', 0, 0, '', 'B', array(0,64,128));

  // print a line using Cell()
   $pdf->Cell(0, 10, 'Chapter 1', 0, 1, 'L');

  // Create a fixed link to the first page using the * character
   $index_link = $pdf->AddLink();
    $pdf->SetLink($index_link, 0, '*1');
    $pdf->Cell(0, 10, 'Link to INDEX', 0, 1, 'R', false, $index_link);

    $pdf->AddPage();
    $pdf->Bookmark('Paragraph 1.1', 1, 0, '', '', array(128,0,0));
    $pdf->Cell(0, 10, 'Paragraph 1.1', 0, 1, 'L');

    $pdf->AddPage();
    $pdf->Bookmark('Paragraph 1.2', 1, 0, '', '', array(128,0,0));
    $pdf->Cell(0, 10, 'Paragraph 1.2', 0, 1, 'L');

    $pdf->AddPage();
    $pdf->Bookmark('Sub-Paragraph 1.2.1', 2, 0, '', 'I', array(0,128,0));
    $pdf->Cell(0, 10, 'Sub-Paragraph 1.2.1', 0, 1, 'L');

     $pdf->AddPage();
     $pdf->Bookmark('Paragraph 1.3', 1, 0, '', '', array(128,0,0));
     $pdf->Cell(0, 10, 'Paragraph 1.3', 0, 1, 'L');

      // fixed link to the first page using the * character
      $html = '<a href="#*1" style="color:blue;">link to INDEX (page 1)</a>';
     $pdf->writeHTML($html, true, false, true, false, '');

    // add some pages and bookmarks
     for ($i = 2; $i < 12; $i++) {
        $pdf->AddPage();
        $pdf->Bookmark('Chapter '.$i, 0, 0, '', 'B', array(0,64,128));
         $pdf->Cell(0, 10, 'Chapter '.$i, 0, 1, 'L');
      }

      // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

       // add a new page for TOC
       $pdf->addTOCPage();

      // write the TOC title
      $pdf->SetFont('times', 'B', 16);
       $pdf->MultiCell(0, 0, 'Table Of Content', 0, 'C', 0, 1, '', '', true, 0);
       $pdf->Ln();

      $pdf->SetFont('dejavusans', '', 12);

      // add a simple Table Of Content at first page
       // (check the example n. 59 for the HTML version)
        $pdf->addTOC(1, 'courier', '.', 'INDEX', 'B', array(128,0,0));

           // end of TOC page
            $pdf->endTOCPage();

        // ---------------------------------------------------------

     //Close and output PDF document
     $pdf->Output('example_045.pdf', 'I');

          //============================================================+
       // END OF FILE
         //============================================================+


问:
What is the best way to group data pairs in javascript?
Instead of using associative arrays (objects), what is the best way to associate two values so they are always associated and can both be accessed as separate values? Associative arrays are annoying because their order isn't guaranteed and you can't access them using indexes.

I could create two separate arrays but if I randomize their order for display their association would not match, and if they are separate in code there is a good chance I can make a mistake when recording their values, putting them in the wrong order so they don't perfectly match up.

答:
In Javascript you can use multidimensional arrays:

```<code>var data = [
    [1, 2],
    [3, 4]
];

data[0][0]; // get '1'
data[0][1]; // get '2'
</code>```

Also if you need to associate data in a more abstract way, ES6 has WeakMaps:

```<code>var wm = new WeakMap();
var x = document.createElement("div");
wm.set(x, {foo: 1, bar: 7});

console.log(wm.get(x).bar) // get '7' from object you associated to HTMLElement
</code>```

Body:
In Javascript you can use multidimensional arrays:

var data = [
    [1, 2],
    [3, 4]
];

data[0][0]; // get '1'
data[0][1]; // get '2'

Also if you need to associate data in a more abstract way, ES6 has WeakMaps:

var wm = new WeakMap();
var x = document.createElement("div");
wm.set(x, {foo: 1, bar: 7});

console.log(wm.get(x).bar) // get '7' from object you associated to HTMLElement


问:
Nesting conditionals in Java
The Problem

Given the following code:

```<code>if (enforceLength && rawContents.length != recordLength) {
</code>```

Right now if enforceLength and rawContents does not match recordLength, it returns true and triggers our warning system. Some of our recordLength however are HEADER_DIFF characters longer than the rawContents.length.

So we are hoping to put an or on rawContents.length so that it can either match recordLength or recordLength + HEADER_DIFF.

Question

Is there a straightforward way to create an OR conditional on just the second part of this if statement? i.e. so that it triggers the alert if rawContents.length does not equal recordLength but it does not if recordLength happens to be exactly HEADER_DIFF longer than expected.

A failed attempt

One attempt that failed:

```<code>if (enforceLength && rawContents.length != recordLength + HEADER_DIFF
  || rawContents.length != recordLength)
</code>```

答:
This is a classic problem with trying to fold too much into one if statement through an irrational fear of the arrow pattern.

Surely this would be much clearer.

```<code>    if (enforceLength) {
        // Can be correct or out by HEADER_DIFF
        if(!(rawContents.length == recordLength + HEADER_DIFF || rawContents.length == recordLength)) {

        }
    }
</code>```

Title: Nesting conditionals in Java

Body:
The Problem

Given the following code:

if (enforceLength && rawContents.length != recordLength) {

Right now if enforceLength and rawContents does not match recordLength, it returns true and triggers our warning system. Some of our recordLength however are HEADER_DIFF characters longer than the rawContents.length.

So we are hoping to put an or on rawContents.length so that it can either match recordLength or recordLength + HEADER_DIFF.

Question

Is there a straightforward way to create an OR conditional on just the second part of this if statement? i.e. so that it triggers the alert if rawContents.length does not equal recordLength but it does not if recordLength happens to be exactly HEADER_DIFF longer than expected.

A failed attempt

One attempt that failed:

if (enforceLength && rawContents.length != recordLength + HEADER_DIFF
  || rawContents.length != recordLength)

Body:
This is a classic problem with trying to fold too much into one if statement through an irrational fear of the arrow pattern.

Surely this would be much clearer.

    if (enforceLength) {
        // Can be correct or out by HEADER_DIFF
        if(!(rawContents.length == recordLength + HEADER_DIFF || rawContents.length == recordLength)) {

        }
    }


问:
Choose dynamically a property of the component
Consider the following simple code:

```<code>export class TestComponent {
    mobileMessage: string;
    private mobileValidationMessages:ISchemeObject = {
        required: "Mobile is required",
        pattern:  "Mobile format is not correct"
    }

    setMessage(controlName: string): void {
        const x = <any>(controlName + "Message");
        this[x] = "Something";
    }
}
</code>```

With the above I want to call setMessage() with any argument I like, e.g.
setMessage("mobile") and be able to change mobileMessage. However, Typescript is complaining and does not allow me to do that. How may I achieve that?

答:
You can use Type something like:</p>

```<code>export class TestComponent {
 field: {[key: string]: string};

 setValue(fieldName: string, value: string) {
   this.field[fieldName] = value;
}
</code>```

Body:
Consider the following simple code:

export class TestComponent {
    mobileMessage: string;
    private mobileValidationMessages:ISchemeObject = {
        required: "Mobile is required",
        pattern:  "Mobile format is not correct"
    }

    setMessage(controlName: string): void {
        const x = <any>(controlName + "Message");
        this[x] = "Something";
    }
}

With the above I want to call setMessage() with any argument I like, e.g.
setMessage("mobile") and be able to change mobileMessage. However, Typescript is complaining and does not allow me to do that. How may I achieve that?

Body:
You can use Type something like:

export class TestComponent {
 field: {[key: string]: string};

 setValue(fieldName: string, value: string) {
   this.field[fieldName] = value;
}


问:
SQL Select Like Keywords in Any Order
I am building a Search function for a shopping cart site, which queries a SQL Server database.  When the user enters "Hula Hoops" in the search box, I want results for all records containing both "Hula" and "Hoop", in any order.  Furthermore, I need to search multiple columns (i.e. ProductName, Description, ShortName, MaufacturerName, etc.)

All of these product names should be returned, when searching for "Hula hoop":

Hula hoop

Hoop Hula

The Hoopity of xxhula sticks

(Bonus points if these can be ordered by relevance!)

答:
It sounds like you're really looking for full-text search, especially since you want to weight the words.

In order to use LIKE, you'll have to use multiple expressions (one per word, per column), which means dynamic SQL. I don't know which language you're using, so I can't provide an example, but you'll have to produce a statement that's like this:

For "Hula Hoops":

```<code>where (ProductName like '%hula%' or ProductName like '%hoops%')
  and (Description like '%hula%' or Description like '%hoops%')
  and (ShortName like '%hula%' or ShortName like '%hoops%')
</code>```

etc.

Unfortunately, that's really the only way to do it. Using Full Text Search would allow you to reduce your criteria to one per column, but you'll still have to specify the columns explicitly.

Since you're using SQL Server, I'm going to hazard a guess that this is a C# question. You'd have to do something like this (assuming you're constructing the SqlCommand or DbCommand object yourself; if you're using an ORM, all bets are off and you probably wouldn't be asking this anyway):

```<code>SqlCommand command = new SqlCommand();
int paramCount = 0;

string searchTerms = "Hula Hoops";

string commandPrefix = @"select *

from Products";

StringBuilder whereBuilder = new StringBuilder();

foreach(string term in searchTerms.Split(' '))
{
    if(whereBuilder.Length == 0)
    {
        whereBuilder.Append(" where ");
    }
    else
    {
        whereBuilder.Append(" and ");
    }

    paramCount++;

    SqlParameter param = new SqlParameter(string.Format("param{0}",paramCount), "%" + term + "%");

    command.Parameters.Add(param);

    whereBuilder.AppendFormat("(ProductName like @param{0} or Description like @param{0} or ShortName like @param{0})",paramCount);
}

command.CommandText = commandPrefix + whereBuilder.ToString();
</code>```

Title: SQL Select Like Keywords in Any Order

Body:
It sounds like you're really looking for full-text search, especially since you want to weight the words.

In order to use LIKE, you'll have to use multiple expressions (one per word, per column), which means dynamic SQL. I don't know which language you're using, so I can't provide an example, but you'll have to produce a statement that's like this:

For "Hula Hoops":

where (ProductName like '%hula%' or ProductName like '%hoops%')
  and (Description like '%hula%' or Description like '%hoops%')
  and (ShortName like '%hula%' or ShortName like '%hoops%')

etc.

Unfortunately, that's really the only way to do it. Using Full Text Search would allow you to reduce your criteria to one per column, but you'll still have to specify the columns explicitly.

Since you're using SQL Server, I'm going to hazard a guess that this is a C# question. You'd have to do something like this (assuming you're constructing the SqlCommand or DbCommand object yourself; if you're using an ORM, all bets are off and you probably wouldn't be asking this anyway):

SqlCommand command = new SqlCommand();
int paramCount = 0;

string searchTerms = "Hula Hoops";

string commandPrefix = @"select *

from Products";

StringBuilder whereBuilder = new StringBuilder();

foreach(string term in searchTerms.Split(' '))
{
    if(whereBuilder.Length == 0)
    {
        whereBuilder.Append(" where ");
    }
    else
    {
        whereBuilder.Append(" and ");
    }

    paramCount++;

    SqlParameter param = new SqlParameter(string.Format("param{0}",paramCount), "%" + term + "%");

    command.Parameters.Add(param);

    whereBuilder.AppendFormat("(ProductName like @param{0} or Description like @param{0} or ShortName like @param{0})",paramCount);
}

command.CommandText = commandPrefix + whereBuilder.ToString();


问:
create unit test for ws in golang
I use the gorilla web socket framework and use the following client to run the web socket locally and debug it

https://github.com/gorilla/websocket

```<code>ws = new WebSocket("ws://localhost:8080/mypath")
ws.onmessage = function(ev) { console.log(ev.data) }
ws.send("hello")
</code>```

This is working when I use it in the chrome console but my question if there is a way to do some unit test in go and avoid using the chrome console?

答:
Create a test server using the net/http/httptest package. Connect to that server using the Gorilla client. Read and write messages to test the connection.</p>

```<code>package main

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{}

func echo(w http.ResponseWriter, r *http.Request) {
    c, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        return
    }
    defer c.Close()
    for {
        mt, message, err := c.ReadMessage()
        if err != nil {
            break
        }
        err = c.WriteMessage(mt, message)
        if err != nil {
            break
        }
    }
}

func TestExample(t *testing.T) {
    // Create test server with the echo handler.
    s := httptest.NewServer(http.HandlerFunc(echo))
    defer s.Close()

    // Convert http://127.0.0.1 to ws://127.0.0.
    u := "ws" + strings.TrimPrefix(s.URL, "http")

    // Connect to the server
    ws, _, err := websocket.DefaultDialer.Dial(u, nil)
    if err != nil {
        t.Fatalf("%v", err)
    }
    defer ws.Close()

    // Send message to server, read response and check to see if it's what we expect.
    for i := 0; i < 10; i++ {
        if err := ws.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil {
            t.Fatalf("%v", err)
        }
        _, p, err := ws.ReadMessage()
        if err != nil {
            t.Fatalf("%v", err)
        }
        if string(p) != "hello" {
            t.Fatalf("bad message")
        }
    }
}
</code>```

Title: create unit test for ws in golang

Body:
I use the gorilla web socket framework and use the following client to run the web socket locally and debug it

https://github.com/gorilla/websocket

ws = new WebSocket("ws://localhost:8080/mypath")
ws.onmessage = function(ev) { console.log(ev.data) }
ws.send("hello")

This is working when I use it in the chrome console but my question if there is a way to do some unit test in go and avoid using the chrome console?

Body:
Create a test server using the net/http/httptest package. Connect to that server using the Gorilla client. Read and write messages to test the connection.

package main

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{}

func echo(w http.ResponseWriter, r *http.Request) {
    c, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        return
    }
    defer c.Close()
    for {
        mt, message, err := c.ReadMessage()
        if err != nil {
            break
        }
        err = c.WriteMessage(mt, message)
        if err != nil {
            break
        }
    }
}

func TestExample(t *testing.T) {
    // Create test server with the echo handler.
    s := httptest.NewServer(http.HandlerFunc(echo))
    defer s.Close()

    // Convert http://127.0.0.1 to ws://127.0.0.
    u := "ws" + strings.TrimPrefix(s.URL, "http")

    // Connect to the server
    ws, _, err := websocket.DefaultDialer.Dial(u, nil)
    if err != nil {
        t.Fatalf("%v", err)
    }
    defer ws.Close()

    // Send message to server, read response and check to see if it's what we expect.
    for i := 0; i < 10; i++ {
        if err := ws.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil {
            t.Fatalf("%v", err)
        }
        _, p, err := ws.ReadMessage()
        if err != nil {
            t.Fatalf("%v", err)
        }
        if string(p) != "hello" {
            t.Fatalf("bad message")
        }
    }
}


问:
Javascript regular expression: remove first and last slash
I have these strings in javascript:

```<code>/banking/bonifici/italia
/banking/bonifici/italia/
</code>```

and I would like to remove the first and last slash if it's exists.

I tried ^\/(.+)\/?$ but it doesn't work.

Reading some post in stackoverflow I found that php has trim function and I could use his javascript translation (http://phpjs.org/functions/trim:566) but I would prefer a "simple" regular expression.

答:
In case if using RegExp is not an option, or you have to handle corner cases while working with URLs (such as double/triple slashes or empty lines without complex replacements), or utilizing additional processing, here's a less obvious, but more functional-style solution:

const urls = [
  '//some/link///to/the/resource/',
  '/root',
  '/something/else',
];

const trimmedUrls = urls.map(url => url.split('/').filter(x => x).join('/'));

console.log(trimmedUrls);```

In this snippet filter() function can implement more complex logic than just filtering empty strings (which is default behavior).

Word of warning - this is not as fast as other snippets here.

Body:
I have these strings in javascript:

/banking/bonifici/italia
/banking/bonifici/italia/

and I would like to remove the first and last slash if it's exists.

I tried ^\/(.+)\/?$ but it doesn't work.

Reading some post in stackoverflow I found that php has trim function and I could use his javascript translation (http://phpjs.org/functions/trim:566) but I would prefer a "simple" regular expression.

Body:
In case if using RegExp is not an option, or you have to handle corner cases while working with URLs (such as double/triple slashes or empty lines without complex replacements), or utilizing additional processing, here's a less obvious, but more functional-style solution:

const urls = [
  '//some/link///to/the/resource/',
  '/root',
  '/something/else',
];

const trimmedUrls = urls.map(url => url.split('/').filter(x => x).join('/'));

console.log(trimmedUrls);

In this snippet filter() function can implement more complex logic than just filtering empty strings (which is default behavior).

Word of warning - this is not as fast as other snippets here.


问:
jelly checkbox not persisting in the UI
I have a jelly checkbox in in jenkins plugin :

```<code><f:optionalBlock name="sendFcmPayload"
                                 help="/plugin/artifactory/help/common/help-sendFcmPayload.html"
                                 inline="true" checked="${instance.sendFcmPayload}"
                                 title="Send details of this build to FCM">
</f:optionalBlock>
</code>```

I reference this value in the back end and the value received is correct in accordance to what I select in the UI, but the problem is every time I save the job configuration, the checkbox value in the UI doesn't persist.

Ive kept the optional block empty for now but based on it being checked or not I send a boolean value in the backend.

答:
Since you've left the body of the f:optionalBlock empty I assume all you need to do is bind the checkbox to a Boolean attribute. If so, the proper way to create the checkbox in the Jelly file is simply to use f:checkbox nested in f:entry like so:

```<code><f:entry title="Send details of this build to FCM" field="sendFcmPayload">
    <f:checkbox/>
</f:entry>
</code>```

I hope that helps.

Title: jelly checkbox not persisting in the UI

Body:
I have a jelly checkbox in in jenkins plugin :

<f:optionalBlock name="sendFcmPayload"
                                 help="/plugin/artifactory/help/common/help-sendFcmPayload.html"
                                 inline="true" checked="${instance.sendFcmPayload}"
                                 title="Send details of this build to FCM">
</f:optionalBlock>

I reference this value in the back end and the value received is correct in accordance to what I select in the UI, but the problem is every time I save the job configuration, the checkbox value in the UI doesn't persist.

Ive kept the optional block empty for now but based on it being checked or not I send a boolean value in the backend.

Body:
Since you've left the body of the f:optionalBlock empty I assume all you need to do is bind the checkbox to a Boolean attribute. If so, the proper way to create the checkbox in the Jelly file is simply to use f:checkbox nested in f:entry like so:

<f:entry title="Send details of this build to FCM" field="sendFcmPayload">
    <f:checkbox/>
</f:entry>

I hope that helps.


问:
Umbraco forces me to update Umbraco version on localhost
I´m trying to start a project I pulled from a colleague. No errors, no visible issue in the project.

The project starts without problems, but immediately force me to login to Umbraco. When I enter credentials for the Admin I am returned to a view that is forcing me to upgrade Umbraco version, something I do not want to do since the project is live on the Umbraco I´m currently on.

I have worked with Umbraco before on several project and never experienced this issue.

The project is running fine on my colleagues computer, connected to the same umbraco database. He has no changes that are not committed to the repository I´m pulling the project from.

Any ideas what might be causing this situation?

Umbraco v6.2.6 (Assembly version: 1.0.5906.18846)

Thanks and best regards, Martin

答:
Check that the version of Umbraco in the core DLLs matches the one that's in the "umbracoConfigurationStatus" appSettings key in your web.config file. If they're different, it'll try and get you to upgrade. Compare against your colleagues machine as well to see if there's a difference between what's on his machine and yours.

You get the upgrade message when Umbraco detects a mismatch between the version it's running and what the web.config file says the site is running.


问:
Sorting a partially linked list in sql
I have declared a task-priority list in SQL like so:

```<code>CREATE TABLE TaskList(
    id int not null primary key,
    execute_before int null,
    SomeData nvarchar(50) NOT NULL)
</code>```

I now want to select rows from this table such that the rows would be sorted by id, but any rows that "execute_before" a given row would be placed before such rows, again sorted by id.

So, if the table contains data like this:

```<code>id      execute_before
1       null
2       null
3       2
4       3
5       2
6       null
</code>```

the result should be like so:

```<code>id      execute_before
1       null
4       3
3       2
5       2
2       null
6       null
</code>```

My target SQL server is PostgreSQL, but I'm using it through Django, so either of these solutions is fine.

I'm currently solving the issue with a rather inefficient (gross understatement) sorting in code:

```<code>def annotate_exec_sort(queryset):
    from functools import cmp_to_key
    from django.db.models import Case, When

    def cmp(item1, item2):
        rb = item1.run_before
        while rb:
            if rb.id == item2.id:
                return -1
            rb = rb.run_before
        rb = item2.run_before
        while rb:
            if rb.id == item1.id:
                return 1
            rb = rb.run_before

        if item1.id < item2.id:
            return -1
        elif item1.id > item2.id:
            return 1
        return 0

    recs = sorted(queryset.all(), key=cmp_to_key(cmp))
    return queryset.annotate(srt=Case(*[When(id=r[1], then=r[0]) for r in enumerate([r.id for r in recs])],
                                      default=0,
                                      output_field=models.IntegerField()))
</code>```

答:
Here's a solution using PostgreSQL WITH RECURSIVE query to traverse the
dependency graph. The setup looks like this:

```<code>begin;

drop table if exists tasklist;

create table tasklist
(
    id int not null primary key,
    execute_before int null
);

\copy tasklist(id, execute_before) from stdin with csv delimiter E'\t' null as 'null'
1   null
2   null
3   2
4   3
5   2
6   null
\.

commit;
</code>```

And then the solution looks like the following:

```<code>with recursive s as
(
    select id, execute_before, 0 as level, '{}'::integer[] as before
      from tasklist t1
     where execute_before is null

 union

    select tasklist.id,
           tasklist.execute_before,
           level + 1 as level,
           case when tasklist.execute_before is not null
                then before || tasklist.id
                else before
            end as before
      from tasklist
           join s
             on tasklist.execute_before = s.id
     where not tasklist.id = any(before)
)
  select id, execute_before, level, before
    from s
order by level desc, id;
</code>```

which gives the following output:

```<code> id │ execute_before │ level │ before
════╪════════════════╪═══════╪════════
  4 │              3 │     2 │ {3,4}
  3 │              2 │     1 │ {3}
  5 │              2 │     1 │ {5}
  1 │              ¤ │     0 │ {}
  2 │              ¤ │     0 │ {}
  6 │              ¤ │     0 │ {}
(6 rows)
</code>```

Title: Sorting a partially linked list in sql

Body:
I have declared a task-priority list in SQL like so:

CREATE TABLE TaskList(
    id int not null primary key,
    execute_before int null,
    SomeData nvarchar(50) NOT NULL)

I now want to select rows from this table such that the rows would be sorted by id, but any rows that "execute_before" a given row would be placed before such rows, again sorted by id.

So, if the table contains data like this:

id      execute_before
1       null
2       null
3       2
4       3
5       2
6       null

the result should be like so:

id      execute_before
1       null
4       3
3       2
5       2
2       null
6       null

My target SQL server is PostgreSQL, but I'm using it through Django, so either of these solutions is fine.

I'm currently solving the issue with a rather inefficient (gross understatement) sorting in code:

def annotate_exec_sort(queryset):
    from functools import cmp_to_key
    from django.db.models import Case, When

    def cmp(item1, item2):
        rb = item1.run_before
        while rb:
            if rb.id == item2.id:
                return -1
            rb = rb.run_before
        rb = item2.run_before
        while rb:
            if rb.id == item1.id:
                return 1
            rb = rb.run_before

        if item1.id < item2.id:
            return -1
        elif item1.id > item2.id:
            return 1
        return 0

    recs = sorted(queryset.all(), key=cmp_to_key(cmp))
    return queryset.annotate(srt=Case(*[When(id=r[1], then=r[0]) for r in enumerate([r.id for r in recs])],
                                      default=0,
                                      output_field=models.IntegerField()))

Body:
Here's a solution using PostgreSQL WITH RECURSIVE query to traverse the
dependency graph. The setup looks like this:

begin;

drop table if exists tasklist;

create table tasklist
(
    id int not null primary key,
    execute_before int null
);

\copy tasklist(id, execute_before) from stdin with csv delimiter E'\t' null as 'null'
1   null
2   null
3   2
4   3
5   2
6   null
\.

commit;

And then the solution looks like the following:

with recursive s as
(
    select id, execute_before, 0 as level, '{}'::integer[] as before
      from tasklist t1
     where execute_before is null

 union

    select tasklist.id,
           tasklist.execute_before,
           level + 1 as level,
           case when tasklist.execute_before is not null
                then before || tasklist.id
                else before
            end as before
      from tasklist
           join s
             on tasklist.execute_before = s.id
     where not tasklist.id = any(before)
)
  select id, execute_before, level, before
    from s
order by level desc, id;

which gives the following output:

 id │ execute_before │ level │ before
════╪════════════════╪═══════╪════════
  4 │              3 │     2 │ {3,4}
  3 │              2 │     1 │ {3}
  5 │              2 │     1 │ {5}
  1 │              ¤ │     0 │ {}
  2 │              ¤ │     0 │ {}
  6 │              ¤ │     0 │ {}
(6 rows)


问:
Entity Types cannot share table | Not actually the same table though
I have two databases that so happen to have the same table name. Entity is giving me an InvalidOperationException stating "The entity types 'PmsUser' and 'AcctUser' cannot share table 'NGUSERS'...

I created these using a code first approach.

My models for both look something like

```<code>[Table("NGUSERS")]
public partial class AcctUser
{
    ...
</code>```

and

```<code>[Table("NGUSERS")]
public partial class PmsUser
{
    ...
</code>```

They each have their own respective connection string to differing databases. What do I need to do to get it to allow the same table name (modifying the Database isn't an option)?

答:
Use two ModelBuilder instead of attributes. Then pass the created DbModel to the DbConnection. Or set the database name in the DbContext. See Entity Framework Connections and Models.

This base class helps to register the model builders with the DbContext:

```<code>public abstract class ModelBuilderBase {

    protected readonly DbModelBuilder ModelBuilder;

    protected ModelBuilderBase(DbModelBuilder modelBuilder) {
        ModelBuilder = modelBuilder;
    }

    public abstract void BuildModel();
}
</code>```

ModelBuilder implementation:

```<code>public class ModelBuilder1 : ModelBuilderBase {

    public ModelBuilder1 (DbModelBuilder modelBuilder) : base(modelBuilder)
    { }

    public override void BuildModel() {

        ModelBuilder.Entity<AcctUser>().ToTable("NGUSERS");
    }
}
</code>```

DbContext:

```<code>public class DbContext1 : DbContext {
    public DbContext1() : base("Database1") /* set DB name */ {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        var modelBuilders = new List<ModelBuilderBase> {
            new ModelBuilder1(modelBuilder)
        };

        modelBuilders.ToList().ForEach(x => x.BuildModel());
    }
}
</code>```

Create ModelBuilder2 and DbContext2 for the second DB/Table.

Body:
I have two databases that so happen to have the same table name. Entity is giving me an InvalidOperationException stating "The entity types 'PmsUser' and 'AcctUser' cannot share table 'NGUSERS'...

I created these using a code first approach.

My models for both look something like

[Table("NGUSERS")]
public partial class AcctUser
{
    ...

and

[Table("NGUSERS")]
public partial class PmsUser
{
    ...

They each have their own respective connection string to differing databases. What do I need to do to get it to allow the same table name (modifying the Database isn't an option)?

Body:
Use two ModelBuilder instead of attributes. Then pass the created DbModel to the DbConnection. Or set the database name in the DbContext. See Entity Framework Connections and Models.

This base class helps to register the model builders with the DbContext:

public abstract class ModelBuilderBase {

    protected readonly DbModelBuilder ModelBuilder;

    protected ModelBuilderBase(DbModelBuilder modelBuilder) {
        ModelBuilder = modelBuilder;
    }

    public abstract void BuildModel();
}

ModelBuilder implementation:

public class ModelBuilder1 : ModelBuilderBase {

    public ModelBuilder1 (DbModelBuilder modelBuilder) : base(modelBuilder)
    { }

    public override void BuildModel() {

        ModelBuilder.Entity<AcctUser>().ToTable("NGUSERS");
    }
}

DbContext:

public class DbContext1 : DbContext {
    public DbContext1() : base("Database1") /* set DB name */ {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        var modelBuilders = new List<ModelBuilderBase> {
            new ModelBuilder1(modelBuilder)
        };

        modelBuilders.ToList().ForEach(x => x.BuildModel());
    }
}

Create ModelBuilder2 and DbContext2 for the second DB/Table.


问:
How to change height of default wordpress embed link "windows"
could anyone tell me if it's possible to make all these(in picture) wp-default links with class .wp-embed .post      same height so that it won't look horrible like in picture.enter image description here I know that it is programmed so that the height addapts to text size inside it.

How do i do that, i can't find they way how to overwrite that with CSS. Is it only achievable by PHP / if so how - i can barely read PHP for now...

答:
There are two separate questions here:

How do I change the css on a wordpress site?

The answer is that it will depend on the setup of your site.

-- You may have access to edit the css for the theme by going to Dashboard -> Appearance -> Editor and then finding the style.css

-- You may also have access to edit the css file through manually editting the file on the server.

-- if those first two options don't work, and you are able to add plugins, you can add a plugin to let you add css to the page.  Simple Custom Css is one such plugin.

How do I fix this particular css problem?

To answer this question I would need to see more of the css and html for this page


问:
Auto scroll on drag - Vaadin DragDrop add-on
I have a fixed position CssLayout with a DDVerticalLayout child component.  I'm populating this vertical layout dynamically based on user interaction to create a list view.  I run into a problem when the list becomes larger than the displayed area.  It scrolls correctly but the drag doesn't auto scroll.  This forces users to drag, scroll, drag, scroll, drag...

For example, if I selected an item at the bottom of the list and the view only displays 6 items at a time, I can't drag it more than 5 spaces up at a single time.  The view doesn't auto scroll based on the mouse hover.

Parent CssLayout with child DDVerticalLayout CSS:

```<code>.list {
  z-index: 9999;
  position: fixed;
  right: 1%;
  top: 20%;
  max-width: 25%;
  max-height: 70%;
  min-height: 150px;

  .v-verticallayout {
    background-color: #EEEEEE;
    overflow-y: scroll;
    overflow-x: hidden;
    display: block;
    margin-left: 6px;
    margin-right: 6px;
    max-height: 350px;
    min-height: 100px;
    border-radius: 4px;
    border: 1px solid #d5d5d5;
  }
}
</code>```

DDVerticalLayout setup within CssLayout class:

```<code>private final DDVerticalLayout layout = new DDVerticalLayout();
//...
layout.setDragMode(LayoutDragMode.CLONE);
layout.setSizeUndefined();
layout.setDropHandler(new DefaultVerticalLayoutDropHandler()
       @Override
        protected void handleComponentReordering(DragAndDropEvent event) {
            super.handleComponentReordering(event);
            //custom code omitted
        }
    });
</code>```

I'm using the drag and drop add-on v1.3.2 for Vaadin v7.7.6.

答:
Its an old post but may be useful for someone else come across this issue.
You need to wrap your VerticalLayout in a Panel in order to use the DNDScroll add-on. Something like this -</p>

```<code>Panel panel = new Panel();
panel.setContent(content);
panel.setHeight(200, Unit.PIXELS); //optional - could be setSizeFull();
PanelAutoScrollExtension extension = new PanelAutoScrollExtension();
extension.extend(panel);
</code>```

Body:
I have a fixed position CssLayout with a DDVerticalLayout child component.  I'm populating this vertical layout dynamically based on user interaction to create a list view.  I run into a problem when the list becomes larger than the displayed area.  It scrolls correctly but the drag doesn't auto scroll.  This forces users to drag, scroll, drag, scroll, drag...

For example, if I selected an item at the bottom of the list and the view only displays 6 items at a time, I can't drag it more than 5 spaces up at a single time.  The view doesn't auto scroll based on the mouse hover.

Parent CssLayout with child DDVerticalLayout CSS:

.list {
  z-index: 9999;
  position: fixed;
  right: 1%;
  top: 20%;
  max-width: 25%;
  max-height: 70%;
  min-height: 150px;

  .v-verticallayout {
    background-color: #EEEEEE;
    overflow-y: scroll;
    overflow-x: hidden;
    display: block;
    margin-left: 6px;
    margin-right: 6px;
    max-height: 350px;
    min-height: 100px;
    border-radius: 4px;
    border: 1px solid #d5d5d5;
  }
}

DDVerticalLayout setup within CssLayout class:

private final DDVerticalLayout layout = new DDVerticalLayout();
//...
layout.setDragMode(LayoutDragMode.CLONE);
layout.setSizeUndefined();
layout.setDropHandler(new DefaultVerticalLayoutDropHandler()
       @Override
        protected void handleComponentReordering(DragAndDropEvent event) {
            super.handleComponentReordering(event);
            //custom code omitted
        }
    });

I'm using the drag and drop add-on v1.3.2 for Vaadin v7.7.6.

Body:
Its an old post but may be useful for someone else come across this issue.
You need to wrap your VerticalLayout in a Panel in order to use the DNDScroll add-on. Something like this -

Panel panel = new Panel();
panel.setContent(content);
panel.setHeight(200, Unit.PIXELS); //optional - could be setSizeFull();
PanelAutoScrollExtension extension = new PanelAutoScrollExtension();
extension.extend(panel);


问:
webkit mask in javascript function on scroll
I'm trying to do this inside loadingisCompleted

```<code> $(window).scroll(function(){
    if ($('body').hasClass('home')) {
        if ($(window).scrollTop() > 0) {
        $('#tol-header').css('-webkit-mask-image','-webkit-gradient(linear, center top, center bottom, color-stop(1.00, rgba(0, 0, 0, 0)), color-stop(0.00, rgba(19, 40, 39, 1)))');

        } else {
            $('#tol-header').css('background','transparent');
        };
    };
});
</code>```

Purpose:

Default background: transparent

On scroll to be executed: -webkit-mask-image .....

No influence on the elements which are situated in the header.

My less file contains

```<code>#tol-header { background: transparent; }
</code>```

The final result is that I have permanent "transparent" opacity on/over all elements (menus, logo, etc) in the header, no matter if I scroll or not, nothing in common with what I would like to get.

If I change the places of scrollTop - background: transparent; else - -webkit-mask .... It works perfect, as I background (without any influences on other elements; as I want), but ... it works even when I'm not scrolling and I'm at the top of the page.

Would be thankful if somebody can help.

答:
I'm taking a stab at what you're wanting to do here as your question lacks a few key details.

I believe you want $('#tol-header').css('-webkit-mask-image', 'none') in the else as well so the webkit mask is removed again.

Body:
I'm trying to do this inside loadingisCompleted

 $(window).scroll(function(){
    if ($('body').hasClass('home')) {
        if ($(window).scrollTop() > 0) {
        $('#tol-header').css('-webkit-mask-image','-webkit-gradient(linear, center top, center bottom, color-stop(1.00, rgba(0, 0, 0, 0)), color-stop(0.00, rgba(19, 40, 39, 1)))');

        } else {
            $('#tol-header').css('background','transparent');
        };
    };
});

Purpose:

Default background: transparent

On scroll to be executed: -webkit-mask-image .....

No influence on the elements which are situated in the header.

My less file contains

#tol-header { background: transparent; }

The final result is that I have permanent "transparent" opacity on/over all elements (menus, logo, etc) in the header, no matter if I scroll or not, nothing in common with what I would like to get.

If I change the places of scrollTop - background: transparent; else - -webkit-mask .... It works perfect, as I background (without any influences on other elements; as I want), but ... it works even when I'm not scrolling and I'm at the top of the page.

Would be thankful if somebody can help.


问:
Vue.js/Weex: Fontawesome not working on dynamic text
```<code><template>
  <div>
    <text class="fontawesome"></text>
    <text class="fontawesome">{{testfontawesome}}</text>
  </div>
</template>
<style scoped>
  .fontawesome {
    font-family:FontAwesome;
  }
</style>
<script>
    export default {
        data: () => ({
            testfontawesome: ""
        }),
    }
</script>
</code>```

How can I display fontawesome icon in dynamic value?
In the code sample above, only the first line shows the icon correctly, secondly shows the raw value instead of the icon.
Why?

答:
You need to bind the value as raw html.

https://v2.vuejs.org/v2/guide/syntax.html#Raw-HTML

```<code><text class="fontawesome" v-html="testfontawesome"></text>
</code>```

Vue is protecting you from cross-site scripting (XSS) attacks by automatically html encoding values.

As the warnings in the docs point out, avoid using v-html to display user-generated text, as it could be malicious.

Body:
<template>

    <text class="fontawesome"></text>
    <text class="fontawesome">{{testfontawesome}}</text>

</template>

How can I display fontawesome icon in dynamic value?
In the code sample above, only the first line shows the icon correctly, secondly shows the raw value instead of the icon.
Why?

Body:
You need to bind the value as raw html.

https://v2.vuejs.org/v2/guide/syntax.html#Raw-HTML

<text class="fontawesome" v-html="testfontawesome"></text>

Vue is protecting you from cross-site scripting (XSS) attacks by automatically html encoding values.

As the warnings in the docs point out, avoid using v-html to display user-generated text, as it could be malicious.

ContentLicense: CC BY-SA 4.0


问:
Sensitive Dependency property values are exposed by snoop tool in WPF application, How to prevent that?
I am using one user control which has it's password property. To set that password property i am using DependencyProperty created in viewmodel. When I am running application and trying to debug using Snoop tool(SnoopWpf), and when i look into user control properties it shows the password set for that control. I want to prevent snoop tool to show password property value.
Is there any way we can add security to perticular dependency property?

XAML Code:

```<code><class:MyControl x:Name="myControl" IsReadOnly="True"
CtlPassword="{Binding myPassword, Mode=OneWay}"
</class:MyControl>

private static DependencyProperty PasswordProperty = DependencyProperty.Register("myPassword", typeof(String), typeof(myControl), new PropertyMetadata(null));

public String myPassword
{
     get { return (String)GetValue(PasswordProperty); }
     set { SetValue(PasswordProperty, value); }
}
</code>```

I looked into this link for one of the solution - Snoop proof solution
Can we add any security to this myPassword property? Which will hide this property from any debugging tool

答:
Don't store passwords in string properties. This is a big no-no if you care about security. At least use a SecureString - or don't store them at all.

There is an example of how to use a behaviour to bind the to a SecurePassword property available here:

Bind SecurePassword to ViewModel

Body:
I am using one user control which has it's password property. To set that password property i am using DependencyProperty created in viewmodel. When I am running application and trying to debug using Snoop tool(SnoopWpf), and when i look into user control properties it shows the password set for that control. I want to prevent snoop tool to show password property value.
Is there any way we can add security to perticular dependency property?

XAML Code:

<class:MyControl x:Name="myControl" IsReadOnly="True"
CtlPassword="{Binding myPassword, Mode=OneWay}"
</class:MyControl>

private static DependencyProperty PasswordProperty = DependencyProperty.Register("myPassword", typeof(String), typeof(myControl), new PropertyMetadata(null));

public String myPassword
{
     get { return (String)GetValue(PasswordProperty); }
     set { SetValue(PasswordProperty, value); }
}

I looked into this link for one of the solution - Snoop proof solution
Can we add any security to this myPassword property? Which will hide this property from any debugging tool


问:
Why can't my cypher query use multiple variable-length paths?
In the following graph, how can I match both Rule 1 and Rule 2, using the green nodes "Qualification" and "New York" as conditions?

Help me understand why the following Cypher query does not work:

```<code>MATCH
(r:Rule),
(r)-[w1:When*]->(c:State{instanceName:"New York"}),
(r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50
</code>```

This query returns only Rule 2, not Rule 1.

Each of these queries works individually and returns the expected results:

```<code>MATCH
(r:Rule),
(r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50

MATCH
(r:Rule),
(r)-[w1:When*]->(c:State{instanceName:"New York"})
RETURN * LIMIT 50
</code>```

答:
The query does not return rule 1 due to the uniqueness of relationships in a single MATCH clause. In your example, the When relationship between Rule 1 and Instance is the same for both paths, and only one of them is returned.

To work around this, use two separate MATCH clauses.

```<code>MATCH
  (r:Rule),
  (r)-[w1:When*]->(c:State {instanceName: "New York"}),
MATCH
  (r)-[w2:When*]->(c2:Service {instanceName: "Qualification"})
RETURN *
LIMIT 50
</code>```

Body:
In the following graph, how can I match both Rule 1 and Rule 2, using the green nodes "Qualification" and "New York" as conditions?

Help me understand why the following Cypher query does not work:

MATCH
(r:Rule),
(r)-[w1:When*]->(c:State{instanceName:"New York"}),
(r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50

This query returns only Rule 2, not Rule 1.

Each of these queries works individually and returns the expected results:

MATCH
(r:Rule),
(r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50

MATCH
(r:Rule),
(r)-[w1:When*]->(c:State{instanceName:"New York"})
RETURN * LIMIT 50

Body:
The query does not return rule 1 due to the uniqueness of relationships in a single MATCH clause. In your example, the When relationship between Rule 1 and Instance is the same for both paths, and only one of them is returned.

To work around this, use two separate MATCH clauses.

MATCH
  (r:Rule),
  (r)-[w1:When*]->(c:State {instanceName: "New York"}),
MATCH
  (r)-[w2:When*]->(c2:Service {instanceName: "Qualification"})
RETURN *
LIMIT 50