问:
Drag and Drop Javascript Puzzle
I'm trying to revive some old code I have which is a jigsaw puzzle. It loads images (puzzle pieces) from a folder, randomly places them around the page, and then you drag and drop onto the board. This used to work, but when I tried to use it today, it just throws errors (see below).

HTML:

```<code><body onload="init();" onmousemove="initDrag();" onmouseup="mousePress=false;">
  <div id="main">
    <div id="inside">
      <img src="holder.gif" style="position:absolute; left:500; top:500;" />
    </div>
  </div>
  <div style="position:absolute;top:10px;left:600px;display:none;">
  </div>
  <p id="pText" class="congrats" style="position:absolute; top:410px; left:475px;"></p>
  <p style="position:absolute; top:20px; left:750px;" class="links"><a href="hard.html">hard puzzle</a> | <a href="main.html">home</a></p>
</body>
</code>```

Javascript:

```<code>// ARRAY FOR PLACEMENT OF IMAGES: [down, over]
var place = new Array([51,300],[51,432],[51,569],[51,707],[112,300],[112,432],[112,569],[112,707],[199,300],[199,432],[199,569],[199,707],[286,300],[286,432],[286,569],[286,707]);

var displayed = new Array();
var mousePress = false;
var pieces = place.length;
var placed = new Array();

var moveObject;

function init() {
    var append = "";
    for ( i=0; i<pieces; i++ )
    {
        append+= '<div onDrag="return false;" unselectable=on id="puzzle" name="puzzle" class="puzzleMain"><img src="img/us/img' + i + '.gif" onmousedown="mousePress=true;moveObject=' + i + ';if(document.all) {offsetX=window.event.offsetX;offsetY=window.event.offsetY;}" onmouseup="mousePress=false;doplace(' + i + ');"></div>';
        displayed[i] = 0;
        placed[i]=0;
    }
    document.getElementById("main").innerHTML += append;
    document.images[i].onload = rndmImg;
}

function rndmImg() {
    x=855;y=50;
    do {
        do {
            displayNext = Math.floor( Math.random()* pieces );
        } while( displayed[displayNext] );
        document.getElementsByName("puzzle")[displayNext].style.top = y;
        document.getElementsByName("puzzle")[displayNext].style.left = x;
        document.getElementsByName("puzzle")[displayNext].style.visibility="visible";
        displayed[displayNext]=1;
        x += document.images[displayNext].width;
        if( x >= 900 ) {
            y += document.images[displayNext].height;
            if ( y>=300 ) { x=0 } else { x=851 }
        }
    } while(!allDisplayed());
}

function allDisplayed() {
    for( z=0; z<displayed.length; z++ ) if( !displayed[z] ) return false;
    return true;
}

function lower() {
    for( p=0;p<document.getElementsByName("puzzle").length;p++ )
    document.getElementsByName("puzzle")[p].style.zIndex = 1;
    document.getElementsByName("puzzle")[moveObject].style.zIndex=5;
}

function initDrag(e) {
    if(!mousePress)return;
    if( document.getElementById("inside").innerHTML != "" ) document.getElementById("inside").innerHTML = "";
    lower();
    if(document.all) {
        mouseX = window.event.clientX - (offsetX);
        mouseY = window.event.clientY - (offsetY);
    } else {
        mouseX = e.clientX - 50;
        mouseY = e.clientY - 50;
    }
    document.getElementsByName("puzzle")[moveObject].style.top=mouseY;
    document.getElementsByName("puzzle")[moveObject].style.left=mouseX;
    return false;
}

function doplace(index) {
    w = document.images[index].width;
    h = document.images[index].height;
    t = parseInt(document.getElementsByName("puzzle")[index].style.top);
    l = parseInt(document.getElementsByName("puzzle")[index].style.left);

    if ( ( l >= place[index][1]-(w/2) && l <= place[index][1]+(w/2) ) && ( t >= place[index][0]-(h/2) && t <= place[index][0] + (h/2) ) )
    {
        document.getElementsByName("puzzle")[index].style.top = place[index][0];
        document.getElementsByName("puzzle")[index].style.left = place[index][1];
        placed[index] = 1;
        if(isComplete())
            pText.innerHTML = "Puzzle is complete!";
    }

}

function generateArray()
{
    append="var place = new Array(";
    for( i=0; i<document.getElementsByName("puzzle").length; i++ )
    {
        t = document.getElementsByName("puzzle")[i].style.pixelTop;
        l = document.getElementsByName("puzzle")[i].style.pixelLeft;
        append+="[" + t + "," + l + "],";
    }
    document.forms[0].mArray.value = append;
}

function isComplete()
{
    for( q=0;q<placed.length;q++ ) if( !placed[q] )return false;
    return true;
}
</code>```

The error I mostly get is: Uncaught TypeError: Cannot read property 'clientX' of undefined
    at initDrag (easy.html:70)
    at HTMLBodyElement.onmousemove (easy.html:116)

I have a JSFiddle here. Can anyone shed some light on what the issue might be?

答:
In your code you have onmousemove="initDrag();" so if document.all is falsy then mouseX = e.clientX - 50 would throw a Cannot read property 'clientX' of undefined because you call initDrag() without any argument on mouse move.

Now adays you neither should use document.all nor window.event, both are relicts.

Title: Drag and Drop Javascript Puzzle

Body:
I'm trying to revive some old code I have which is a jigsaw puzzle. It loads images (puzzle pieces) from a folder, randomly places them around the page, and then you drag and drop onto the board. This used to work, but when I tried to use it today, it just throws errors (see below).

HTML:

hard puzzle | home

Javascript:

// ARRAY FOR PLACEMENT OF IMAGES: [down, over]
var place = new Array([51,300],[51,432],[51,569],[51,707],[112,300],[112,432],[112,569],[112,707],[199,300],[199,432],[199,569],[199,707],[286,300],[286,432],[286,569],[286,707]);

var displayed = new Array();
var mousePress = false;
var pieces = place.length;
var placed = new Array();

var moveObject;

function init() {
    var append = "";
    for ( i=0; i<pieces; i++ )
    {
        append+= '

';
        displayed[i] = 0;
        placed[i]=0;
    }
    document.getElementById("main").innerHTML += append;
    document.images[i].onload = rndmImg;
}

function rndmImg() {
    x=855;y=50;
    do {
        do {
            displayNext = Math.floor( Math.random()* pieces );
        } while( displayed[displayNext] );
        document.getElementsByName("puzzle")[displayNext].style.top = y;
        document.getElementsByName("puzzle")[displayNext].style.left = x;
        document.getElementsByName("puzzle")[displayNext].style.visibility="visible";
        displayed[displayNext]=1;
        x += document.images[displayNext].width;
        if( x >= 900 ) {
            y += document.images[displayNext].height;
            if ( y>=300 ) { x=0 } else { x=851 }
        }
    } while(!allDisplayed());
}

function allDisplayed() {
    for( z=0; z<displayed.length; z++ ) if( !displayed[z] ) return false;
    return true;
}

function lower() {
    for( p=0;p<document.getElementsByName("puzzle").length;p++ )
    document.getElementsByName("puzzle")[p].style.zIndex = 1;
    document.getElementsByName("puzzle")[moveObject].style.zIndex=5;
}

function initDrag(e) {
    if(!mousePress)return;
    if( document.getElementById("inside").innerHTML != "" ) document.getElementById("inside").innerHTML = "";
    lower();
    if(document.all) {
        mouseX = window.event.clientX - (offsetX);
        mouseY = window.event.clientY - (offsetY);
    } else {
        mouseX = e.clientX - 50;
        mouseY = e.clientY - 50;
    }
    document.getElementsByName("puzzle")[moveObject].style.top=mouseY;
    document.getElementsByName("puzzle")[moveObject].style.left=mouseX;
    return false;
}

function doplace(index) {
    w = document.images[index].width;
    h = document.images[index].height;
    t = parseInt(document.getElementsByName("puzzle")[index].style.top);
    l = parseInt(document.getElementsByName("puzzle")[index].style.left);

    if ( ( l >= place[index][1]-(w/2) && l <= place[index][1]+(w/2) ) && ( t >= place[index][0]-(h/2) && t <= place[index][0] + (h/2) ) )
    {
        document.getElementsByName("puzzle")[index].style.top = place[index][0];
        document.getElementsByName("puzzle")[index].style.left = place[index][1];
        placed[index] = 1;
        if(isComplete())
            pText.innerHTML = "Puzzle is complete!";
    }

}

function generateArray()
{
    append="var place = new Array(";
    for( i=0; i<document.getElementsByName("puzzle").length; i++ )
    {
        t = document.getElementsByName("puzzle")[i].style.pixelTop;
        l = document.getElementsByName("puzzle")[i].style.pixelLeft;
        append+="[" + t + "," + l + "],";
    }
    document.forms[0].mArray.value = append;
}

function isComplete()
{
    for( q=0;q<placed.length;q++ ) if( !placed[q] )return false;
    return true;
}

The error I mostly get is: Uncaught TypeError: Cannot read property 'clientX' of undefined
    at initDrag (easy.html:70)
    at HTMLBodyElement.onmousemove (easy.html:116)

I have a JSFiddle here. Can anyone shed some light on what the issue might be?


来源: stackexchange

问:
Push elements dynamically using javascript
I am getting the points from the multidimensional array using map, but I am getting array of array values.

I need the below format:

```<code>[36, 122, 25]
</code>```

But I'm getting the multi array of points.

Below is my code and output

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]

var result = data.map(function(arr, count) {
  return [arr.points];
});

console.log(result);```
</div>
</div>
</p>

<p>output is:</p>

```[[36], [122], [25]]
```

答:
In your code you are using [] that creates a new array using arr.points values. Remove the [] from return statement.

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]
var result = data.map(function(arr, count) {
  return arr.points;
});
console.log(result);```

ContentLicense: CC BY-SA 3.0

Body:
I am getting the points from the multidimensional array using map, but I am getting array of array values.

I need the below format:

[36, 122, 25]

But I'm getting the multi array of points.

Below is my code and output

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]

var result = data.map(function(arr, count) {
  return [arr.points];
});

console.log(result);

output is:

[[36], [122], [25]]


问:
How do I find the number of common numbers occurring in 2nd array?
commonCount(ar1, ar2)

if arr1 = [1,1,2,3,3] and arr2 = [1,4,3,1,1], the answer is 3

My thought process:

initialize accumulator

iterate through arr1

if arr1[i] is in the arr2, add 1 to the accumulator

remove the arr1[i] from arr2 (because don't want to have duplicate if the number already exist)

return accumulator

1) How do I check if arr1[i] is in the arr2?

2) How do I remove arr1[i] from arr2?

答:
try with arr2 .filter(val => !arr1.includes(val)); to remove duplicate value from second array

var arr1 = [1, 1, 2, 3, 3];
var arr2 = [1, 4, 3, 1, 1];
arr2 = arr2 .filter(val => !arr1.includes(val));

console.log(arr1);
console.log(arr2);```


问:
MongoDB - Collection-level roles
I have a trouble.
I'm trying to apply a role to user.
I want the user only find, insert, remove and update specific collection

I'm doing this.

Create role:

db.createRole({role:'user_role_col',privileges:[{resource:{db:'something_else', collection: 'col_something_else'}, actions: ['find','remove','insert','update']}], roles: []});
.

Create user with that role:

db.createUser({user: 'user_col',pwd: '1234',roles: [{role: "user_role_col", db: "something_else"}]})
.

When I created role and user, I stay on something_else database (use something_else)

0 errors got, but I can only read col_something_else, I cannot remove, update, or insert :(

What am I doing wrong?

答:
I believe the following commands replicates what you did. Here I'm creating the role and user in the test database:

```<code>> use test

> db.createRole({role: 'testRole', privileges: [{resource: {db:'test', collection:'test'}, actions:['find','update','insert','remove']}], roles: []})

> db.createUser({user:'testUser',pwd:'password',roles:[{role:'testRole', db:'test'}]})
</code>```

I would then have to quit the mongo shell and re-authenticate using the new credentials. However, the authenticationDatabase parameter must point to the test database, since that's where I created the role and the user:

```<code>$ mongo -u testUser -p password --authenticationDatabase test

> db.test2.insert({a:1})  //try inserting to a non-"test" collection
unauthorized

> db.test2.find()  //try find on a non-"test" collection
unauthorized

> db.test.insert({a:1})  //insert into "test" collection
Inserted 1 record(s)

> db.test.updateMany({},{$set:{a:2}})  //update "test" collection
{
  "acknowledged": true,
  "matchedCount": 1,
  "modifiedCount": 1
}

> db.test.find()  //find on "test" collection
{
  "_id": ObjectId("5a0bcfa4322032cfcc3a69c6"),
  "a": 2
}

> db.test.deleteOne({a:2})  //delete from "test" collection
{
  "acknowledged": true,
  "deletedCount": 1
}

> db.test.drop()  //try to drop "test" collection
2017-11-15T16:32:07.715+1100 E QUERY    [thread1] Error: drop failed: {
  "ok": 0,
  "errmsg": "not authorized on test to execute command { drop: \"test\" }",
  "code": 13,
  "codeName": "Unauthorized"
}
</code>```

I found that the new custom role (testRole) is authorized correctly. This is using MongoDB 3.4.10.

Title: MongoDB - Collection-level roles

Body:
I believe the following commands replicates what you did. Here I'm creating the role and user in the test database:

> use test

> db.createRole({role: 'testRole', privileges: [{resource: {db:'test', collection:'test'}, actions:['find','update','insert','remove']}], roles: []})

> db.createUser({user:'testUser',pwd:'password',roles:[{role:'testRole', db:'test'}]})

I would then have to quit the mongo shell and re-authenticate using the new credentials. However, the authenticationDatabase parameter must point to the test database, since that's where I created the role and the user:

$ mongo -u testUser -p password --authenticationDatabase test

> db.test2.insert({a:1})  //try inserting to a non-"test" collection
unauthorized

> db.test2.find()  //try find on a non-"test" collection
unauthorized

> db.test.insert({a:1})  //insert into "test" collection
Inserted 1 record(s)

> db.test.updateMany({},{$set:{a:2}})  //update "test" collection
{
  "acknowledged": true,
  "matchedCount": 1,
  "modifiedCount": 1
}

> db.test.find()  //find on "test" collection
{
  "_id": ObjectId("5a0bcfa4322032cfcc3a69c6"),
  "a": 2
}

> db.test.deleteOne({a:2})  //delete from "test" collection
{
  "acknowledged": true,
  "deletedCount": 1
}

> db.test.drop()  //try to drop "test" collection
2017-11-15T16:32:07.715+1100 E QUERY    [thread1] Error: drop failed: {
  "ok": 0,
  "errmsg": "not authorized on test to execute command { drop: \"test\" }",
  "code": 13,
  "codeName": "Unauthorized"
}

I found that the new custom role (testRole) is authorized correctly. This is using MongoDB 3.4.10.


问:
How to check for presence of a string in a property
If I have a property

```<code><PropertyGroup>
  <MyProp>abd;efg;hij;klm</MyProp>
</PropertyGroup>
</code>```

How do I parse $(MyProp) to check the presence of klm?

答:
You can use property functions to invoke the string Contains() method to check for string occurrences. While some other options using the Items (through an Include="$(MyProp)" and checking if an item with the expected identity exists) is also possible, conditions using property functions can be used on any msbuild element, both inside and outside of targets.

Example:

```<code><Project>
  <PropertyGroup>
    <MyProp>abd;efg;hij;klm</MyProp>
  </PropertyGroup>

  <Target Name="Build">
    <Message Importance="high" Text="klm is included!" Condition="$(MyProp.Contains('klm'))" />

    <PropertyGroup>
      <MyProp>;$(MyProp);</MyProp>
    </PropertyGroup>
    <Message Importance="high" Text="exactly klm is included!" Condition="$(MyProp.Contains(';klm;'))" />
  </Target>
</Project>
</code>```

The second approach - pre- and appending ; and checking for ;klm; - makes sure that the string is matched as a whole in the list can deal with ;aklm.

ContentLicense: CC BY-SA 4.0

Body:
If I have a property

<PropertyGroup>
  <MyProp>abd;efg;hij;klm</MyProp>
</PropertyGroup>

How do I parse $(MyProp) to check the presence of klm?

Body:
You can use property functions to invoke the string Contains() method to check for string occurrences. While some other options using the Items (through an Include="$(MyProp)" and checking if an item with the expected identity exists) is also possible, conditions using property functions can be used on any msbuild element, both inside and outside of targets.

Example:

<Project>
  <PropertyGroup>
    <MyProp>abd;efg;hij;klm</MyProp>
  </PropertyGroup>

  <Target Name="Build">
    <Message Importance="high" Text="klm is included!" Condition="$(MyProp.Contains('klm'))" />

    <PropertyGroup>
      <MyProp>;$(MyProp);</MyProp>
    </PropertyGroup>
    <Message Importance="high" Text="exactly klm is included!" Condition="$(MyProp.Contains(';klm;'))" />
  </Target>
</Project>

The second approach - pre- and appending ; and checking for ;klm; - makes sure that the string is matched as a whole in the list can deal with ;aklm.


问:
Detect non-null reference in an array
I just asked a similar question, but then I realized I actually need something else. Since that question already has two answers, I do not want to edit my question. So here is what I actually need:

I want to detect whether a subrange of an array contains null references only. Somehow like this:

```<code>public static <T> boolean nullReferencesOnly
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] != null) return false;
    }
    return true;
}
</code>```

Is there a method like this in the Java library so I don't have to manually loop over the array?

答:
You could use a functional programming library like Guava (http://code.google.com/p/guava-libraries/). You could do something like this:

```<code>
import com.google.common.base.Predicate;

public class NotNull implements Predicate
{

    @Override
    public boolean apply(String arg0)
    {
        return arg0 != null;
    }

}
</code>```

And a test driver to see how it's used:

```<code>
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

import com.google.common.collect.Iterables;

public class Driver
{
    @Test
    public void testNotNull()
    {
        List l = Arrays.asList(new String[] {null, null, null});

        String s = Iterables.find(l, new NotNull(), null);

        assertNull(s);
    }

    @Test
    public void testNotNull2()
    {
        List l = Arrays.asList(new String[] {null, "1", null});

        String s = Iterables.find(l, new NotNull(), null);

        assertNotNull(s);
    }
}
</code>```

With this, you just call Iterables.find() and see if it can find anything that isn't null. As long as it returns nothing (null), you know that there wasn't anything in the list that wasn't null.

ContentLicense: CC BY-SA 2.5

Title: Detect non-null reference in an array

Body:
I just asked a similar question, but then I realized I actually need something else. Since that question already has two answers, I do not want to edit my question. So here is what I actually need:

I want to detect whether a subrange of an array contains null references only. Somehow like this:

public static <T> boolean nullReferencesOnly
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] != null) return false;
    }
    return true;
}

Is there a method like this in the Java library so I don't have to manually loop over the array?

Body:
You could use a functional programming library like Guava (http://code.google.com/p/guava-libraries/). You could do something like this:

import com.google.common.base.Predicate;

public class NotNull implements Predicate
{

    @Override
    public boolean apply(String arg0)
    {
        return arg0 != null;
    }

}

And a test driver to see how it's used:

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

import com.google.common.collect.Iterables;

public class Driver
{
    @Test
    public void testNotNull()
    {
        List l = Arrays.asList(new String[] {null, null, null});

        String s = Iterables.find(l, new NotNull(), null);

        assertNull(s);
    }

    @Test
    public void testNotNull2()
    {
        List l = Arrays.asList(new String[] {null, "1", null});

        String s = Iterables.find(l, new NotNull(), null);

        assertNotNull(s);
    }
}

With this, you just call Iterables.find() and see if it can find anything that isn't null. As long as it returns nothing (null), you know that there wasn't anything in the list that wasn't null.


问:
Getting additional information during registration in MVC5 application
Putting together an MVC5 application and what I would like to do is have a user either register as a client or a tradesmen. There login details can go into the same default [AspNetUsers] table that is created but if they are a tradesman I want additional details to be collected. When I look at some of the code that comes with the application I'm building I'm somewhat confused as to what I should do next or even if the approach I'm using is correct. I'm aiming to collect either set of registration information depending on which is filled in.

My account/register controller is beginning to look like this:

```<code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        using (var context = new ApplicationDbContext())
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    UserName = model.Email,
                    Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                if (result.Succeeded)
                {
                    if (model.CompanyName.Trim().Length > 0)
                    {
                        var company = new CompanyModel
                        {
                            CompanyName = model.CompanyName,
                            AddressLine1 = model.AddressLine1,
                            AddressLine2 = model.AddressLine2,
                            Town = model.Town,
                            County = model.County,
                            Postcode = model.Postcode,
                            TelNo = model.TelNo,
                            MobNo = model.MobNo,
                            GoogleVerified = model.GoogleVerified,
                            FacebookProfileUrl = model.FacebookProfileUrl
                        };

                        //insert company details?
                    }

                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
    }
</code>```

So my question would be is what I'm doing correct/a good thing to do, can I collect details for two types of user through the same Controller.

Also with the Register.cshtml page I have a jquery accordion, the idea being a client can fill in one section and join or a tradesman can click the accordion and it reveals another section to fill in. The problem I then face is I'm using this line of code once:

```<code>@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
</code>```

{

Then sitting the accordion control inside this, which means I have these controls

```<code>@Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })
</code>```

Twice, once for a user and once for a tradesman, is this allowed?

答:
Adding a  twice is fine, but I assume you must then have the associated @Html.TextBoxFor(m => m.FirstName) duplicated as well, which is not fine because (1) it generates duplicate id attributes which is invalid html and (2) the DefaultModelBinder will only bind the value if the first input with name="FirstName".

There is no reason to repeat the controls. Instead decorate the view model properties associated with your CompanyModel with conditional validation attributes (for example a foolproof [RequiredIf]) so they are required if the user is also a tradesman. Since you have indicate the user can either be a tradesman or not, I suggest a bool property to generate a checkbox. Your view model would then look like

```<code>public class RegisterViewModel
{
    // Properties associated with ApplicationUser
    [Display(Name = "Company Name")]
    [Required(ErrorMessage = "Please enter your First Name")]
    public string FirstName { get; set; }
    ....
    public bool IsTradesPerson { get; set; }
    // Properties associated with CompanyModel
    [Display(Name = "Company Name")]
    [RequiredIfTrue("IsTradesPerson", ErrorMessage = "Please enter your Company Name")]
    public string CompanyName { get; set; }
    ....
}
</code>```

and in the view, place the controls associated with CompanyModel model in a hidden
 element so that its visibility can be toggled based on the IsTradesPerson property

```<code><div id="usercontrols">
    @Html.LabelFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.FirstName)
    @Html.ValidationMessageFor(m => m.FirstName)
    ....
    @Html.LabelFor(m => m.IsTradesperson)
    @Html.CheckBoxFor(m.IsTradesperson)
</div>
<div id="tradespersoncontrols" hidden>
    @Html.LabelFor(m => m.CompanyName)
    @Html.TextBoxFor(m => m.CompanyName)
    @Html.ValidationMessageFor(m => m.CompanyName)
    ....
<div>
</code>```

and the script to toggle the visibility

```<code>var controls = $('tradespersoncontrols');
$('#IsTradesperson').click(function) {
    if ($(this).is(':checked')) {
        controls.show();
    } else {
        controls.hide();
    }
});
</code>```

Then in the POST method you can check if(model.IsTradesperson) and if so, create your CompanyModel based on the view model properties and save it.

Body:
Putting together an MVC5 application and what I would like to do is have a user either register as a client or a tradesmen. There login details can go into the same default [AspNetUsers] table that is created but if they are a tradesman I want additional details to be collected. When I look at some of the code that comes with the application I'm building I'm somewhat confused as to what I should do next or even if the approach I'm using is correct. I'm aiming to collect either set of registration information depending on which is filled in.

My account/register controller is beginning to look like this:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        using (var context = new ApplicationDbContext())
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    UserName = model.Email,
                    Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                if (result.Succeeded)
                {
                    if (model.CompanyName.Trim().Length > 0)
                    {
                        var company = new CompanyModel
                        {
                            CompanyName = model.CompanyName,
                            AddressLine1 = model.AddressLine1,
                            AddressLine2 = model.AddressLine2,
                            Town = model.Town,
                            County = model.County,
                            Postcode = model.Postcode,
                            TelNo = model.TelNo,
                            MobNo = model.MobNo,
                            GoogleVerified = model.GoogleVerified,
                            FacebookProfileUrl = model.FacebookProfileUrl
                        };

                        //insert company details?
                    }

                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
    }

So my question would be is what I'm doing correct/a good thing to do, can I collect details for two types of user through the same Controller.

Also with the Register.cshtml page I have a jquery accordion, the idea being a client can fill in one section and join or a tradesman can click the accordion and it reveals another section to fill in. The problem I then face is I'm using this line of code once:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))

{

Then sitting the accordion control inside this, which means I have these controls

@Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })

Twice, once for a user and once for a tradesman, is this allowed?

Body:
Adding a <label> twice is fine, but I assume you must then have the associated @Html.TextBoxFor(m => m.FirstName) duplicated as well, which is not fine because (1) it generates duplicate id attributes which is invalid html and (2) the DefaultModelBinder will only bind the value if the first input with name="FirstName".

There is no reason to repeat the controls. Instead decorate the view model properties associated with your CompanyModel with conditional validation attributes (for example a foolproof [RequiredIf]) so they are required if the user is also a tradesman. Since you have indicate the user can either be a tradesman or not, I suggest a bool property to generate a checkbox. Your view model would then look like

public class RegisterViewModel
{
    // Properties associated with ApplicationUser
    [Display(Name = "Company Name")]
    [Required(ErrorMessage = "Please enter your First Name")]
    public string FirstName { get; set; }
    ....
    public bool IsTradesPerson { get; set; }
    // Properties associated with CompanyModel
    [Display(Name = "Company Name")]
    [RequiredIfTrue("IsTradesPerson", ErrorMessage = "Please enter your Company Name")]
    public string CompanyName { get; set; }
    ....
}

and in the view, place the controls associated with CompanyModel model in a hidden <div> element so that its visibility can be toggled based on the IsTradesPerson property

<div id="usercontrols">
    @Html.LabelFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.FirstName)
    @Html.ValidationMessageFor(m => m.FirstName)
    ....
    @Html.LabelFor(m => m.IsTradesperson)
    @Html.CheckBoxFor(m.IsTradesperson)
</div>
<div id="tradespersoncontrols" hidden>
    @Html.LabelFor(m => m.CompanyName)
    @Html.TextBoxFor(m => m.CompanyName)
    @Html.ValidationMessageFor(m => m.CompanyName)
    ....
<div>

and the script to toggle the visibility

var controls = $('tradespersoncontrols');
$('#IsTradesperson').click(function) {
    if ($(this).is(':checked')) {
        controls.show();
    } else {
        controls.hide();
    }
});

Then in the POST method you can check if(model.IsTradesperson) and if so, create your CompanyModel based on the view model properties and save it.


问:
How to prevent a UIViewController from being popped out?
I have a childViewController which is pushed from parentViewController. In childViewController I want to block pop action in a particular condition.

I wrote this code in viewWillDisappear: But I guess need to do this somewhere else.

```<code>override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if changesMade {
        let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

        let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
        let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
            self.saveSession()
        })

        alertController.addAction(saveOption)
        alertController.addAction(cancelOption)
        present(alertController, animated: true)
    }
}
</code>```

答:
There are two cases here:

User can pop using back button.

User can pop using interactive pop gesture of navigation controller.

I think you should use a custom back button and name it Done and write your logic of showing alert on press of this button.
Using the custom back button would disable the interactive pop gesture by default and you will be spared from playing the dance of enabling/disabling interactivePopGesture on navigation controller.

Body:
I have a childViewController which is pushed from parentViewController. In childViewController I want to block pop action in a particular condition.

I wrote this code in viewWillDisappear: But I guess need to do this somewhere else.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if changesMade {
        let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

        let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
        let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
            self.saveSession()
        })

        alertController.addAction(saveOption)
        alertController.addAction(cancelOption)
        present(alertController, animated: true)
    }
}


问:
Continuous tracking of users location
I have xamarin.forms application for ios,I need to implement a functionality of continuous tracking of users locations,for example consider two users "A" and "B"
now "A" can able to know the location of "B" and "B" Can be able to know the "A's" location at any time,Is there any way to achieve this functionality,please provide any sample or guidelines if it is possible.</p>

答:
If both devices have long distance than using following idea you can track device location remotely.

Using API implementation, device A and B send a current location to your server through didUpdateLocation method after that from device A get a device B current location and from device B get device A current location so, you can track each device location continuously.

As per your requirement, you have to call this API.

e.g   call API in some of the time interval is the best way to tacking device location continuously.

Below link help for background location update service,

Periodic iOS background location updates
How do I get a background location update every n minutes in my iOS application?

Title: Continuous tracking of users location


问:
How do I concatenate strings within an array of objects nested inside another array of objects?
Here's the JSON object I'm working with:

```<code>var object = {
    "units": [
        { "unitNum": "1", "fuels": [{ "fuelDesc": "Coal" }] },
        { "unitNum": "2", "fuels": [{ "fuelDesc": "Pipeline Natural Gas" }] }
    ]
}
</code>```

What's the most performative way of concatenating all of the fuelDesc strings into one string, separated by ,?

NOTE: I've simplified the object here. The actual objects is a lot larger so I'm concerned with performance. Also, the fuels array can have more than one item.

The result would be "Coal,Pipeline Natural Gas".

I did this:

```<code>var fuelsStr = "";
for (i = 0; i < units.length; i += 1) {
    var mergedFuels = [].concat.apply([], units[i].fuels)
    var unitFuelStr = mergedFuels.map(function (mergedFuels) {
        return mergedFuels["fuelDesc"];
    }).join(",");
    fuelsStr += unitFuelStr;
}
</code>```

答:
i would use a combination of javascript's reduce and map functions

var object = {
  "units": [{
    "unitNum": "1",
    "fuels": [{
      "fuelDesc": "Coal"
    }]
  }, {
    "unitNum": "2",
    "fuels": [{
      "fuelDesc": "Pipeline Natural Gas"
    }, {
      "fuelDesc": "some fuel"
    }]
  }]
};

var myStr = object.units.reduce(
  (first, second) =>
  first.fuels.map(item =>
    item.fuelDesc)
  .concat(second.fuels.map(item => item.fuelDesc))).join()

  console.log(myStr);```

I believe this is just about as efficient as you can get, but its been a while since ive done math involving big O so if someone can prove me wrong let me know!

Body:
Here's the JSON object I'm working with:

var object = {
    "units": [
        { "unitNum": "1", "fuels": [{ "fuelDesc": "Coal" }] },
        { "unitNum": "2", "fuels": [{ "fuelDesc": "Pipeline Natural Gas" }] }
    ]
}

What's the most performative way of concatenating all of the fuelDesc strings into one string, separated by ,?

NOTE: I've simplified the object here. The actual objects is a lot larger so I'm concerned with performance. Also, the fuels array can have more than one item.

The result would be "Coal,Pipeline Natural Gas".

I did this:

var fuelsStr = "";
for (i = 0; i < units.length; i += 1) {
    var mergedFuels = [].concat.apply([], units[i].fuels)
    var unitFuelStr = mergedFuels.map(function (mergedFuels) {
        return mergedFuels["fuelDesc"];
    }).join(",");
    fuelsStr += unitFuelStr;
}

Body:
i would use a combination of javascript's reduce and map functions

var object = {
  "units": [{
    "unitNum": "1",
    "fuels": [{
      "fuelDesc": "Coal"
    }]
  }, {
    "unitNum": "2",
    "fuels": [{
      "fuelDesc": "Pipeline Natural Gas"
    }, {
      "fuelDesc": "some fuel"
    }]
  }]
};

var myStr = object.units.reduce(
  (first, second) =>
  first.fuels.map(item =>
    item.fuelDesc)
  .concat(second.fuels.map(item => item.fuelDesc))).join()

  console.log(myStr);

I believe this is just about as efficient as you can get, but its been a while since ive done math involving big O so if someone can prove me wrong let me know!


问:
How to extract the two elements in Selenium(python)?
I need to extract all the "snail"s and "hello world"s under class 'm' and 'n'.
m and n are repeated, but they have different "snail"s and "hello world"s.</p>

<p>[![below][1]][1] . </p>

答:
Simply use xpath

```<code>driver.find_element_by_xpath("//a[contains(text(),'snail')]")
driver.find_element_by_xpath("//a[contains(text(),'Re: hello world')]")
</code>```

it may possible issue with quotes as i dont know python too much

Body:
I need to extract all the "snail"s and "hello world"s under class 'm' and 'n'.
m and n are repeated, but they have different "snail"s and "hello world"s.

[![below][1]][1] .

Body:
Simply use xpath

driver.find_element_by_xpath("//a[contains(text(),'snail')]")
driver.find_element_by_xpath("//a[contains(text(),'Re: hello world')]")

it may possible issue with quotes as i dont know python too much


问:
Qt - Block user interface while computer is making a move
To learn Qt I decided to build a TicTacToe program. The UI is simple enough but I've stumbled on a problem that I can't solve. I wanted the human user to be able to play against the computer, as such, I need the UI to be blocked while the cpu is making the calculations. I've tried working with setEnabled but it's not working the way I wanted and I went with just put a Qframe in the front and use the hide() and show() functions to block the interaction with the user. The problem is that it isn't working. When I click on the QPushButton the cell is updated and call the show function. Then I do whatever calculations I need and when it is finished I just call hide(). Below is an example code.

```<code>void TicTacToe_Gui::on_cell11_clicked(){

   ui->cell11->setText("wait...");
   ui->cell11->repaint();
   ui->frontPanel->show();

   for(int i=0; i<=1000000000; i++){
   }

   ui->cell11->setText("done");
   ui->frontPanel->hide();

}
</code>```

where the cell is a QPushButton.

Well, when the code in the for loop is running and I click on the other cells, the animations of the other buttons (I mean, the push animation) are not presented and it seems the UI is blocked but as soon as the code stops the other buttons are updated as if clicked. Check images below

I know similar questions have been asked many times and I've read most of them but I can't seem to make it to work. Can somebody help me?

答:
To not handle many signals and slot of several buttons it is advisable to use QButtonGroup and connect the buttonClicked signal to a single slot, this class can associate a button with an id, with that id we can obtain the row and column of the button:

```<code>group = new QButtonGroup(this);
for(int i=0; i < 3; i++){
    for(int j=0; j < 3; j++){
        board[i][j] = TicTacToe_State::N;
        QToolButton *btn = new QToolButton(this);
        btn->setFixedSize(100, 100);
        btn->setStyleSheet("QToolButton::disabled{color:black}");
        group->addButton(btn, /*id*/ 3*i+j);
        lay->addWidget(btn, i , j);
    }
}
connect(group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked), this, &TicTacToe_Gui::onClicked);
</code>```

The problem is caused because the heavy task you perform blocks the main-loop of the GUI, for heavy tasks it is advisable to use a secondary thread and when some result is obtained, send it to the main thread. In Qt there are several alternatives but the simplest for this case is to use QtConcurrent::run with QFutureWatcher and a QEventLoop, for this example I will create a structure that defines the result of the heavy algorithm:

```<code>struct TicTacToe_Result
{
    int row;
    int col;
};
enum TicTacToe_State{N, X, O};
TicTacToe_State board[3][3];
</code>```

The struct is the output of the algorithm, so if you want to add more fields to the result just add a new member. The enumeration describes the possible states of each button, and the array is the matrix that stores the information of the button board, this is a member of the class, so that the lambda function can access is passed &.

```<code>void TicTacToe_Gui::onClicked(int id)
{
    QAbstractButton *btnO = group->button(id);
    btnO->setText("O");
    int row = id/3;
    int col = id%3;
    board[row][col] = TicTacToe_State::O;
    QFutureWatcher<TicTacToe_Result> watcher;
    QFuture<TicTacToe_Result> future = QtConcurrent::run([&](){
        // here the heavy algorithm
        for(int i=0; i<=1000000000; i++){
        }
        return TicTacToe_Result{r, c};
    });

    watcher.setFuture(future);
    QEventLoop loop;
    connect(&watcher, &QFutureWatcherBase::finished, &loop, &QEventLoop::quit);
    loop.exec();
    TicTacToe_Result r = watcher.result();
    board[r.row][r.col] = TicTacToe_State::X;
    QAbstractButton *btnX = group->button(3*r.row+r.col);
    btnX->setText("X");
}
</code>```

QtConcurrent returns the result through QFuture, this class can wait synchronously and asynchronously, to do it asynchronously we use QFutureWatcher, to be able to execute it sequentially we will use QEventLoop.

I have implemented an example in the following link

Body:
To learn Qt I decided to build a TicTacToe program. The UI is simple enough but I've stumbled on a problem that I can't solve. I wanted the human user to be able to play against the computer, as such, I need the UI to be blocked while the cpu is making the calculations. I've tried working with setEnabled but it's not working the way I wanted and I went with just put a Qframe in the front and use the hide() and show() functions to block the interaction with the user. The problem is that it isn't working. When I click on the QPushButton the cell is updated and call the show function. Then I do whatever calculations I need and when it is finished I just call hide(). Below is an example code.

void TicTacToe_Gui::on_cell11_clicked(){

   ui->cell11->setText("wait...");
   ui->cell11->repaint();
   ui->frontPanel->show();

   for(int i=0; i<=1000000000; i++){
   }

   ui->cell11->setText("done");
   ui->frontPanel->hide();

}

where the cell is a QPushButton.

Well, when the code in the for loop is running and I click on the other cells, the animations of the other buttons (I mean, the push animation) are not presented and it seems the UI is blocked but as soon as the code stops the other buttons are updated as if clicked. Check images below

I know similar questions have been asked many times and I've read most of them but I can't seem to make it to work. Can somebody help me?

Body:
To not handle many signals and slot of several buttons it is advisable to use QButtonGroup and connect the buttonClicked signal to a single slot, this class can associate a button with an id, with that id we can obtain the row and column of the button:

group = new QButtonGroup(this);
for(int i=0; i < 3; i++){
    for(int j=0; j < 3; j++){
        board[i][j] = TicTacToe_State::N;
        QToolButton *btn = new QToolButton(this);
        btn->setFixedSize(100, 100);
        btn->setStyleSheet("QToolButton::disabled{color:black}");
        group->addButton(btn, /*id*/ 3*i+j);
        lay->addWidget(btn, i , j);
    }
}
connect(group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked), this, &TicTacToe_Gui::onClicked);

The problem is caused because the heavy task you perform blocks the main-loop of the GUI, for heavy tasks it is advisable to use a secondary thread and when some result is obtained, send it to the main thread. In Qt there are several alternatives but the simplest for this case is to use QtConcurrent::run with QFutureWatcher and a QEventLoop, for this example I will create a structure that defines the result of the heavy algorithm:

struct TicTacToe_Result
{
    int row;
    int col;
};
enum TicTacToe_State{N, X, O};
TicTacToe_State board[3][3];

The struct is the output of the algorithm, so if you want to add more fields to the result just add a new member. The enumeration describes the possible states of each button, and the array is the matrix that stores the information of the button board, this is a member of the class, so that the lambda function can access is passed &.

void TicTacToe_Gui::onClicked(int id)
{
    QAbstractButton *btnO = group->button(id);
    btnO->setText("O");
    int row = id/3;
    int col = id%3;
    board[row][col] = TicTacToe_State::O;
    QFutureWatcher<TicTacToe_Result> watcher;
    QFuture<TicTacToe_Result> future = QtConcurrent::run([&](){
        // here the heavy algorithm
        for(int i=0; i<=1000000000; i++){
        }
        return TicTacToe_Result{r, c};
    });

    watcher.setFuture(future);
    QEventLoop loop;
    connect(&watcher, &QFutureWatcherBase::finished, &loop, &QEventLoop::quit);
    loop.exec();
    TicTacToe_Result r = watcher.result();
    board[r.row][r.col] = TicTacToe_State::X;
    QAbstractButton *btnX = group->button(3*r.row+r.col);
    btnX->setText("X");
}

QtConcurrent returns the result through QFuture, this class can wait synchronously and asynchronously, to do it asynchronously we use QFutureWatcher, to be able to execute it sequentially we will use QEventLoop.

I have implemented an example in the following link


问:
How to add additional jar file to spring-boot application at runtime?
I built a spring-boot application and make the jar file exectuable. There is a compileOnly dependency on my project which need to be provided at runtime. When I run java -jar myApp.jar I will get ClassNotFound exeception which is expected. But I don't know how to add the additional jar file on java command. I have tried below command:

```<code>java -Dloader.path=/libs/third.jar -jar myApp.jar
</code>```

but it doesn't work. How can I add /libs/third.jar on my application?

答:
After some searching I figured out the problem with -Dloader.path. In order to make it works I need to change the project layout to be ZIP which will use PropertiesLauncher. Below is the configuration.

```<code>springBoot {
    executable = true
    layout = "ZIP"
}
</code>```

Body:
I built a spring-boot application and make the jar file exectuable. There is a compileOnly dependency on my project which need to be provided at runtime. When I run java -jar myApp.jar I will get ClassNotFound exeception which is expected. But I don't know how to add the additional jar file on java command. I have tried below command:

java -Dloader.path=/libs/third.jar -jar myApp.jar

but it doesn't work. How can I add /libs/third.jar on my application?

Body:
After some searching I figured out the problem with -Dloader.path. In order to make it works I need to change the project layout to be ZIP which will use PropertiesLauncher. Below is the configuration.

springBoot {
    executable = true
    layout = "ZIP"
}


问:
How to count words in a file using python >2.0
I want to write a program that can count keywords in a file.
Example: I created a list, with the following keywords. Then I open a file with bunch of words, and I want to count how many keywords are there in the file. But no matter what I do, the count will always give me 0. What did I do wrong?

Here is my code:

```<code>Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite',
         'excites', 'exciting', 'glad', 'greatest', 'happy', 'love',
         'loves', 'loved', 'loving', 'lovin', 'prettiest']

def CountFile():
  file = open("File.txt", "r")
  Count = 0
  for i in file:
    i = i.split()
    if i in Happy:
      count = count + 1
  print("there are" count "keywords")
  return

CountFile()
</code>```

答:
Try this code

Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite',
         'excites', 'exciting', 'glad', 'greatest', 'happy', 'love',
         'loves', 'loved', 'loving', 'lovin', 'prettiest']

```<code>def CountFile():
   file = open("File.txt", "r")
   count = 0
   for i in file:
      i = i.split()
      for so in i:
         if so in Happy:
            count = count + 1
   print("there are %s keywords" %count)

CountFile()
</code>```

Body:
I want to write a program that can count keywords in a file.
Example: I created a list, with the following keywords. Then I open a file with bunch of words, and I want to count how many keywords are there in the file. But no matter what I do, the count will always give me 0. What did I do wrong?

Here is my code:

Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite',
         'excites', 'exciting', 'glad', 'greatest', 'happy', 'love',
         'loves', 'loved', 'loving', 'lovin', 'prettiest']

def CountFile():
  file = open("File.txt", "r")
  Count = 0
  for i in file:
    i = i.split()
    if i in Happy:
      count = count + 1
  print("there are" count "keywords")
  return

CountFile()

Body:
Try this code

Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite',
         'excites', 'exciting', 'glad', 'greatest', 'happy', 'love',
         'loves', 'loved', 'loving', 'lovin', 'prettiest']

def CountFile():
   file = open("File.txt", "r")
   count = 0
   for i in file:
      i = i.split()
      for so in i:
         if so in Happy:
            count = count + 1
   print("there are %s keywords" %count)

CountFile()


问:
Authenticate without username and password
I have a database table with 4 columns (email, token, tokenDate (DateTime), isOnline (bool))

What I am trying to do in ASP.NET MVC is have an application where the user goes to a page like this Home/Index?email=xxxxx@xxxxxxx.com and when they goto the page, they are login, now what I could do it when they goto the page is this:

Find the user in the database table

Mark isOnline to true

Set the tokenDate to DateTime.Now

Create a random token and set that as token

Create a web cookie with the same value as token

And when someone else (or the same person) with the same email tries to goto the page

Find the user in the database table

If isOnline is marked as true and the cookie does not exist and if it does check against the one in the database, if fails boot them out, if success, they can enter.

My question is what token would I want to create so they original user is still authenticated so if they close their browser or goto another page they can still goto the main page where they authenticated?

答:
User goes to a page like this Home/Index?email=xxxxx@xxxxxxx.com or User Types email in a text box

STEP 1:

Find the user in the database table if doesn't exist take to access
denied page.

If exist Mark isOnline to true.

Set the tokenDate to.
DateTime.UtcNow so that you can display later into local time of
user.

Create a random token using
GUID
and set that as token in database.

Create a
cookie
to store
multiple
values one with the GUID value as token and another would be user
email  then set cookie expiry to years so doesn't expire even if user
closes the browser.

Step 2:

Now when user goes to Home/SomeOtherPage or the authentication page Home/Index?email=xxxxx@xxxxxxx.com

Check if cookie with the name exist , if exist get the email and token values from cookie and check against the value in database , if token matches for the email then user is authenticated.

Edit cookie and Set another value in cookie saying if user is authenticated, So next time when user visits check the value of authenticated as this would eliminate hitting database again if user visit pages again.

Note:

It would be better if you could encrypt the email while setting it in the cookie.


问:
How to read country_code from JSON data using jQuery or JavaScript?
```<code>{
  "status": "success",
  "description": "Data successfully received.",
  "data": {
    "geo": {
      "host": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "ip": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "rdns": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "asn": "AS55836",
      "isp": "Reliance Jio Infocomm Limited ",
      "country_name": "India",
      "country_code": "IN",
      "region": "",
      "city": "",
      "postal_code": "",
      "continent_code": "AS",
      "latitude": "20",
      "longitude": "77",
      "dma_code": "",
      "area_code": "",
      "timezone": "Asia/Kolkata",
      "datetime": "2017-11-15 10:12:15"
    }
  }
}
</code>```

How to read country_code using jQuery or JavaScript?

答:
Here you go

var a = {
  "status": "success",
  "description": "Data successfully received.",
  "data": {
    "geo": {
      "host": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "ip": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "rdns": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "asn": "AS55836",
      "isp": "Reliance Jio Infocomm Limited ",
      "country_name": "India",
      "country_code": "IN",
      "region": "",
      "city": "",
      "postal_code": "",
      "continent_code": "AS",
      "latitude": "20",
      "longitude": "77",
      "dma_code": "",
      "area_code": "",
      "timezone": "Asia/Kolkata",
      "datetime": "2017-11-15 10:12:15"
    }
  }
}

console.log("Country Code: "+ a.data.geo.country_code);```

Body:
{
  "status": "success",
  "description": "Data successfully received.",
  "data": {
    "geo": {
      "host": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "ip": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "rdns": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "asn": "AS55836",
      "isp": "Reliance Jio Infocomm Limited ",
      "country_name": "India",
      "country_code": "IN",
      "region": "",
      "city": "",
      "postal_code": "",
      "continent_code": "AS",
      "latitude": "20",
      "longitude": "77",
      "dma_code": "",
      "area_code": "",
      "timezone": "Asia/Kolkata",
      "datetime": "2017-11-15 10:12:15"
    }
  }
}

How to read country_code using jQuery or JavaScript?


问:
Error: The source control operation failed because the revisions
I've installed Xcode 7, and now always get this message when I select "commit" from xcode menu.

"The source control operation failed because the revisions... could not be found."

Any idea?  :)

答:
Same thing happend to me. Xcode claimed of failing to find a revision of a file while trying to commit - even though i was able to see its previous versions using the Comparison and Blame views.

The solution was restarting Xcode. Everything magically worked afterwards, and i was able to commit the project, including the problematic file.


问:
Sometimes scripts idle and require me to press RETURN in order to unlock them - Python
this has been happening quite a few times, and have not been able to explain this behaviour in any way.

Often I write quick Python scripts for some quick tasks, often these tasks are row iterations using Django's ORM.

example:

```<code>from core.models import MyModel

ITEM_IDS = [...]

for index, item_id in enumerate(ITEM_IDS):
    print index
    if MyModel.objects.filter(serial=item_id).count():
        do_something()
        print index, item_id
</code>```

at times the script stops on one of the iterations indefinitely,
pressing RETURN quickly resumes the interations!!!

Edit: this happens on Windows!

Any idea what is happening? :)

答:
Is there any chance it is the terminal window (or "dos box", or whatever) that is to blame?

For example, in many terminal windows, if there is a scroll bar, and you are scrolled anywhere but the bottom, it will stay there; thus, it will seem that nothing is happening.  But when you press a key, the terminal window scrolls immediately to the bottom, and you can see the output being printed?

Just a wild guess.

Body:
this has been happening quite a few times, and have not been able to explain this behaviour in any way.

Often I write quick Python scripts for some quick tasks, often these tasks are row iterations using Django's ORM.

example:

from core.models import MyModel

ITEM_IDS = [...]

for index, item_id in enumerate(ITEM_IDS):
    print index
    if MyModel.objects.filter(serial=item_id).count():
        do_something()
        print index, item_id

at times the script stops on one of the iterations indefinitely,
pressing RETURN quickly resumes the interations!!!

Edit: this happens on Windows!

Any idea what is happening? :)


问:
Are there any alternatives to Ionic View for iOS?
I continually have connection issues when attempting to preview iOS apps with Ionic 3.

No problems whatsoever with the Android side.

But iOS is just so temperamental and frustrating!

Connection errors, not Synching to latest etc?

答:
I have a lot of luck sharing my app with Hockey App. You do need an apple developer account to use it with IOS though. And there are a few more steps involved than simply using uploading to Ionic Dashboard.

https://www.hockeyapp.net/

And the instructions to do this process is
https://gist.github.com/SWTPAIN/a6f8bda444da4e3a5886

And if you are just testing on your own phone, it is much easier to just plug it in and run ionic cordova run --prod ios


问:
Perl: Need assistance converting if-elsif-else to something simpler
I've been reading up on dispatch tables and I get the general idea of how they work, but I'm having some trouble taking what I see online and applying the concept to some code I originally wrote as an ugly mess of if-elsif-else statements.

I have options parsing configured by using GetOpt::Long, and in turn, those options set a value in the %OPTIONS hash, depending on the option used.

Taking the below code as an example... (UPDATED WITH MORE DETAIL)

```<code>use     5.008008;
use     strict;
use     warnings;
use     File::Basename qw(basename);
use     Getopt::Long qw(HelpMessage VersionMessage :config posix_default require_order no_ignore_case auto_version auto_help);

my $EMPTY      => q{};

sub usage
{
    my $PROG = basename($0);
    print {*STDERR} $_ for @_;
    print {*STDERR} "Try $PROG --help for more information.\n";
    exit(1);
}

sub process_args
{
    my %OPTIONS;

    $OPTIONS{host}              = $EMPTY;
    $OPTIONS{bash}              = 0;
    $OPTIONS{nic}               = 0;
    $OPTIONS{nicName}           = $EMPTY;
    $OPTIONS{console}           = 0;
    $OPTIONS{virtual}           = 0;
    $OPTIONS{cmdb}              = 0;
    $OPTIONS{policyid}          = 0;
    $OPTIONS{showcompliant}     = 0;
    $OPTIONS{backup}            = 0;
    $OPTIONS{backuphistory}     = 0;
    $OPTIONS{page}              = $EMPTY;

    GetOptions
      (
        'host|h=s'              => \$OPTIONS{host}               ,
        'use-bash-script'       => \$OPTIONS{bash}               ,
        'remote-console|r!'     => \$OPTIONS{console}            ,
        'virtual-console|v!'    => \$OPTIONS{virtual}            ,
        'nic|n!'                => \$OPTIONS{nic}                ,
        'nic-name|m=s'          => \$OPTIONS{nicName}            ,
        'cmdb|d!'               => \$OPTIONS{cmdb}               ,
        'policy|p=i'            => \$OPTIONS{policyid}           ,
        'show-compliant|c!'     => \$OPTIONS{showcompliant}      ,
        'backup|b!'             => \$OPTIONS{backup}             ,
        'backup-history|s!'     => \$OPTIONS{backuphistory}      ,
        'page|g=s'              => \$OPTIONS{page}               ,
        'help'                  => sub      { HelpMessage(-exitval => 0, -verbose ->1)     },
        'version'               => sub      { VersionMessage()  },
      ) or usage;

    if ($OPTIONS{host} eq $EMPTY)
    {
        print {*STDERR} "ERROR: Must specify a host with -h flag\n";
        HelpMessage;
    }

    sanity_check_options(\%OPTIONS);

    # Parse anything else on the command line and throw usage
    for (@ARGV)
    {
        warn "Unknown argument: $_\n";
        HelpMessage;
    }

    return {%OPTIONS};
}

sub sanity_check_options
{
    my $OPTIONS     = shift;

    if (($OPTIONS->{console}) and ($OPTIONS->{virtual}))
    {
        print "ERROR: Cannot use flags -r and -v together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -r and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -r and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -r and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{virtual}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -v and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -v and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -v and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{backup}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -b and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{backup}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -b and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{nic}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -n and -d together\n";
        HelpMessage;
    }

    if (($OPTIONS->{policyid} != 0) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -p without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{showcompliant}) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -c without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{backuphistory}) and not ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flag -s without also specifying -b\n";
        HelpMessage;
    }

    if (($OPTIONS->{nicName}) and not ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flag -m without also specifying -n\n";
        HelpMessage;
    }

    return %{$OPTIONS};
}
</code>```

I'd like to turn the above code into a dispatch table, but can't figure out how to do it.

Any help is appreciated.

答:
I am not sure how a dispatch table would help since you need to go through pair-wise combinations of specific possibilities, and thus cannot trigger a suitable action by one lookup.

Here is another way to organize it

```<code>use List::MoreUtils 'firstval';

sub sanity_check_options
{
    my ($OPTIONS, $opt_excl) = @_;

    # Check each of 'opt_excl' against all other for ConFLict
    my @excl = sort keys %$opt_excl;
    while (my $eo = shift @excl)
    {
        if (my $cfl = firstval { $OPTIONS->{$eo} and $OPTIONS->{$_} } @excl)
        {
            say "Can't use -$opt_excl->{$eo} and -$opt_excl->{$cfl} together";
            HelpMessage();
            last;
        }
    }

    # Go through specific checks on
    # policyid, showcompliant, backuphistory, and nicName
    ...
    return 1;  # or some measure of whether there were errors
}

# Mutually exclusive options
my %opt_excl = (
    console => 'r', virtual => 'v', cmdb => 'c', backup => 'b', nic => 'n'
);

sanity_check_options(\%OPTIONS, \%opt_excl);
</code>```

This checks all options listed in %opt_excl against each other for conflict, removing the segments of elsif involving the (five) options that are mutually exclusive. It uses List::MoreUtils::firstval.
The few other specific invocations are best checked one by one.

There is no use of returning $OPTIONS since it is passed as reference so any changes apply to the original structure (while it's not meant to be changed either). Perhaps you can keep track of whether there were errors and return that if it can be used in the caller, or just return 1.

This addresses the long elsif chain as asked, and doesn't go into the rest of code. Here is one comment though: There is no need for {%OPTIONS}, which copies the hash in order to create an anonymous one; just use return \%OPTIONS;

Comment on possible multiple conflicting options

This answer as it stands does not print all conflicting options that have been used if there are more than two, as raised by ikegami in comments; it does catch any conflicts so that the run is aborted.

The code is readily adjusted for this. Instead of the code in the if block either

set a flag as a conflict is detected and break out of the loop, then print the list of those that must not be used with each other (values %opt_excl) or point at the following usage message

collect the conflicts as they are observed; print them after the loop

or, see a different approach in ikegami's answer

However, one is expected to know of allowed invocations of a program and any listing of conflicts is a courtesy to the forgetful user (or a debugging aid); a usage message is printed as well anyway.

Given the number of conflicting options the usage message should have a prominent note on this. Also consider that so many conflicting options may indicate a design flaw.

Finally, this code fully relies on the fact that this processing goes once per run and operates with a handful of options; thus it is not concerned with efficiency and freely uses ancillary data structures.

Body:
I've been reading up on dispatch tables and I get the general idea of how they work, but I'm having some trouble taking what I see online and applying the concept to some code I originally wrote as an ugly mess of if-elsif-else statements.

I have options parsing configured by using GetOpt::Long, and in turn, those options set a value in the %OPTIONS hash, depending on the option used.

Taking the below code as an example... (UPDATED WITH MORE DETAIL)

use     5.008008;
use     strict;
use     warnings;
use     File::Basename qw(basename);
use     Getopt::Long qw(HelpMessage VersionMessage :config posix_default require_order no_ignore_case auto_version auto_help);

my $EMPTY      => q{};

sub usage
{
    my $PROG = basename($0);
    print {*STDERR} $_ for @_;
    print {*STDERR} "Try $PROG --help for more information.\n";
    exit(1);
}

sub process_args
{
    my %OPTIONS;

    $OPTIONS{host}              = $EMPTY;
    $OPTIONS{bash}              = 0;
    $OPTIONS{nic}               = 0;
    $OPTIONS{nicName}           = $EMPTY;
    $OPTIONS{console}           = 0;
    $OPTIONS{virtual}           = 0;
    $OPTIONS{cmdb}              = 0;
    $OPTIONS{policyid}          = 0;
    $OPTIONS{showcompliant}     = 0;
    $OPTIONS{backup}            = 0;
    $OPTIONS{backuphistory}     = 0;
    $OPTIONS{page}              = $EMPTY;

    GetOptions
      (
        'host|h=s'              => \$OPTIONS{host}               ,
        'use-bash-script'       => \$OPTIONS{bash}               ,
        'remote-console|r!'     => \$OPTIONS{console}            ,
        'virtual-console|v!'    => \$OPTIONS{virtual}            ,
        'nic|n!'                => \$OPTIONS{nic}                ,
        'nic-name|m=s'          => \$OPTIONS{nicName}            ,
        'cmdb|d!'               => \$OPTIONS{cmdb}               ,
        'policy|p=i'            => \$OPTIONS{policyid}           ,
        'show-compliant|c!'     => \$OPTIONS{showcompliant}      ,
        'backup|b!'             => \$OPTIONS{backup}             ,
        'backup-history|s!'     => \$OPTIONS{backuphistory}      ,
        'page|g=s'              => \$OPTIONS{page}               ,
        'help'                  => sub      { HelpMessage(-exitval => 0, -verbose ->1)     },
        'version'               => sub      { VersionMessage()  },
      ) or usage;

    if ($OPTIONS{host} eq $EMPTY)
    {
        print {*STDERR} "ERROR: Must specify a host with -h flag\n";
        HelpMessage;
    }

    sanity_check_options(\%OPTIONS);

    # Parse anything else on the command line and throw usage
    for (@ARGV)
    {
        warn "Unknown argument: $_\n";
        HelpMessage;
    }

    return {%OPTIONS};
}

sub sanity_check_options
{
    my $OPTIONS     = shift;

    if (($OPTIONS->{console}) and ($OPTIONS->{virtual}))
    {
        print "ERROR: Cannot use flags -r and -v together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -r and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -r and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -r and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{virtual}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -v and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -v and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -v and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{backup}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -b and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{backup}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -b and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{nic}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -n and -d together\n";
        HelpMessage;
    }

    if (($OPTIONS->{policyid} != 0) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -p without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{showcompliant}) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -c without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{backuphistory}) and not ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flag -s without also specifying -b\n";
        HelpMessage;
    }

    if (($OPTIONS->{nicName}) and not ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flag -m without also specifying -n\n";
        HelpMessage;
    }

    return %{$OPTIONS};
}

I'd like to turn the above code into a dispatch table, but can't figure out how to do it.

Any help is appreciated.

Body:
I am not sure how a dispatch table would help since you need to go through pair-wise combinations of specific possibilities, and thus cannot trigger a suitable action by one lookup.

Here is another way to organize it

use List::MoreUtils 'firstval';

sub sanity_check_options
{
    my ($OPTIONS, $opt_excl) = @_;

    # Check each of 'opt_excl' against all other for ConFLict
    my @excl = sort keys %$opt_excl;
    while (my $eo = shift @excl)
    {
        if (my $cfl = firstval { $OPTIONS->{$eo} and $OPTIONS->{$_} } @excl)
        {
            say "Can't use -$opt_excl->{$eo} and -$opt_excl->{$cfl} together";
            HelpMessage();
            last;
        }
    }

    # Go through specific checks on
    # policyid, showcompliant, backuphistory, and nicName
    ...
    return 1;  # or some measure of whether there were errors
}

# Mutually exclusive options
my %opt_excl = (
    console => 'r', virtual => 'v', cmdb => 'c', backup => 'b', nic => 'n'
);

sanity_check_options(\%OPTIONS, \%opt_excl);

This checks all options listed in %opt_excl against each other for conflict, removing the segments of elsif involving the (five) options that are mutually exclusive. It uses List::MoreUtils::firstval.
The few other specific invocations are best checked one by one.

There is no use of returning $OPTIONS since it is passed as reference so any changes apply to the original structure (while it's not meant to be changed either). Perhaps you can keep track of whether there were errors and return that if it can be used in the caller, or just return 1.

This addresses the long elsif chain as asked, and doesn't go into the rest of code. Here is one comment though: There is no need for {%OPTIONS}, which copies the hash in order to create an anonymous one; just use return \%OPTIONS;

Comment on possible multiple conflicting options

This answer as it stands does not print all conflicting options that have been used if there are more than two, as raised by ikegami in comments; it does catch any conflicts so that the run is aborted.

The code is readily adjusted for this. Instead of the code in the if block either

set a flag as a conflict is detected and break out of the loop, then print the list of those that must not be used with each other (values %opt_excl) or point at the following usage message

collect the conflicts as they are observed; print them after the loop

or, see a different approach in ikegami's answer

However, one is expected to know of allowed invocations of a program and any listing of conflicts is a courtesy to the forgetful user (or a debugging aid); a usage message is printed as well anyway.

Given the number of conflicting options the usage message should have a prominent note on this. Also consider that so many conflicting options may indicate a design flaw.

Finally, this code fully relies on the fact that this processing goes once per run and operates with a handful of options; thus it is not concerned with efficiency and freely uses ancillary data structures.


问:
Send .csv file as attachment through UTL_MAIL.Send
I have a file on local drive let's say C:\test\att.csv. I had configured PL/SQL procedure to gather data from database and send an email. The att.csv file contains some values which I have send as an attachment of the email. Can you please help me how to do that. Below is my current code.</p>

```<code>EXECUTE IMMEDIATE 'ALTER SESSION SET smtp_out_server = ''abcd.abc.ab''';
  UTL_MAIL.send(sender => 'XXX@abc.com',
            recipients => 'xxx@abc.com',
               subject => 'Test Databases'',
               message =>  v_htmlbody,
               mime_type => 'text/html; charset=us-ascii');
</code>```

答:
To send an attachment using UTL_MAIL you need to use either UTL_MAIL.send_attach_raw or UTL_MAIL.send_attach_varchar2. Refer to https://docs.oracle.com/database/121/ARPLS/u_mail.htm#ARPLS71208 for the parameters to pass, including attachment and att_filename. These procedures require that the data for the attachment is available in a RAW or VARCHAR2 format.

If the attachment is on the local disk on the database server, you can load the data using UTL_FILE. Refer to: https://docs.oracle.com/database/121/ARPLS/u_file.htm#ARPLS069

Body:
I have a file on local drive let's say C:\test\att.csv. I had configured PL/SQL procedure to gather data from database and send an email. The att.csv file contains some values which I have send as an attachment of the email. Can you please help me how to do that. Below is my current code.

EXECUTE IMMEDIATE 'ALTER SESSION SET smtp_out_server = ''abcd.abc.ab''';
  UTL_MAIL.send(sender => 'XXX@abc.com',
            recipients => 'xxx@abc.com',
               subject => 'Test Databases'',
               message =>  v_htmlbody,
               mime_type => 'text/html; charset=us-ascii');


问:
How can I achieve a dashed or dotted border in WPF?
I have a ListViewItem that I am applying a Style to and I would like to put a dotted grey line as the bottom Border.

How can I do this in WPF? I can only see solid color brushes.

答:
A bit late to the party, but the following solution worked for me. It is slightly simpler/better than both other solutions:</p>

```<code><Border BorderThickness="1">
  <Border.BorderBrush>
    <VisualBrush>
      <VisualBrush.Visual>
        <Rectangle StrokeDashArray="4 2" Stroke="Gray" StrokeThickness="1"
                  Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualWidth}"
                  Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualHeight}"/>
      </VisualBrush.Visual>
    </VisualBrush>
  </Border.BorderBrush>

  <TextBlock Text="Whatever" />
</Border>
</code>```

Body:
A bit late to the party, but the following solution worked for me. It is slightly simpler/better than both other solutions:

<Border BorderThickness="1">
  <Border.BorderBrush>
    <VisualBrush>
      <VisualBrush.Visual>
        <Rectangle StrokeDashArray="4 2" Stroke="Gray" StrokeThickness="1"
                  Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualWidth}"
                  Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualHeight}"/>
      </VisualBrush.Visual>
    </VisualBrush>
  </Border.BorderBrush>

  <TextBlock Text="Whatever" />
</Border>


答:
To extract the element with text "snail" you can use either of the following :

css_selector :

```<code>elem1 = driver.find_element_by_css_selector("a[href=qry.php?userid=snail]")
</code>```

xpath :

```<code>elem1 = driver.find_element_by_xpath("//a[@href='qry.php?userid=snail']")
</code>```

xpath (Multiple Attributes):

```<code>elem1 = driver.find_element_by_xpath("//a[@href='qry.php?userid=snail' and text()='snail']")
</code>```

To extract the element with text "hello world" you can use either of the following :

css_selector :

```<code>elem2 = driver.find_element_by_css_selector("a[con.php?bid=284&id=142707]")
</code>```

xpath :

```<code>elem2 = driver.find_element_by_xpath("//a[@href='con.php?bid=284&id=142707']")
</code>```

xpath (Multiple Attributes):

```<code>elem2 = driver.find_element_by_xpath("//a[@href='con.php?bid=284&id=142707' and contains(.,'hello world')]")
</code>```

Title: How to extract the two elements in Selenium(python)?

Body:
To extract the element with text "snail" you can use either of the following :

css_selector :

elem1 = driver.find_element_by_css_selector("a[href=qry.php?userid=snail]")

xpath :

elem1 = driver.find_element_by_xpath("//a[@href='qry.php?userid=snail']")

xpath (Multiple Attributes):

elem1 = driver.find_element_by_xpath("//a[@href='qry.php?userid=snail' and text()='snail']")

To extract the element with text "hello world" you can use either of the following :

css_selector :

elem2 = driver.find_element_by_css_selector("a[con.php?bid=284&id=142707]")

xpath :

elem2 = driver.find_element_by_xpath("//a[@href='con.php?bid=284&id=142707']")

xpath (Multiple Attributes):

elem2 = driver.find_element_by_xpath("//a[@href='con.php?bid=284&id=142707' and contains(.,'hello world')]")


问:
How to post image file type in postman or rest client form data?
I did one project in Android (Retrofit) ,I could have gotten response fine in APP,but I don't know how to get response in Postman and Advanced REST client , my issue is how do I send file Type(I don't know what to call it is),In project I achieved by putting  new TypedFile("image/png",... but how would I put these parameters in Postman and Advanced REST client? I want to check and know about it, I searched lot and I tried lot but no result. Please help me...

 Here is project code:

```<code> MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
    try {
        multipartTypedOutput.addPart("originalImgBlob", new TypedFile("image/png", files.get(0)));
        multipartTypedOutput.addPart("img430Blog", new TypedFile("image/png;base64", files.get(1)));
        multipartTypedOutput.addPart("img200Blog", new TypedFile("image/png;base64", files.get(2)));
        multipartTypedOutput.addPart("img100Blog", new TypedFile("image/png;base64", files.get(3)));
        multipartTypedOutput.addPart("blurResponseBlob", new TypedFile("image/png;base64", files.get(4)));
        Log.d("UploadActivity", "postNewsFeed() returned: " + "" + files.get(2));
    } catch (Exception e) {
        e.printStackTrace();
    }
    doServereCall(multipartTypedOutput);
</code>```

```<code>/* Set profile pic in registration */
@Headers("Accept:application/json")
@POST("/api/mbrphotos/prfImgIU/{memberId}/{actionType}")
public void sendMultiImages(@Path("memberId") String memberId,
                            @Path("actionType") String actionType,
                            @Body MultipartTypedOutput multipartTypedOutput, Callback<JsonObject> callback);
</code>```

答: In Advanced REST Client go to "Body" tab and choose "Any file data" to enable file upload.

Body:
I did one project in Android (Retrofit) ,I could have gotten response fine in APP,but I don't know how to get response in Postman and Advanced REST client , my issue is how do I send file Type(I don't know what to call it is),In project I achieved by putting  new TypedFile("image/png",... but how would I put these parameters in Postman and Advanced REST client? I want to check and know about it, I searched lot and I tried lot but no result. Please help me...

 Here is project code:

 MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
    try {
        multipartTypedOutput.addPart("originalImgBlob", new TypedFile("image/png", files.get(0)));
        multipartTypedOutput.addPart("img430Blog", new TypedFile("image/png;base64", files.get(1)));
        multipartTypedOutput.addPart("img200Blog", new TypedFile("image/png;base64", files.get(2)));
        multipartTypedOutput.addPart("img100Blog", new TypedFile("image/png;base64", files.get(3)));
        multipartTypedOutput.addPart("blurResponseBlob", new TypedFile("image/png;base64", files.get(4)));
        Log.d("UploadActivity", "postNewsFeed() returned: " + "" + files.get(2));
    } catch (Exception e) {
        e.printStackTrace();
    }
    doServereCall(multipartTypedOutput);

/* Set profile pic in registration */
@Headers("Accept:application/json")
@POST("/api/mbrphotos/prfImgIU/{memberId}/{actionType}")
public void sendMultiImages(@Path("memberId") String memberId,
                            @Path("actionType") String actionType,
                            @Body MultipartTypedOutput multipartTypedOutput, Callback<JsonObject> callback);


问:
How to return value after event click
I try make simple case with 2 button like this.

$(document).ready(function(){
  function tes(){
    var result;
    $("#wrapper").html('<button id="btn2">Button 2</button>');
    $("#btn2").click(function(){
      result = "How to passing this value?, After button 2 clicked"
    })
    return result;
  }

  $("#btn1").click(function(){
    alert(tes());
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<div id="wrapper"></div></code>```

How to pass value of variable result after button2 click, where element for button2 exists after button1 click?

答:
Ok as you've no problem using jQuery. I think this is what you want

var result = '';
function tes(){

 document.getElementById("wrapper").innerHTML = '<button id="btn2">Button 2</button>';
   result = "How to passing this value?, After button 2 clicked"
}

var button = document.getElementById("btn1");
button.onclick = function(){
 tes();
}
$(document).on('click', '#btn2', function(){
     alert(result)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<div id="wrapper"></div></code>```

Ps. You're trying to bind events on dynamically created elements and the way you're doing in your code is not the proper way. You can do that $(document).on('click', 'DOM_Element', function(){}).  Just to let you know so you should have an idea when working on JS in future

Title: How to return value after event click

Body:
I try make simple case with 2 button like this.

$(document).ready(function(){
  function tes(){
    var result;
    $("#wrapper").html('<button id="btn2">Button 2</button>');
    $("#btn2").click(function(){
      result = "How to passing this value?, After button 2 clicked"
    })
    return result;
  }

  $("#btn1").click(function(){
    alert(tes());
  })
})

<button id="btn1">Button 1</button>

How to pass value of variable result after button2 click, where element for button2 exists after button1 click?

Body:
Ok as you've no problem using jQuery. I think this is what you want

var result = '';
function tes(){

 document.getElementById("wrapper").innerHTML = '<button id="btn2">Button 2</button>';
   result = "How to passing this value?, After button 2 clicked"
}

var button = document.getElementById("btn1");
button.onclick = function(){
 tes();
}
$(document).on('click', '#btn2', function(){
     alert(result)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<div id="wrapper"></div>

Ps. You're trying to bind events on dynamically created elements and the way you're doing in your code is not the proper way. You can do that $(document).on('click', 'DOM_Element', function(){}).  Just to let you know so you should have an idea when working on JS in future


问:
App Getting Crash while Continuous open and close Activity between 2 activities
My Android App having multiple activities, now my problem is unable to findable.

A Activity have one recyclerView it get data from local database, If I click the items it will open B Activity, this same flow continuously then app getting crash(like open B Activity come back to A Activity and open again B activity- up to 5 to 6 time do same action then app getting crash)

The Crash message is related to SQLite DATABASE but unable to find where it occurs. Please help me... already spend more time for this...

Note: open DB on Oncreate and Close DB on OnDestroy in both activities

Error Message

```<code>E/SQLiteQuery: exception: unable to open database file (code 14); query: SELECT DISTINCT * FROM parameters WHERE inspection_no LIKE '%TEST-123%'
E/InputChannel-JNI: Error 24 dup channel fd 1023.
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.testapp.testprocess, PID: 13078
                  java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
                      at android.view.InputChannel.nativeReadFromParcel(Native Method)
                      at android.view.InputChannel.readFromParcel(InputChannel.java:148)
                      at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:841)
                      at android.view.ViewRootImpl.setView(ViewRootImpl.java:640)
                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3518)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2733)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6121)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
</code>```

答:
I solved the issue by the following steps.

I have created Singleton Database, so it ensures the database object created only once.

Closing cursor object after querying the database. (I missed it)

Closing the database in onStop() of an activity. (I read onDestroy() is not safe, it won't be called for sure)

Thanks to all for the timely help :)

Body:
My Android App having multiple activities, now my problem is unable to findable.

A Activity have one recyclerView it get data from local database, If I click the items it will open B Activity, this same flow continuously then app getting crash(like open B Activity come back to A Activity and open again B activity- up to 5 to 6 time do same action then app getting crash)

The Crash message is related to SQLite DATABASE but unable to find where it occurs. Please help me... already spend more time for this...

Note: open DB on Oncreate and Close DB on OnDestroy in both activities

Error Message

E/SQLiteQuery: exception: unable to open database file (code 14); query: SELECT DISTINCT * FROM parameters WHERE inspection_no LIKE '%TEST-123%'
E/InputChannel-JNI: Error 24 dup channel fd 1023.
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.testapp.testprocess, PID: 13078
                  java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
                      at android.view.InputChannel.nativeReadFromParcel(Native Method)
                      at android.view.InputChannel.readFromParcel(InputChannel.java:148)
                      at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:841)
                      at android.view.ViewRootImpl.setView(ViewRootImpl.java:640)
                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3518)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2733)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6121)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)


问:
Java: is there a way to convert text into a class?
I have the input: "ListClients param1 param2"
which splits by " " to "ListClients", "param1", "param2";

and I want to call a static method from ListClients.

So it would do ListClients.someMethodThatTakesPraams(param1, param2);

is there a way to do that in java?

答: Reflection will be your friend.</p>

Body: Reflection will be your friend.


问:
How to embed an HTML div inside of a svg
Example:

```<code><div> Hello World </div>

<svg>
<div> From SVG Land</div>
</svg>
</code>```

Question:

Despite the tags, are SVG objects parsed separately and not some proper part of the dom tree? How do I get DIVs inside of SVG elements?

答:
As mentioned by @Stasik, foreignObject can be used.

Example:

```<code><svg>
    <foreignObject width="100" height="50"
               requiredExtensions="http://www.w3.org/1999/xhtml">
      <!-- XHTML content goes here -->
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Here is a paragraph that requires word wrap</p>
      </body>
    </foreignObject>
<svg>
</code>```

Extracted from: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject

Body:
Example:

 Hello World

<svg>

 From SVG Land

</svg>

Question:

Despite the tags, are SVG objects parsed separately and not some proper part of the dom tree? How do I get DIVs inside of SVG elements?

Body:
As mentioned by @Stasik, foreignObject can be used.

Example:

<svg>
    <foreignObject width="100" height="50"
               requiredExtensions="http://www.w3.org/1999/xhtml">
      <!-- XHTML content goes here -->
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Here is a paragraph that requires word wrap</p>
      </body>
    </foreignObject>
<svg>

Extracted from: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject