问:
New data only appears after a page reload- AngularJs
I have a small problem here. When I add a new data via a form, it is not displayed/fetched until page reloads. For Page reload, I'm using $state.reload(), as follows:

.then(function () {
          $state.reload();
        });```

If I remove it($state.reload()), data won't be displayed until I do manual reload of the browser. Which technique can I use in the promise so that after new data is added, it get displayed without reloading page? Thanks.

答:
You should read response from the call back.

```<code>.then(function (response) {
     console.log(response);
    });
</code>```

get the data from "response" and bind it with the model.

Body:
I have a small problem here. When I add a new data via a form, it is not displayed/fetched until page reloads. For Page reload, I'm using $state.reload(), as follows:

.then(function () {
          $state.reload();
        });

If I remove it($state.reload()), data won't be displayed until I do manual reload of the browser. Which technique can I use in the promise so that after new data is added, it get displayed without reloading page? Thanks.

Body:
You should read response from the call back.

.then(function (response) {
     console.log(response);
    });

get the data from "response" and bind it with the model.


来源: stackexchange

问:
Get elements of a sublist in python based on indexes of a different list
I have two lists of lists.

I want to get the elements from second list of lists, based on a value from the first list of lists.

I if I have simple lists, everything go smooth, but once I have list of list, I'm missing something at the end.

Here is the code working for two lists (N = names, and V = values):

```<code>N = ['name 1', 'name 2','name 3','name 4','name 5','name 6','name 7','name 8','name 9','name 10']

V = ['val 1', 'val 2','val 3','val 4','val 5','val 6','val 7','val 8','val 9','val 10']

bool_ls = []
NN = N
for i in NN:
        if i == 'name 5':
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)

# GOOD INDEXES = GI

GI = [i for i, x in enumerate(bool_ls) if x == 'y']

# SELECT THE GOOD VALUES = "GV" FROM V

GV = [V[index] for index in GI]
</code>```

if I define a function, works well applied to the two lists:

```<code>def GV(N,V,name):
    bool_ls = []
    NN = N
    for i in NN:
        if i == name:
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)
    GI = [i for i, x in enumerate(bool_ls) if x == 'y']
    GV = [V[index] for index in GI]

    return GV
</code>```

Once I try "list of list", I cannot get the similar results. My code looks like below so far:

```<code>NN = [['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3']]

VV = [['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3']]

def GV(NN,VV,name):
    bool_ls = []
    NNN = NN
    for j in NNN:
        for i in j:
            if i == name:
                i = 'y'
            else:
                i = 'n'
            bool_ls.append(i)

# here is where I'm lost
</code>```

Help greatly appreciated! Thank you.

答: There's an easier way to do what your function is doing, but, to answer your question, you just need two loops (one for each level of lists): the first list iterates over the list of lists, the second iterates over the inner lists and does the somewhat odd y or n thing to chose a value.

ContentLicense: CC BY-SA 3.0

Body:
I have two lists of lists.

I want to get the elements from second list of lists, based on a value from the first list of lists.

I if I have simple lists, everything go smooth, but once I have list of list, I'm missing something at the end.

Here is the code working for two lists (N = names, and V = values):

N = ['name 1', 'name 2','name 3','name 4','name 5','name 6','name 7','name 8','name 9','name 10']

V = ['val 1', 'val 2','val 3','val 4','val 5','val 6','val 7','val 8','val 9','val 10']

bool_ls = []
NN = N
for i in NN:
        if i == 'name 5':
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)

# GOOD INDEXES = GI

GI = [i for i, x in enumerate(bool_ls) if x == 'y']

# SELECT THE GOOD VALUES = "GV" FROM V

GV = [V[index] for index in GI]

if I define a function, works well applied to the two lists:

def GV(N,V,name):
    bool_ls = []
    NN = N
    for i in NN:
        if i == name:
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)
    GI = [i for i, x in enumerate(bool_ls) if x == 'y']
    GV = [V[index] for index in GI]

    return GV

Once I try "list of list", I cannot get the similar results. My code looks like below so far:

NN = [['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3']]

VV = [['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3']]

def GV(NN,VV,name):
    bool_ls = []
    NNN = NN
    for j in NNN:
        for i in j:
            if i == name:
                i = 'y'
            else:
                i = 'n'
            bool_ls.append(i)

# here is where I'm lost

Help greatly appreciated! Thank you.


问:
Intellisense missing for ajax with jQuery in Visual Studio 2010

I'm new in ASP.NET, I'm making a website and I need ajax to do something. But when I try to call ajax in jQuery, it doesn't appear after $. sign. I have downloaded latest version jQuery. I'm using Visual Studio 2010.

I took a picture for my problem. I tried some soluntion above but ajax still not work.The picture for my problem

答:
This example can be used to get you started.
This can be your view:

```<code><!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index28</title>
    @*the next line should point to your jquery*@
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#create").click(function () {
                var MyModel = {
                    ArticleName: $("#articleName").val(),
                    CountField: $("#countField").val(),
                    PriceField: $("#priceField").val()
                }
                $.ajax({
                    url: '/Home/GoIntoMethod',
                    type: 'POST',
                    data: MyModel,
                    dataType: 'json',
                    success: function (result) {
                        $("#targetName").val(result.targetName);
                        $("#targetCount").val(result.targetCount);
                        $("#targetPrice").val(result.targetPrice);
                    },
                    error: function (data, status, error) {
                        //alert("error");
                    }
                });
            })
        })
    </script>
</head>
<body>
    <div>
        @*you can make these field using html helper*@
        <input type="text" id="targetName" />
        <input type="text" id="targetCount" />
        <input type="text" id="targetPrice" />
    </div>
    <div class="row">
        <input id='create' type="submit" value="Save" />
    </div>
</body>
</html>
</code>```

Here is the controller:

```<code>public class HomeController : Controller
{
    [HttpPost]
    public ActionResult GoIntoMethod()
    {
        //put a breakpoint here to see you can do whatever you want with the fields
        return Json(new
        {
            targetName = "aName",
            targetCount = "4",
            targetPrice = "2.37"
        }
         , @"application/json");
    }

    public ActionResult Index28(int? id)
    {
        return View();
    }
</code>```

Body:
This example can be used to get you started.
This can be your view:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index28</title>
    @*the next line should point to your jquery*@
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#create").click(function () {
                var MyModel = {
                    ArticleName: $("#articleName").val(),
                    CountField: $("#countField").val(),
                    PriceField: $("#priceField").val()
                }
                $.ajax({
                    url: '/Home/GoIntoMethod',
                    type: 'POST',
                    data: MyModel,
                    dataType: 'json',
                    success: function (result) {
                        $("#targetName").val(result.targetName);
                        $("#targetCount").val(result.targetCount);
                        $("#targetPrice").val(result.targetPrice);
                    },
                    error: function (data, status, error) {
                        //alert("error");
                    }
                });
            })
        })
    </script>
</head>
<body>
    <div>
        @*you can make these field using html helper*@
        <input type="text" id="targetName" />
        <input type="text" id="targetCount" />
        <input type="text" id="targetPrice" />
    </div>
    <div class="row">
        <input id='create' type="submit" value="Save" />
    </div>
</body>
</html>

Here is the controller:

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult GoIntoMethod()
    {
        //put a breakpoint here to see you can do whatever you want with the fields
        return Json(new
        {
            targetName = "aName",
            targetCount = "4",
            targetPrice = "2.37"
        }
         , @"application/json");
    }

    public ActionResult Index28(int? id)
    {
        return View();
    }


问:
If statement using php and advances custom fields in wordpress - hide empty fields
I have an and if statement for a button.

If both advanced custom fields are present I want it to show the button and if not I want it to hide but I am struggling here.

I have looked at this page:

https://www.advancedcustomfields.com/resources/hiding-empty-fields/

Here is my code:

```<code><?php if( get_field('button_link') && get_field('button_text') ): ?>
    <a href="<?php the_field('button_link');  ?>" class="btn third-btn mx-auto">
    <?php the_field('button_text');?> <i class="fa fa-arrow-circle-right" aria-hidden="true"></i>
  </a>
<?php endif; ?>
</code>```

Anyone got a suggestion please?

Cheers :)

答:
I am not an ACF expert but looking at the get_field() function description here https://www.advancedcustomfields.com/resources/get_field/ it looks like the function will never return a boolean as mentioned on the Description and I quote:

Returns the value of the specified field

Since it does not return a boolean value, you can't assure get_field( 'something' ) && get_field( 'something2' ) will be the correct boolean. There are certain values that the if statement interpret as boolean true or false. For example null and 0 are interpreted as false, but -1 interpreted as true. I would recommend to do a

```<code>var_dump( get_field('button_link') )
</code>```

to explore the output. Also, according to https://www.advancedcustomfields.com/resources/get_field/ under 'Check if value exists' you can check if one value exists, so this might work:

```<code><?php if ( get_field( 'button_link' ) ) : ?>
    <?php if ( get_field( 'button_text' ) ) : ?>
        <a href="<?php the_field( 'button_link' ) ?>" class="btn third-btn mx-auto">
            <?php the_field( 'button_text' ) ?> <i class="fa fa-arrow-circle-right" aria-hidden="true"></i>
        </a>
    <?php endif ?>
<?php endif ?>
</code>```

It is like a nested AND without using the && operator. If this does not work we need more information about what you get from:

```<code>var_dump( get_field( 'button_link' ) );
var_dump( get_field( 'button_text' ) );
</code>```

Body:
I have an and if statement for a button.

If both advanced custom fields are present I want it to show the button and if not I want it to hide but I am struggling here.

I have looked at this page:

https://www.advancedcustomfields.com/resources/hiding-empty-fields/

Here is my code:

<?php if( get_field('button_link') && get_field('button_text') ): ?>
    <a href="<?php the_field('button_link');  ?>" class="btn third-btn mx-auto">
    <?php the_field('button_text');?>

<?php endif; ?>

Anyone got a suggestion please?

Cheers :)

Body:
I am not an ACF expert but looking at the get_field() function description here https://www.advancedcustomfields.com/resources/get_field/ it looks like the function will never return a boolean as mentioned on the Description and I quote:

Returns the value of the specified field

Since it does not return a boolean value, you can't assure get_field( 'something' ) && get_field( 'something2' ) will be the correct boolean. There are certain values that the if statement interpret as boolean true or false. For example null and 0 are interpreted as false, but -1 interpreted as true. I would recommend to do a

var_dump( get_field('button_link') )

to explore the output. Also, according to https://www.advancedcustomfields.com/resources/get_field/ under 'Check if value exists' you can check if one value exists, so this might work:

<?php if ( get_field( 'button_link' ) ) : ?>
    <?php if ( get_field( 'button_text' ) ) : ?>
        <a href="<?php the_field( 'button_link' ) ?>" class="btn third-btn mx-auto">
            <?php the_field( 'button_text' ) ?> <i class="fa fa-arrow-circle-right" aria-hidden="true"></i>
        </a>
    <?php endif ?>
<?php endif ?>

It is like a nested AND without using the && operator. If this does not work we need more information about what you get from:

var_dump( get_field( 'button_link' ) );
var_dump( get_field( 'button_text' ) );


问:
Error "Cannot read property 'style' of null" in Chrome Extension
As a javascript beginner I want to create an extension to display a modal when a user points a URL in Google Chrome. In an HTML where I have put HTML + CSS + JS in one file, it works fine but putting it into a Chrome extension gets me this error message:"Cannot read property 'style' of null" for line "modal.style.display = "block";" in content_script.js. It seems that modal is null and the modal does not show up. I can't see what I am doing wrong.

content_script.js with JS:

```<code>var modal  = document.createElement ('iframe');
modal.src  = chrome.extension.getURL ('./options.html');
document.body.appendChild (modal);

var modal = document.getElementById("myModal");

document.addEventListener('mousemove', function (e) {
  var srcElement = e.srcElement;
  if (srcElement.nodeName == 'A') {
        modal.style.display = "block";
    }
  if (srcElement.nodeName != 'A') {
        modal.style.display = "none";
    }
}, false);
</code>```

options.html - the content of the modal in HTML:

```<code><div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>
</code>```

manifest.json

```<code>{
   "background": {
      "persistent": false,
      "scripts": ["background.js" ]
   },

   "browser_action": {
   "default_icon": "icon128.png"
   },

   "content_scripts": [ {
      "js": ["content_script.js"],
      "matches": [ "http://*/*", "https://*/*" ],
      "css" : ["css.css"],
      "run_at": "document_end"
   } ],

   "description": "Description",
   "icons": {
      "128": "icon128.png",
      "16": "icon16.png",
      "48": "icon48.png"
   },

   "web_accessible_resources": [
    "options.html"]
   ,

   "manifest_version": 2,
   "name": "Name",
   "permissions": [ "tabs", "http://*/*", "https://*/*" ],
   "version": "1.0"
}
</code>```

答:
An  is a separate document. Its content is not directly accessible from the document in which the  exists. In fact, access between such documents may be restricted for security reasons, which is one of the reasons to use iframes.

Your code:

```<code>var modal = document.getElementById("myModal");
</code>```

is attempting to access the content of the  by searching in the top level document. The iframe's content does not exist in the top level document, so the element with the ID myModal is not found. Thus, modal is now null, which causes your error. You need to perform your search for the ID within the  document, which is accessed with .contentDocument:

```<code>var myModalDiv = modal.contentDocument.getElementById("myModal");
</code>```

NOTE: Part of the confusion is using the same variable name to both reference your  and to try to reference the top
 within the . You should not reuse variable names in this way, as it generates confusion as to what your variable represents. Under most circumstances, a variable should be named to match what it represents. Usually, there is no reason to reuse variable names in this manner. If you are going to do so and the variable is going to represent multiple things, then that should be indicated in the variable's name.

Body:
As a javascript beginner I want to create an extension to display a modal when a user points a URL in Google Chrome. In an HTML where I have put HTML + CSS + JS in one file, it works fine but putting it into a Chrome extension gets me this error message:"Cannot read property 'style' of null" for line "modal.style.display = "block";" in content_script.js. It seems that modal is null and the modal does not show up. I can't see what I am doing wrong.

content_script.js with JS:

var modal  = document.createElement ('iframe');
modal.src  = chrome.extension.getURL ('./options.html');
document.body.appendChild (modal);

var modal = document.getElementById("myModal");

document.addEventListener('mousemove', function (e) {
  var srcElement = e.srcElement;
  if (srcElement.nodeName == 'A') {
        modal.style.display = "block";
    }
  if (srcElement.nodeName != 'A') {
        modal.style.display = "none";
    }
}, false);

options.html - the content of the modal in HTML:

      ×

Modal Header

Some text in the Modal Body

Some other text...

Modal Footer

manifest.json

{
   "background": {
      "persistent": false,
      "scripts": ["background.js" ]
   },

   "browser_action": {
   "default_icon": "icon128.png"
   },

   "content_scripts": [ {
      "js": ["content_script.js"],
      "matches": [ "http://*/*", "https://*/*" ],
      "css" : ["css.css"],
      "run_at": "document_end"
   } ],

   "description": "Description",
   "icons": {
      "128": "icon128.png",
      "16": "icon16.png",
      "48": "icon48.png"
   },

   "web_accessible_resources": [
    "options.html"]
   ,

   "manifest_version": 2,
   "name": "Name",
   "permissions": [ "tabs", "http://*/*", "https://*/*" ],
   "version": "1.0"
}

Body:
An <iframe> is a separate document. Its content is not directly accessible from the document in which the <iframe> exists. In fact, access between such documents may be restricted for security reasons, which is one of the reasons to use iframes.

Your code:

var modal = document.getElementById("myModal");

is attempting to access the content of the <iframe> by searching in the top level document. The iframe's content does not exist in the top level document, so the element with the ID myModal is not found. Thus, modal is now null, which causes your error. You need to perform your search for the ID within the <iframe> document, which is accessed with .contentDocument:

var myModalDiv = modal.contentDocument.getElementById("myModal");

NOTE: Part of the confusion is using the same variable name to both reference your <iframe> and to try to reference the top <div> within the <iframe>. You should not reuse variable names in this way, as it generates confusion as to what your variable represents. Under most circumstances, a variable should be named to match what it represents. Usually, there is no reason to reuse variable names in this manner. If you are going to do so and the variable is going to represent multiple things, then that should be indicated in the variable's name.


问:
Set Background in a LinearLayout from byte array
I have a LinearLayout with a default Background, but in some circumstances I need to set a custom Background from a byte[] data from Blob object in SQL Database.
I alreay have made the custom Adapter but I have no idea how do the image part.</p>

```<code>if (Ad.getAd_image().length > 0) {
    //Ad.getAd_image() is a byte[] object
    ad_image_layout.setBackground(???);
}
</code>```

答:
We can achieve by 2 ways,
1. If you have direct byte[] you can use

```<code>byte[] b = //your data;
Drawable image = new BitmapDrawable(getResources(), BitmapFactory.decodeByteArray(b, 0, b.length));
</code>```

If you have input stream you can use this

```<code>InputStream is = //your input stream;
Bitmap bitmap = BitmapFactory.decodeStream(is);
</code>```

Body:
I have a LinearLayout with a default Background, but in some circumstances I need to set a custom Background from a byte[] data from Blob object in SQL Database.
I alreay have made the custom Adapter but I have no idea how do the image part.

if (Ad.getAd_image().length > 0) {
    //Ad.getAd_image() is a byte[] object
    ad_image_layout.setBackground(???);
}

Body:
We can achieve by 2 ways,
1. If you have direct byte[] you can use

byte[] b = //your data;
Drawable image = new BitmapDrawable(getResources(), BitmapFactory.decodeByteArray(b, 0, b.length));

If you have input stream you can use this

InputStream is = //your input stream;
Bitmap bitmap = BitmapFactory.decodeStream(is);


问:
BASH script to check for two mounted drives 'unary operator expected'
Trying to write a bash script that will check for two mounted drives then do something if both are connected. So far I've got:

```<code>if [ $(mount | grep -c /media/card) != 1 ]
 then
    echo "ERROR: SD card not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
    if [ $(mount | grep -c /media/backup) !=1 ]
    then
            echo "ERROR: Backup not mounted"
            sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
            sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
    else
            echo "All Plugged in"
    fi
fi
</code>```

Running returns the error:

```<code>./backup2.sh: line 12: [: 0: unary operator expected
</code>```

Not sure why the first if statement works, but then the second doesn't, as they basically the same. Is there a cleaner way of checking for two mounted devices? Ideally outputting an error showing which one(s) aren't mounted.

答:
This is a little cleaner code -- removed the nested if and used elif instead as well as taken into account janos remark about the space needed at !=1:

```<code>#!/bin/bash

if [ $(mount | grep -c /media/card) != 1 ]
then
    echo "ERROR: SD card not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
elif [ $(mount | grep -c /media/backup) != 1 ]
then
    echo "ERROR: Backup not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
    echo "All Plugged in"
fi
</code>```

Seems to work well under Red Hat 6.x

Body:
Trying to write a bash script that will check for two mounted drives then do something if both are connected. So far I've got:

if [ $(mount | grep -c /media/card) != 1 ]
 then
    echo "ERROR: SD card not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
    if [ $(mount | grep -c /media/backup) !=1 ]
    then
            echo "ERROR: Backup not mounted"
            sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
            sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
    else
            echo "All Plugged in"
    fi
fi

Running returns the error:

./backup2.sh: line 12: [: 0: unary operator expected

Not sure why the first if statement works, but then the second doesn't, as they basically the same. Is there a cleaner way of checking for two mounted devices? Ideally outputting an error showing which one(s) aren't mounted.

Body:
This is a little cleaner code -- removed the nested if and used elif instead as well as taken into account janos remark about the space needed at !=1:

#!/bin/bash

if [ $(mount | grep -c /media/card) != 1 ]
then
    echo "ERROR: SD card not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
elif [ $(mount | grep -c /media/backup) != 1 ]
then
    echo "ERROR: Backup not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
    echo "All Plugged in"
fi

Seems to work well under Red Hat 6.x


问:
How to output an Excel *.xls file from classic ASP
I have a number of generated html tables that I need to output as an Excel file. The site is codded in classic ASP. Is this possible? Could it be done by somehow using the Open Office libraries?

EDIT: Thus far, I have tried some of the suggestions, but it seems to fail. Ideally, I want the user to be able to click a link that will begin the download of a .xls file. This code:

```<code><%@ Language=VBScript %>
<%  option explicit

Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", " filename=excelTest.xls"
%>
<table>
    <tr>
        <th>Test Col 1</th>
        <th>Test Col 2</th>
        <th>Test Col 3</th>
        <th colspan="2">Test Col 4</th>
        <th>Test Col 6</th>
        <th>Test Col 7</th>
    </tr>
    <tr>
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
    </tr>
</table>
</code>```

seems to fail when IE7 is used to get the page. IE says that it "cannot download excelTest.asp" and that "The requested site is either unavailable or cannot be found."

答:
You must specify the file to be downloaded (attachment) by the client in the http header:

```<code>Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", "attachment: filename=excelTest.xls"
</code>```

http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html

OwnerDisplayName: cdeszaq

ContentLicense: CC BY-SA 2.5

Body:
I have a number of generated html tables that I need to output as an Excel file. The site is codded in classic ASP. Is this possible? Could it be done by somehow using the Open Office libraries?

EDIT: Thus far, I have tried some of the suggestions, but it seems to fail. Ideally, I want the user to be able to click a link that will begin the download of a .xls file. This code:

<%@ Language=VBScript %>
<%  option explicit

Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", " filename=excelTest.xls"
%>

        Test Col 1
        Test Col 2
        Test Col 3
        Test Col 4
        Test Col 6
        Test Col 7

        Data
        Data
        Data
        Data
        Data
        Data
        Data

seems to fail when IE7 is used to get the page. IE says that it "cannot download excelTest.asp" and that "The requested site is either unavailable or cannot be found."

LastEditorDisplayName: cdeszaq

Body:
You must specify the file to be downloaded (attachment) by the client in the http header:

Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", "attachment: filename=excelTest.xls"

http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html

OwnerDisplayName: Espen


问:
Missing argument 1 for give_profile_name() error after changing host
I changed host recently. And I am seeing an error after this. I was using a piece of code at Displaying Logged-In User Name in Wordpress Menu
to show the user name instead of 'profile page'. It was running fine on the previous host. After I copied everything and data, I am seeing this error on the menu bar. Users see this when they log in. Please suggest the remedy.

Following is the code that I am usign. It is exactly the same as given on the link of stackoverflow that I posted. I have created a page #profile_name# just as mentioned in the link.

```<code>function give_profile_name($atts){
$user=wp_get_current_user();
$name=$user->user_firstname .' '. $user->user_lastname ;
return $name;
}

add_shortcode('profile_name', 'give_profile_name');

add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
    if ( '#profile_name#' == $menu_item->title ) {
        global $shortcode_tags;
        if ( isset( $shortcode_tags['profile_name'] ) ) {
            // Or do_shortcode(), if you must.
            $menu_item->title = call_user_func( $shortcode_tags['profile_name'] );
        }
    }
}

return $menu_items;
}
</code>```

答:
Not sure if you still an answer to this but I figured I would reply anyway since I ran into this same error with the same code snippet while trying to add a user's first name to a navigation menu. I noticed that it was still working despite the error, so after playing around, I just deleted the $atts from the function. So the first piece of the code would be:

```<code>function give_profile_name(){
$user=wp_get_current_user();
$name=$user->user_firstname .' '. $user->user_lastname ;
return $name;
}
</code>```

Body:
I changed host recently. And I am seeing an error after this. I was using a piece of code at Displaying Logged-In User Name in Wordpress Menu
to show the user name instead of 'profile page'. It was running fine on the previous host. After I copied everything and data, I am seeing this error on the menu bar. Users see this when they log in. Please suggest the remedy.

Following is the code that I am usign. It is exactly the same as given on the link of stackoverflow that I posted. I have created a page #profile_name# just as mentioned in the link.

function give_profile_name($atts){
$user=wp_get_current_user();
$name=$user->user_firstname .' '. $user->user_lastname ;
return $name;
}

add_shortcode('profile_name', 'give_profile_name');

add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
    if ( '#profile_name#' == $menu_item->title ) {
        global $shortcode_tags;
        if ( isset( $shortcode_tags['profile_name'] ) ) {
            // Or do_shortcode(), if you must.
            $menu_item->title = call_user_func( $shortcode_tags['profile_name'] );
        }
    }
}

return $menu_items;
}

Body:
Not sure if you still an answer to this but I figured I would reply anyway since I ran into this same error with the same code snippet while trying to add a user's first name to a navigation menu. I noticed that it was still working despite the error, so after playing around, I just deleted the $atts from the function. So the first piece of the code would be:

function give_profile_name(){
$user=wp_get_current_user();
$name=$user->user_firstname .' '. $user->user_lastname ;
return $name;
}


问:
How to call one Action method from another Action method(both are in the same Controller) in MVC C#?
Hi From the calling Action Method, I have:

```<code>[HttpPost]
public JsonResult SubmitForms(Note note, string action = "Submit")
{
     //some code
     RedirectToAction("SaveDemographicForm", "PatientForms", new { model.DemographicFormData,  action="Submit" , submitAll = true });
     //some code
}
</code>```

And this the Action Method that I am trying to call:

```<code>[HttpPost]
public JsonResult SaveDemographicForm(DemographicForm demographicForm, string action = "Save", bool submitAll = false )
{
      //Some code
}
</code>```

What am I doing wrong here?
Thanks in advance.

答:
using System.Web.Mvc;

using System.Web.Mvc.Html;

```<code>public ActionResult Index()
{
    HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
    helper.RenderAction("Index2");//call your action

    return View();
}

public ActionResult Index2(/*your arg*/)
{
    //your code
    return new EmptyResult();
}
</code>```

Body:
Hi From the calling Action Method, I have:

[HttpPost]
public JsonResult SubmitForms(Note note, string action = "Submit")
{
     //some code
     RedirectToAction("SaveDemographicForm", "PatientForms", new { model.DemographicFormData,  action="Submit" , submitAll = true });
     //some code
}

And this the Action Method that I am trying to call:

[HttpPost]
public JsonResult SaveDemographicForm(DemographicForm demographicForm, string action = "Save", bool submitAll = false )
{
      //Some code
}

What am I doing wrong here?
Thanks in advance.

Body:
using System.Web.Mvc;

using System.Web.Mvc.Html;

public ActionResult Index()
{
    HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
    helper.RenderAction("Index2");//call your action

    return View();
}

public ActionResult Index2(/*your arg*/)
{
    //your code
    return new EmptyResult();
}


问:
Filtering RDD computation dataset
I was practicing with apache spark and i tried doing some computations. Although, i was able to achieve my desired result, but i had to try two different methods before it worked.

I have an existing dataset which i created an RDD from.

"RT @NigeriaNewsdesk: Chibok schoolgirls were swapped for 5 Boko Haram commanders via @todayng"

I wanted to filter and get the words that starts with @ so i  created an RDD from an existing dataset.

```<code>usernameFile = sc.parallelize(tweets)
username = usernameFile.flatMap(lambda line: line.split()).filter(lambda x: x.startswith('@')).collect()
print(username)
</code>```

I got something like this

```<code>[u'R', u'T', u' ', u'@', u'N', u'i', u'g', u'e', u'r', u'i', u'a', u'N', u'e', u'w', u's', u'd', u'e', u's', u'k', u':', u' ', u'C', u'h', u'i', u'b', u'o', u'k', u' ', u's', u'c', u'h', u'o', u'o', u'l', u'g', u'i', u'r', u'l', u's', u' ', u'w', u'e', u'r', u'e', u' ', u's', u'w', u'a', u'p', u'p', u'e', u'd', u' ', u'f'
</code>```

I will also attach it
On the second attempt, i did something like this

```<code>tweets = tweets.split(" ")
usernameFile = sc.parallelize(tweets)
username = usernameFile.flatMap(lambda line: line.split()).filter(lambda x: x.startswith('@')).collect()
print(username)
print("username done")
</code>```

The second attempt worked absolutely fine, but my question is why did i have to split it before parallelizing the dataset?

Can i achieve the same thing without doing this first?

```<code>tweets = tweets.split(" ")
</code>```

Thank you.

答:
Just map directly like this:

```<code>import re

tweets = sc.parallelize([
    "RT @foo abc @bar"
])

tweets.flatMap(lambda s: re.findall("@\w+", s))
</code>```

It doesn't get simpler than that :)

Title: Filtering RDD computation dataset

Body:
I was practicing with apache spark and i tried doing some computations. Although, i was able to achieve my desired result, but i had to try two different methods before it worked.

I have an existing dataset which i created an RDD from.

"RT @NigeriaNewsdesk: Chibok schoolgirls were swapped for 5 Boko Haram commanders via @todayng"

I wanted to filter and get the words that starts with @ so i  created an RDD from an existing dataset.

usernameFile = sc.parallelize(tweets)
username = usernameFile.flatMap(lambda line: line.split()).filter(lambda x: x.startswith('@')).collect()
print(username)

I got something like this

[u'R', u'T', u' ', u'@', u'N', u'i', u'g', u'e', u'r', u'i', u'a', u'N', u'e', u'w', u's', u'd', u'e', u's', u'k', u':', u' ', u'C', u'h', u'i', u'b', u'o', u'k', u' ', u's', u'c', u'h', u'o', u'o', u'l', u'g', u'i', u'r', u'l', u's', u' ', u'w', u'e', u'r', u'e', u' ', u's', u'w', u'a', u'p', u'p', u'e', u'd', u' ', u'f'

I will also attach it
On the second attempt, i did something like this

tweets = tweets.split(" ")
usernameFile = sc.parallelize(tweets)
username = usernameFile.flatMap(lambda line: line.split()).filter(lambda x: x.startswith('@')).collect()
print(username)
print("username done")

The second attempt worked absolutely fine, but my question is why did i have to split it before parallelizing the dataset?

Can i achieve the same thing without doing this first?

tweets = tweets.split(" ")

Thank you.

Body:
Just map directly like this:

import re

tweets = sc.parallelize([
    "RT @foo abc @bar"
])

tweets.flatMap(lambda s: re.findall("@\w+", s))

It doesn't get simpler than that :)


问:
Understanding VBScript
I have a VBScript that I`m converting to PHP, I hae some part that I don`t understand and don`t know the output of ... Also if possible, provide me with a similar method in HTML/PHP

```<code>TextBox1.Value = 1#
txtTurnoverIncl = TextBox1
Format(CDbl(txtTurnoverExcl.Text) * _
                             CDbl(txtRoyalty.Text) / 100, "#,##0.00")
If txtTurnoverExcl.Text <> "" Then
Format(Round(.Text * 14 / 114, 2), "#,##0.00")
TextBox1 = Now()
TextBox3 = Date
TextBox4 = Format(MyDate, "dddd")
</code>```

And this function:

```<code>Private Function SumCashUp() As Double
    Dim i As Long
    Dim tmp As Double
    For i = 10 To 12
        With Me.Controls("TextBox" & i)
            If IsNumeric(.Text) Then
                tmp = tmp + CDbl(.Text)
            End If
        End With
    Next i
    SumCashUp = tmp
End Function
</code>```

I guess thats all.

答:
TextBox1.Value = 1# - Assign the value 1 in format Double to the textbox control. (thanks MikeD)

txtTurnoverIncl = TextBox1 - Assigning reference to the control TextBox to variable called txtTurnoverIncl

CDbl(txtTurnoverExcl.Text) - Convert the text inside the textbox txtTurnoverExcl to double i.e. numeric value with decimal point e.g. 2.6 - this is useful if you want to perform mathematical operations on the value for example.

Format(..., "#,##0.00") - Format number to look like this: 2.60 or 8.25 i.e. with two digits after decimal point.

Round(.Text * 14 / 114, 2) - The .Text means you're inside With (somecontrol) block, so it's actually somecontrol.Text i.e. taking the Text of the control. Round function will round the number for example Round(662.791, 2) will return 662.79 and Round(662.796, 2) will return 662.8

Now() - Returns the current date and time on the machine where the code is executing

Date or Date() - Like Now() but only with the date, time will be 00:00:00

Format(MyDate, "dddd") - Get name of the day of week of MyDate, according to the Culture on the machine. For example for Hebrew culture it will return יום שלישי for English culture it will return Tuesday. In general, Format() given date and string will Format the date according to the string e.g. Format(Now(), "dd/MM/yyyy") will return 14/12/2010

Title: Understanding VBScript

Body:
I have a VBScript that I`m converting to PHP, I hae some part that I don`t understand and don`t know the output of ... Also if possible, provide me with a similar method in HTML/PHP

TextBox1.Value = 1#
txtTurnoverIncl = TextBox1
Format(CDbl(txtTurnoverExcl.Text) * _
                             CDbl(txtRoyalty.Text) / 100, "#,##0.00")
If txtTurnoverExcl.Text <> "" Then
Format(Round(.Text * 14 / 114, 2), "#,##0.00")
TextBox1 = Now()
TextBox3 = Date
TextBox4 = Format(MyDate, "dddd")

And this function:

Private Function SumCashUp() As Double
    Dim i As Long
    Dim tmp As Double
    For i = 10 To 12
        With Me.Controls("TextBox" & i)
            If IsNumeric(.Text) Then
                tmp = tmp + CDbl(.Text)
            End If
        End With
    Next i
    SumCashUp = tmp
End Function

I guess thats all.


问:
how would you give name to bluetooth service in android things?
I created one simple service in android things to use Bluetooth BLE.when I try to test it with NRF connect app it's visible as "unknown service".I want to give name something like "Speed Service".how would I do it?</p>

答:
```<code>private BluetoothAdapter bluetoothAdapter = null;
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

void ChangeDeviceName(){
                Log.i(LOG, "localdevicename : "+bluetoothAdapter.getName()+" localdeviceAddress : "+bluetoothAdapter.getAddress());
                bluetoothAdapter.setName("NewDeviceName");
                Log.i(LOG, "localdevicename : "+bluetoothAdapter.getName()+" localdeviceAddress : "+bluetoothAdapter.getAddress());
            }
</code>```

Reference: Change the Android bluetooth device name

Hope this case is similar and of use to you.

Body:
private BluetoothAdapter bluetoothAdapter = null;
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

void ChangeDeviceName(){
                Log.i(LOG, "localdevicename : "+bluetoothAdapter.getName()+" localdeviceAddress : "+bluetoothAdapter.getAddress());
                bluetoothAdapter.setName("NewDeviceName");
                Log.i(LOG, "localdevicename : "+bluetoothAdapter.getName()+" localdeviceAddress : "+bluetoothAdapter.getAddress());
            }

Reference: Change the Android bluetooth device name

Hope this case is similar and of use to you.


问:
What is use of "expect_file()" function in Codeception?
Hi i am new to codeception unit testing and i am using it with Yii2. I know the user of functions expect_not() and expect_that() and also know little about expect() function and uses it to check key in error array.

However I don't know the use of expect_file(). I searched little in internet but found not any good help. can anyone please give me little description about the use of this function.

答:
expect_file() is used to verify with assertions specific to file system objects. It has two parameters (one is optional).

If you call this function with a single parameter, it will be used as the Subject Under Test file name. if it is called with two parameters, will be used as a description to display if the assertion fails but if you if you call it with 0 or more than two arguments it will throw a bad method call exceptions.

You can use it like this

```<code>expect_file('filename.txt')->exists();
expect_file('filename.txt')->notExists();
</code>```

BTW expect_file() is an alternate function for verify_file().

Body:
expect_file() is used to verify with assertions specific to file system objects. It has two parameters (one is optional).

If you call this function with a single parameter, it will be used as the Subject Under Test file name. if it is called with two parameters, will be used as a description to display if the assertion fails but if you if you call it with 0 or more than two arguments it will throw a bad method call exceptions.

You can use it like this

expect_file('filename.txt')->exists();
expect_file('filename.txt')->notExists();

BTW expect_file() is an alternate function for verify_file().


问:
Get category under which product was purchased
I have this task to do, but I'm stuck on it. Client wants to get a category name product was purchased at. This info normally is not set. So at first step I'm trying to capture event checkout_cart_product_add_after and set a category for product.

So in my Observer.php I try to get current category, by:

```<code>Mage::registry('current_category')->getName()</code>```

but it appears that current_category object is not set in Mage registry. How can I add a category to a product in a different way? (Note that, product may belong to many categories, I just need the one at which it was purchased).

Regards,
ventus

答:
Keeping this data in user session is not so good idea. There is another way.
On product page I add a hidden input tag with current category id, which can be received by $product->getCategory()->getEntityId().

Second step is more difficult. Before I have added new field (attribute) to the sales_flat_quote_item and sales_flat_order_item named from_category (my custom name ;)). Now I use observer for event sales_quote_save_before and I set to Quote Item my custom attribute.

To convert quote item to order item with my custom attribute I just added to config.xml global section:

```<code>
<fieldsets>
  <sales_convert_quote_item>
    <from_category>
      <to_order_item>*</to_order_item>
    </from_category>
  </sales_convert_quote_item>
</fieldsets>
</code>```

Now I can use it on checkout.

Body:
I have this task to do, but I'm stuck on it. Client wants to get a category name product was purchased at. This info normally is not set. So at first step I'm trying to capture event checkout_cart_product_add_after and set a category for product.

So in my Observer.php I try to get current category, by:

Mage::registry('current_category')->getName()

but it appears that current_category object is not set in Mage registry. How can I add a category to a product in a different way? (Note that, product may belong to many categories, I just need the one at which it was purchased).

Regards,
ventus

Body:
Keeping this data in user session is not so good idea. There is another way.
On product page I add a hidden input tag with current category id, which can be received by $product->getCategory()->getEntityId().

Second step is more difficult. Before I have added new field (attribute) to the sales_flat_quote_item and sales_flat_order_item named from_category (my custom name ;)). Now I use observer for event sales_quote_save_before and I set to Quote Item my custom attribute.

To convert quote item to order item with my custom attribute I just added to config.xml global section:

<fieldsets>
  <sales_convert_quote_item>
    <from_category>
      <to_order_item>*</to_order_item>
    </from_category>
  </sales_convert_quote_item>
</fieldsets>

Now I can use it on checkout.


问:
Disable click button event c#
I program in Visual Studio 2013 C#.
I want to have a functionality to disable for short time a button.
I tried button.Enabled=false,  but I see that when I click it during it is disabled then the click action starts right after I get that button enabled in other place of the program.

How to clear that event or block them when button is disabled?

Best regards,
Krzysztof

答:
This is the extremely simple way that I found on the internet and it works.

Disable the button(s)

Run whatever is needed to be performed on the procedure

Run this command Application.DoEvent();. This command enqueues all the click events (as many as the user clicked) and ignore/dispose them

Enable the button(s) at the end

Good Luck

Title: Disable click button event c#


问:
return new object of same type as child object in overwritten method
I have a virtual super class with several child classes. In the following is a simple example of my situation:

```<code>(*Super class*)
class virtual super = object(self : 'self)
 method virtual generateNewOne : X
end;;

(*Child class one*)
class subOne = object(self)
 inherit super

 method subOneMethod x =
  x+2;

 method generateNewOne =
  let a = new subOne in
  a
 end;;

(*Child class two*)
class subTwo = object(self)
 inherit super

 method subTwoMethod x =
  x+3;

 method generateNewOne =
  let b = new subTwo in
  b
 end;;
</code>```

My question is:

What do i have to insert for the X as type of the generateNewOne method?

My first thought was of type self, but as far as i tried it did not work, because the new objects do not have self type but subOne or subTwo.

答:
You can't do this if you make subOne and subTwo classes, since any subclass of them would be returning the wrong type from generateNewOne. However, as long as you don't need to subclass further you can define them as plain objects:

```<code>(*Super class*)
class virtual super = object (self : 'self)
 method virtual generateNewOne : 'self
end

let rec subOne () = object (self)
 inherit super
 method subOneMethod x = x + 2
 method generateNewOne = subOne ()
end

let rec subTwo () = object (self)
 inherit super
 method subTwoMethod x = x + 3
 method generateNewOne = subTwo ()
end
</code>```

Another possibility is to use the "functional objects" syntax, so the object returns a copy of itself (possibly with some fields modified). Then generateNewOne will be correct even for subclasses, e.g.

```<code>class subTwo = object (self)
 inherit super
 method subTwoMethod x = x + 3
 method generateNewOne = {< >}
end
</code>```

Body:
I have a virtual super class with several child classes. In the following is a simple example of my situation:

(*Super class*)
class virtual super = object(self : 'self)
 method virtual generateNewOne : X
end;;

(*Child class one*)
class subOne = object(self)
 inherit super

 method subOneMethod x =
  x+2;

 method generateNewOne =
  let a = new subOne in
  a
 end;;

(*Child class two*)
class subTwo = object(self)
 inherit super

 method subTwoMethod x =
  x+3;

 method generateNewOne =
  let b = new subTwo in
  b
 end;;

My question is:

What do i have to insert for the X as type of the generateNewOne method?

My first thought was of type self, but as far as i tried it did not work, because the new objects do not have self type but subOne or subTwo.

Body:
You can't do this if you make subOne and subTwo classes, since any subclass of them would be returning the wrong type from generateNewOne. However, as long as you don't need to subclass further you can define them as plain objects:

(*Super class*)
class virtual super = object (self : 'self)
 method virtual generateNewOne : 'self
end

let rec subOne () = object (self)
 inherit super
 method subOneMethod x = x + 2
 method generateNewOne = subOne ()
end

let rec subTwo () = object (self)
 inherit super
 method subTwoMethod x = x + 3
 method generateNewOne = subTwo ()
end

Another possibility is to use the "functional objects" syntax, so the object returns a copy of itself (possibly with some fields modified). Then generateNewOne will be correct even for subclasses, e.g.

class subTwo = object (self)
 inherit super
 method subTwoMethod x = x + 3
 method generateNewOne = {< >}
end


问:
R: Optimize index-wise comparisons that depend on other vectors
I have four vectors

```<code>x, y, z, w
length(x) = length(y) = length(z) = length(w) = 5000
</code>```

and I want to do the following:

Take the vector 'w' and run through each index 'i' from 1 to 5000. For each index 'i', find the index 'j' in 'x' which is closest y[i]. Then, take that index 'j', and compare if w[i] > z[j] for all i and j(i) .... by j(i), I mean that j depends on i.

I only want to know if that's true or not, I don't want to compute the corresponding is and js.

I have fitted this procedure using a for loop, and I use which.min to find the index 'j'. This is very slow. How to optimize?

Example:

```<code>z <- c(1,2,3,4,5)
w <- c(2,3,2,5,5)
x <- c(200,300,400,500,600)
y <- c(300,300,200,500,600)
</code>```

So, based on above, we have the following 5 comparisons:

```<code>w[1] > z[2]   (because y[1] is closest to x[2])
w[2] > z[2]    (because y[2] is closest to x[2])
w[3] < z[1]    (because y[3] is closest to x[1])
</code>```

Notice that now we already know w[i] is not greater strictly than z[j], so we can stop here. Output should then be

```<code>"FALSE"
</code>```

答:
My solution does compute the j's and makes all of the comparisons.

```<code>all(w > z[apply(abs(outer(x, y, `-`)), 2, which.min)])
</code>```

depends on what you need for fast. On my machine, this took just under a second to run on an example with 5000 x values.

```<code>system.time(
     all(w > z[apply(abs(outer(x, y, `-`)), 2, which.min)]))
            user           system          elapsed
0.77000000000000 0.20000000000000 0.97000000000116
</code>```

Body:
I have four vectors

x, y, z, w
length(x) = length(y) = length(z) = length(w) = 5000

and I want to do the following:

Take the vector 'w' and run through each index 'i' from 1 to 5000. For each index 'i', find the index 'j' in 'x' which is closest y[i]. Then, take that index 'j', and compare if w[i] > z[j] for all i and j(i) .... by j(i), I mean that j depends on i.

I only want to know if that's true or not, I don't want to compute the corresponding is and js.

I have fitted this procedure using a for loop, and I use which.min to find the index 'j'. This is very slow. How to optimize?

Example:

z <- c(1,2,3,4,5)
w <- c(2,3,2,5,5)
x <- c(200,300,400,500,600)
y <- c(300,300,200,500,600)

So, based on above, we have the following 5 comparisons:

w[1] > z[2]   (because y[1] is closest to x[2])
w[2] > z[2]    (because y[2] is closest to x[2])
w[3] < z[1]    (because y[3] is closest to x[1])

Notice that now we already know w[i] is not greater strictly than z[j], so we can stop here. Output should then be

"FALSE"

Body:
My solution does compute the j's and makes all of the comparisons.

all(w > z[apply(abs(outer(x, y, `-`)), 2, which.min)])

depends on what you need for fast. On my machine, this took just under a second to run on an example with 5000 x values.

system.time(
     all(w > z[apply(abs(outer(x, y, `-`)), 2, which.min)]))
            user           system          elapsed
0.77000000000000 0.20000000000000 0.97000000000116


问:
MySQL DATE_ADD converts date to 0?
Any pointer would be appreciated! I can't spot what's wrong with the syntax, didn't find an answer on SO, so I'm posting my question here. Thanks in advance!

Here's what I tried:

```<code>mysql> select DATE_ADD(start_date, INTERVAL 2 week), DATE_ADD(end_date,
INTERVAL 2 week) from lists where id=1;
+---------------------------------------+------------------------------
-------+
| DATE_ADD(start_date, INTERVAL 2 week) | DATE_ADD(end_date, INTERVAL 2
week) |
+---------------------------------------+------------------------------
-------+
| 2017-05-28                            | 2017-06-11
|
+---------------------------------------+------------------------------
-------+
</code>```

Result looks correct. Then I tried:

```<code>mysql> update lists set start_date=DATE_ADD(start_date, INTERVAL 2 WEEK) and
end_date=DATE_ADD(end_date, INTERVAL 2 WEEK) where id=1;
ERROR 1292 (22007): Incorrect date value: '0' for column 'start_date' at row
1
</code>```

Did some research on SO, some answers point to strict mode. But in order to trigger strict mode error, the computed dates need to be 0 first, and I can't see how the above syntax could cause DATE_ADD to do that.

Just for the sake of testing, then I tried this:

```<code>mysql> update ignore lists set start_date=DATE_ADD(start_date,
INTERVAL 2 week) and end_date=DATE_ADD(end_date, INTERVAL 2 week) where
id=1;
Query OK, 1 row affected, 1 warning (0.02 sec)
</code>```

It gave this result:

```<code>mysql> select start_date, end_date from lists where id=1;
+------------+------------+
| start_date | end_date   |
+------------+------------+
| 0000-00-00 | 2017-05-28 |
+------------+------------+
</code>```

How???

Thanks again in advance.

答:
Ooops. You have and where you should have a comma.

```<code> update lists
    set start_date=DATE_ADD(start_date, INTERVAL 2 WEEK),
        end_date=DATE_ADD(end_date, INTERVAL 2 WEEK)
  where id=1;
</code>```

and is a boolean operator returning either 0 or 1. So MySQL's parser doesn't choke on it, but rather tries to evaluate it. Hence your zero.

I hate when that happens.

Title: MySQL DATE_ADD converts date to 0?

Body:
Any pointer would be appreciated! I can't spot what's wrong with the syntax, didn't find an answer on SO, so I'm posting my question here. Thanks in advance!

Here's what I tried:

mysql> select DATE_ADD(start_date, INTERVAL 2 week), DATE_ADD(end_date,
INTERVAL 2 week) from lists where id=1;
+---------------------------------------+------------------------------
-------+
| DATE_ADD(start_date, INTERVAL 2 week) | DATE_ADD(end_date, INTERVAL 2
week) |
+---------------------------------------+------------------------------
-------+
| 2017-05-28                            | 2017-06-11
|
+---------------------------------------+------------------------------
-------+

Result looks correct. Then I tried:

mysql> update lists set start_date=DATE_ADD(start_date, INTERVAL 2 WEEK) and
end_date=DATE_ADD(end_date, INTERVAL 2 WEEK) where id=1;
ERROR 1292 (22007): Incorrect date value: '0' for column 'start_date' at row
1

Did some research on SO, some answers point to strict mode. But in order to trigger strict mode error, the computed dates need to be 0 first, and I can't see how the above syntax could cause DATE_ADD to do that.

Just for the sake of testing, then I tried this:

mysql> update ignore lists set start_date=DATE_ADD(start_date,
INTERVAL 2 week) and end_date=DATE_ADD(end_date, INTERVAL 2 week) where
id=1;
Query OK, 1 row affected, 1 warning (0.02 sec)

It gave this result:

mysql> select start_date, end_date from lists where id=1;
+------------+------------+
| start_date | end_date   |
+------------+------------+
| 0000-00-00 | 2017-05-28 |
+------------+------------+

How???

Thanks again in advance.

Body:
Ooops. You have and where you should have a comma.

 update lists
    set start_date=DATE_ADD(start_date, INTERVAL 2 WEEK),
        end_date=DATE_ADD(end_date, INTERVAL 2 WEEK)
  where id=1;

and is a boolean operator returning either 0 or 1. So MySQL's parser doesn't choke on it, but rather tries to evaluate it. Hence your zero.

I hate when that happens.


问:
SQLAlchemy hybrid property not working properly
I have a geometry point column for a model, so I want to define the setter to receive lat/lng instead of the created WKTElement. Here is what my model currently looks like:

```<code>class Poi(db.Model):
    __tablename__ = 'api_pois'

    id = db.Column(db.Integer, primary_key=True, unique=True)
    name = db.Column(db.String(80), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('api_users.id'))
    creation_time = db.Column(db.DateTime, default=func.now())
    category_id = db.Column(db.Integer(), db.ForeignKey('api_poi_categories.id'))
    category = db.relationship('PoiCategory')
    geom = db.Column(Geometry('POINT', srid=4326), nullable=False)
    metadata_poi = db.Column('metadata_poi')

    def __init__(self, name, lat, lng, user_id=None, category_id=None, metadata_poi=None):
        geom_str = 'POINT({} {})'.format(lng, lat)
        self.name = name
        self.user_id = user_id
        self.category_id = category_id
        self._geom = WKTElement(geom_str, srid=4326)
        self.metadata_poi = metadata_poi

    def __repr__(self):
        return '<Poi %r %r>' % (self.id, self.name)

    def as_dict(self, route_id=None):
        sequence = None

        if route_id:
            from sintrafico.models.route import routes_pois

            result = db.session.query(routes_pois).filter_by(route_id=route_id, poi_id=self.id). \
                order_by(routes_pois.c._sequence).one_or_none()

            if result:
                sequence = result[2]

        geom = db.session.query(Poi, func.ST_X(self.geom), func.ST_Y(self.geom)).filter(Poi.id == self.id).one_or_none()

        return {
            'id': self.id,
            'name': self.name if not sequence else '%s - %s' % (sequence, self.name),
            'lat': geom[2],
            'lon': geom[1],
            'city': str(City.city_for_coord(geom[2], geom[1])),
            'sequence': sequence if sequence else None,
            'category_id': self.category_id,
            'category': self.category.name,
            'metadata': self.metadata_poi
        }

    @property
    def location(self):
        geom = db.session.query(Poi, func.ST_X(self.geom), func.ST_Y(self.geom)).filter(Poi.id == self.id).one_or_none()
        return {'lat': geom[2], 'lon': geom[1]}

    @hybrid_property
    def geom(self):
        return self._geom

    @geom.setter
    def geom(self, (lat, lng)):
        geom_str = 'POINT({} {})'.format(lng, lat)
        self._geom = WKTElement(geom_str, srid=4326)
</code>```

This code fails on the line geom = ... inside as_dict() which calls the hybrid getter because Poi object doesn't have attribute _geom. Now if I change the line to

```<code>geom = db.session.query(Poi, func.ST_X(self._geom), func.ST_Y(self._geom)).filter(Poi.id == self.id).one_or_none()
</code>```

the error persists, it is just moved to that line instead of the setter. If I change the declaration to

```<code>_geom = db.Column(Geometry('POINT', srid=4326), nullable=False)
</code>```

Then the error I get is a malformed query:

```<code>HINT:  Perhaps you meant to reference the column "api_pois.geom".
 [SQL: 'SELECT api_pois.id AS api_pois_id, api_pois.name AS api_pois_name, api_pois.user_id AS api_pois_user_id, api_pois.creation_time AS api_pois_creation_time, api_pois.category_id AS api_pois_category_id, ST_AsBinary(api_pois._geom) AS api_pois__geom, api_pois.metadata_poi AS api_pois_metadata_poi \nFROM api_pois \nWHERE api_pois.user_id = %(user_id_1)s ORDER BY api_pois.creation_time DESC'] [parameters: {'user_id_1': 1}]
</code>```

In the last line of this code:

```<code>if args['q']:
    pois = pois.filter(func.lower(Poi.name).like('%{}%'.format(args['q'].lower())))

if args['categories'] is not None and len(args['categories']) > 0:
    pois = [x for x in pois if x.category_id in args['categories']]
</code>```

How can I get it to work?

答:
Name your geom column explicitly instead of letting declarative use the attribute name:</p>

```<code>class Poi(db.Model):
    ...
    _geom = db.Column('geom', Geometry('POINT', srid=4326), nullable=False)
</code>```

Body:
I have a geometry point column for a model, so I want to define the setter to receive lat/lng instead of the created WKTElement. Here is what my model currently looks like:

class Poi(db.Model):
    __tablename__ = 'api_pois'

    id = db.Column(db.Integer, primary_key=True, unique=True)
    name = db.Column(db.String(80), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('api_users.id'))
    creation_time = db.Column(db.DateTime, default=func.now())
    category_id = db.Column(db.Integer(), db.ForeignKey('api_poi_categories.id'))
    category = db.relationship('PoiCategory')
    geom = db.Column(Geometry('POINT', srid=4326), nullable=False)
    metadata_poi = db.Column('metadata_poi')

    def __init__(self, name, lat, lng, user_id=None, category_id=None, metadata_poi=None):
        geom_str = 'POINT({} {})'.format(lng, lat)
        self.name = name
        self.user_id = user_id
        self.category_id = category_id
        self._geom = WKTElement(geom_str, srid=4326)
        self.metadata_poi = metadata_poi

    def __repr__(self):
        return '<Poi %r %r>' % (self.id, self.name)

    def as_dict(self, route_id=None):
        sequence = None

        if route_id:
            from sintrafico.models.route import routes_pois

            result = db.session.query(routes_pois).filter_by(route_id=route_id, poi_id=self.id). \
                order_by(routes_pois.c._sequence).one_or_none()

            if result:
                sequence = result[2]

        geom = db.session.query(Poi, func.ST_X(self.geom), func.ST_Y(self.geom)).filter(Poi.id == self.id).one_or_none()

        return {
            'id': self.id,
            'name': self.name if not sequence else '%s - %s' % (sequence, self.name),
            'lat': geom[2],
            'lon': geom[1],
            'city': str(City.city_for_coord(geom[2], geom[1])),
            'sequence': sequence if sequence else None,
            'category_id': self.category_id,
            'category': self.category.name,
            'metadata': self.metadata_poi
        }

    @property
    def location(self):
        geom = db.session.query(Poi, func.ST_X(self.geom), func.ST_Y(self.geom)).filter(Poi.id == self.id).one_or_none()
        return {'lat': geom[2], 'lon': geom[1]}

    @hybrid_property
    def geom(self):
        return self._geom

    @geom.setter
    def geom(self, (lat, lng)):
        geom_str = 'POINT({} {})'.format(lng, lat)
        self._geom = WKTElement(geom_str, srid=4326)

This code fails on the line geom = ... inside as_dict() which calls the hybrid getter because Poi object doesn't have attribute _geom. Now if I change the line to

geom = db.session.query(Poi, func.ST_X(self._geom), func.ST_Y(self._geom)).filter(Poi.id == self.id).one_or_none()

the error persists, it is just moved to that line instead of the setter. If I change the declaration to

_geom = db.Column(Geometry('POINT', srid=4326), nullable=False)

Then the error I get is a malformed query:

HINT:  Perhaps you meant to reference the column "api_pois.geom".
 [SQL: 'SELECT api_pois.id AS api_pois_id, api_pois.name AS api_pois_name, api_pois.user_id AS api_pois_user_id, api_pois.creation_time AS api_pois_creation_time, api_pois.category_id AS api_pois_category_id, ST_AsBinary(api_pois._geom) AS api_pois__geom, api_pois.metadata_poi AS api_pois_metadata_poi \nFROM api_pois \nWHERE api_pois.user_id = %(user_id_1)s ORDER BY api_pois.creation_time DESC'] [parameters: {'user_id_1': 1}]

In the last line of this code:

if args['q']:
    pois = pois.filter(func.lower(Poi.name).like('%{}%'.format(args['q'].lower())))

if args['categories'] is not None and len(args['categories']) > 0:
    pois = [x for x in pois if x.category_id in args['categories']]

How can I get it to work?

Body:
Name your geom column explicitly instead of letting declarative use the attribute name:

class Poi(db.Model):
    ...
    _geom = db.Column('geom', Geometry('POINT', srid=4326), nullable=False)


问:
Arrive Date Ranges VBA
First of all i'm just a beginner in VBA and I'm Stuck in the middle and couldn't find a possible way out. To be precise on my requirement, Attached below is the Snapshot of the data which i have currently. In the Date Range column i would need a date range based on the Dates available in each invoices. If a continuity breaks in the dates i would need the dates separated by comma which is shown in the sample data. Below is my piece of code which arrives only the dates and couldn't form a date range. Hope i can find my way out and would be earning something new out of this :-) Thanks!]1

```<code>Sub DD()

With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableCancelKey = False
.EnableEvents = False
End With

Sheets("Claim Lines").Select

ActiveWorkbook.Worksheets("Claim Lines").Sort.SortFields.Clear

ActiveWorkbook.Worksheets("Claim Lines").Sort.SortFields.Add Key:=Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
ActiveWorkbook.Worksheets("Claim Lines").Sort.SortFields.Add Key:=Range("D1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Claim Lines").Sort
    .SetRange ActiveSheet.UsedRange
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Range("B2").Select

Do

    If ActiveCell.Value = ActiveCell.Offset(1, 0).Value Then
        StrtRow = 2
        tmperow = ActiveSheet.UsedRange.Rows.Count
        For j = 0 To Application.WorksheetFunction.CountIf(Range("B" & StrtRow & ":B" & tmperow), ActiveCell.Value) - 1
            If j = 0 Then
                DOS = CDate(Cells(ActiveCell.Offset(0, 2).Row + j, "D").Value)
            ElseIf j = Application.WorksheetFunction.CountIf(Range("B" & StrtRow & ":B" & tmperow), ActiveCell.Value) - 1 Then
                ElseIf DOS = DOS Then
                DOS = CDate(Cells(ActiveCell.Offset(0, 2).Row + j, "D").Value)
            ElseIf j = Application.WorksheetFunction.CountIf(Range("B" & StrtRow & ":B" & tmperow), ActiveCell.Value) - 1 Then
            ElseIf DOS = DOS Then
                DOS = DOS & " & " & CDate(Cells(ActiveCell.Offset(0, 2).Row + j, "D").Value)
            Else
                DOS = DOS & ", " & CDate(Cells(ActiveCell.Row + j, "D").Value)
            End If
        Next
        Range("N" & ActiveCell.Row).Value = DOS & " to " & DOS
        DOS = ""
        Else
        Range("N" & ActiveCell.Row).Value = Range("D" & ActiveCell.Row).Value
        End If

        ActiveCell.Offset(1, 0).Select

Loop Until IsEmpty(ActiveCell.Value)

End Sub
</code>```

答:
I quickly wrote this. I am sure there can be better ways to achieve this but I could only spend this much time before I hit the sack :)

```<code>Sub Sample()
    Dim ws As Worksheet
    Dim dString As String, ss As String
    Dim lRow As Long, i As Long
    Dim sRow As Long, eRow As Long
    Dim sDate As Date, eDate As Date

    '~~> This is your worksheet which has data
    Set ws = ThisWorkbook.Worksheets("Claim Lines")

    '~~> Setting start row and end row for Col C
    sRow = 2: eRow = 2

    With ws
        '~~> Sort Col A and B on Col A first and then on Col B
        .Columns("A:B").Sort Key1:=.Range("A1"), Key2:=.Range("B1"), _
        Order1:=xlAscending, Header:=xlYes, OrderCustom:=1, MatchCase:=False, _
        Orientation:=xlTopToBottom, DataOption1:=xlSortNormal

        '~~> Find Last Row of Col A
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Set the Initial Start Date and End Date
        sDate = .Range("B2").Value: eDate = .Range("B2").Value

        '~~> Loop through the data
        For i = 2 To lRow
            '~~> Check if the value of the current cell in Col A
            '~~> is the same as the value in the next cell
            If .Range("A" & i) = .Range("A" & i + 1) Then
                '~~> Compare date values in Col B to check if they are in sequence
                If .Range("B" & i + 1) - .Range("B" & i) = 1 Then
                    '~~> If yes then set it as new End Date
                    eDate = .Range("B" & i + 1)
                Else
                    '~~> Get the string to be written in Col C
                    dString = GetDString(dString, sDate, eDate, .Range("B" & i))
                    '~~> Set New Start Date
                    sDate = .Range("B" & i + 1)
                End If
            Else
                eRow = i
                dString = GetDString(dString, sDate, eDate, .Range("B" & i))
                .Range("C" & sRow & ":C" & eRow).Value = dString
                dString = "": sRow = eRow + 1
                sDate = .Range("B" & i + 1).Value
                eDate = .Range("B" & i + 1).Value
            End If
        Next i
    End With
End Sub

'~~> Function to get the string to be written in Col C
Private Function GetDString(s As String, StartDate As Date, _
endDate As Date, CurCell As Range) As String
    If s = "" Then
        If endDate = CurCell.Value Then
            If StartDate = endDate Then
                s = StartDate
            Else
                s = StartDate & "-" & endDate
            End If
        Else
            s = (StartDate & "-" & endDate) & "," & CurCell.Value
        End If
    Else
        If endDate = CurCell.Value Then
            s = s & "," & StartDate & "-" & endDate
        Else
            s = s & "," & CurCell.Value
        End If
    End If
    GetDString = s
End Function
</code>```

ScreenShot of various tests

Title: Arrive Date Ranges VBA

Body:
First of all i'm just a beginner in VBA and I'm Stuck in the middle and couldn't find a possible way out. To be precise on my requirement, Attached below is the Snapshot of the data which i have currently. In the Date Range column i would need a date range based on the Dates available in each invoices. If a continuity breaks in the dates i would need the dates separated by comma which is shown in the sample data. Below is my piece of code which arrives only the dates and couldn't form a date range. Hope i can find my way out and would be earning something new out of this :-) Thanks!]1

Sub DD()

With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableCancelKey = False
.EnableEvents = False
End With

Sheets("Claim Lines").Select

ActiveWorkbook.Worksheets("Claim Lines").Sort.SortFields.Clear

ActiveWorkbook.Worksheets("Claim Lines").Sort.SortFields.Add Key:=Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
ActiveWorkbook.Worksheets("Claim Lines").Sort.SortFields.Add Key:=Range("D1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Claim Lines").Sort
    .SetRange ActiveSheet.UsedRange
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Range("B2").Select

Do

    If ActiveCell.Value = ActiveCell.Offset(1, 0).Value Then
        StrtRow = 2
        tmperow = ActiveSheet.UsedRange.Rows.Count
        For j = 0 To Application.WorksheetFunction.CountIf(Range("B" & StrtRow & ":B" & tmperow), ActiveCell.Value) - 1
            If j = 0 Then
                DOS = CDate(Cells(ActiveCell.Offset(0, 2).Row + j, "D").Value)
            ElseIf j = Application.WorksheetFunction.CountIf(Range("B" & StrtRow & ":B" & tmperow), ActiveCell.Value) - 1 Then
                ElseIf DOS = DOS Then
                DOS = CDate(Cells(ActiveCell.Offset(0, 2).Row + j, "D").Value)
            ElseIf j = Application.WorksheetFunction.CountIf(Range("B" & StrtRow & ":B" & tmperow), ActiveCell.Value) - 1 Then
            ElseIf DOS = DOS Then
                DOS = DOS & " & " & CDate(Cells(ActiveCell.Offset(0, 2).Row + j, "D").Value)
            Else
                DOS = DOS & ", " & CDate(Cells(ActiveCell.Row + j, "D").Value)
            End If
        Next
        Range("N" & ActiveCell.Row).Value = DOS & " to " & DOS
        DOS = ""
        Else
        Range("N" & ActiveCell.Row).Value = Range("D" & ActiveCell.Row).Value
        End If

        ActiveCell.Offset(1, 0).Select

Loop Until IsEmpty(ActiveCell.Value)

End Sub

Body:
I quickly wrote this. I am sure there can be better ways to achieve this but I could only spend this much time before I hit the sack :)

Sub Sample()
    Dim ws As Worksheet
    Dim dString As String, ss As String
    Dim lRow As Long, i As Long
    Dim sRow As Long, eRow As Long
    Dim sDate As Date, eDate As Date

    '~~> This is your worksheet which has data
    Set ws = ThisWorkbook.Worksheets("Claim Lines")

    '~~> Setting start row and end row for Col C
    sRow = 2: eRow = 2

    With ws
        '~~> Sort Col A and B on Col A first and then on Col B
        .Columns("A:B").Sort Key1:=.Range("A1"), Key2:=.Range("B1"), _
        Order1:=xlAscending, Header:=xlYes, OrderCustom:=1, MatchCase:=False, _
        Orientation:=xlTopToBottom, DataOption1:=xlSortNormal

        '~~> Find Last Row of Col A
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Set the Initial Start Date and End Date
        sDate = .Range("B2").Value: eDate = .Range("B2").Value

        '~~> Loop through the data
        For i = 2 To lRow
            '~~> Check if the value of the current cell in Col A
            '~~> is the same as the value in the next cell
            If .Range("A" & i) = .Range("A" & i + 1) Then
                '~~> Compare date values in Col B to check if they are in sequence
                If .Range("B" & i + 1) - .Range("B" & i) = 1 Then
                    '~~> If yes then set it as new End Date
                    eDate = .Range("B" & i + 1)
                Else
                    '~~> Get the string to be written in Col C
                    dString = GetDString(dString, sDate, eDate, .Range("B" & i))
                    '~~> Set New Start Date
                    sDate = .Range("B" & i + 1)
                End If
            Else
                eRow = i
                dString = GetDString(dString, sDate, eDate, .Range("B" & i))
                .Range("C" & sRow & ":C" & eRow).Value = dString
                dString = "": sRow = eRow + 1
                sDate = .Range("B" & i + 1).Value
                eDate = .Range("B" & i + 1).Value
            End If
        Next i
    End With
End Sub

'~~> Function to get the string to be written in Col C
Private Function GetDString(s As String, StartDate As Date, _
endDate As Date, CurCell As Range) As String
    If s = "" Then
        If endDate = CurCell.Value Then
            If StartDate = endDate Then
                s = StartDate
            Else
                s = StartDate & "-" & endDate
            End If
        Else
            s = (StartDate & "-" & endDate) & "," & CurCell.Value
        End If
    Else
        If endDate = CurCell.Value Then
            s = s & "," & StartDate & "-" & endDate
        Else
            s = s & "," & CurCell.Value
        End If
    End If
    GetDString = s
End Function

ScreenShot of various tests


问:
zxing barcode scanning fragment
I am very new to mobile development and I trying to make an android app using Xamarin(visual studio). I am trying to integrate zxing barcode scanner into my app and I have found many examples of it's integration into app but they are all using Activity. I want to use fragments instead of Activity. I tried to make my fragment and the scanning screen do come up but it is not scanning anything. Can someone please point into the right direction. Thank you.

Updated file

Here is my Fragment2.cs:

```<code>public class Fragment2 : Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
       var view = inflater.Inflate(Resource.Layout.MySettingsView, container, false);

        ImageButton scanBtn = view.FindViewById<ImageButton>(Resource.Id.btnScan);
        TextView results = view.FindViewById<TextView>(Resource.Id.results);

        scanBtn.Click += async (sender, e) =>
        {
            MobileBarcodeScanner.Initialize(Activity.Application);
            var scanner = new MobileBarcodeScanner();
            var result = await scanner.Scan();

            if (result != null)
            {
                return;
            }

            Console.WriteLine($"Scanned Barcode: {result}");
            Activity.RunOnUiThread(() =>
            {
                results.Text = result.Text;
            });
        };

        return view;
    }
}
</code>```

答:
I am changing a few things:

```<code>public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    // you don't need this you can safely remove it.
    //var ignored = base.OnCreateView (inflater, container, savedInstanceState);

    // changed this line to properly inflate the fragment's layout
    var view = inflater.Inflate (Resource.Layout.fragment2_layout, container, false);

    ImageButton scanBtn = view.FindViewById<ImageButton> (Resource.Id. btnScan);
    TextView results = view.FindViewById<TextView> (Resource.Id. Results);

    scanBtn.Click += async (sender, e) => {

        // you don not create a new instance of the Android Application
       // but get the one already created. From an activity you
      // just call `Application` but from inside a fragment you need to get
      // the fragment's activity then get the Application.

        MobileBarcodeScanner.Initialize (Activity.Application);

        var scanner = new MobileBarcodeScanner ();

        var result = await scanner.Scan ();

        // The if was inverted.
        if (result == null)
        {
            return;
        }

        Console.WriteLine ($"Scanned Barcode: {result}");

        // Using this you are sure it will run in the UI thread
        // as you will be updating an UI element.
        Activity.RunOnUiThread (() => {
            results.Text = result.Text;
        });

    };

    return view;
}
</code>```

Hope this helps!

Title: zxing barcode scanning fragment

Body:
I am very new to mobile development and I trying to make an android app using Xamarin(visual studio). I am trying to integrate zxing barcode scanner into my app and I have found many examples of it's integration into app but they are all using Activity. I want to use fragments instead of Activity. I tried to make my fragment and the scanning screen do come up but it is not scanning anything. Can someone please point into the right direction. Thank you.

Updated file

Here is my Fragment2.cs:

public class Fragment2 : Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
       var view = inflater.Inflate(Resource.Layout.MySettingsView, container, false);

        ImageButton scanBtn = view.FindViewById<ImageButton>(Resource.Id.btnScan);
        TextView results = view.FindViewById<TextView>(Resource.Id.results);

        scanBtn.Click += async (sender, e) =>
        {
            MobileBarcodeScanner.Initialize(Activity.Application);
            var scanner = new MobileBarcodeScanner();
            var result = await scanner.Scan();

            if (result != null)
            {
                return;
            }

            Console.WriteLine($"Scanned Barcode: {result}");
            Activity.RunOnUiThread(() =>
            {
                results.Text = result.Text;
            });
        };

        return view;
    }
}

Body:
I am changing a few things:

public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    // you don't need this you can safely remove it.
    //var ignored = base.OnCreateView (inflater, container, savedInstanceState);

    // changed this line to properly inflate the fragment's layout
    var view = inflater.Inflate (Resource.Layout.fragment2_layout, container, false);

    ImageButton scanBtn = view.FindViewById<ImageButton> (Resource.Id. btnScan);
    TextView results = view.FindViewById<TextView> (Resource.Id. Results);

    scanBtn.Click += async (sender, e) => {

        // you don not create a new instance of the Android Application
       // but get the one already created. From an activity you
      // just call `Application` but from inside a fragment you need to get
      // the fragment's activity then get the Application.

        MobileBarcodeScanner.Initialize (Activity.Application);

        var scanner = new MobileBarcodeScanner ();

        var result = await scanner.Scan ();

        // The if was inverted.
        if (result == null)
        {
            return;
        }

        Console.WriteLine ($"Scanned Barcode: {result}");

        // Using this you are sure it will run in the UI thread
        // as you will be updating an UI element.
        Activity.RunOnUiThread (() => {
            results.Text = result.Text;
        });

    };

    return view;
}

Hope this helps!


问:
How to replace occurrences with javascript inside delimiters?
How to replace all occurrences that are within two characters.
Example:

```<code>I love :octocat: beach and you do :joy: not like it
</code>```

Replace with a url that will be generated based on what's inside the delimiters

```<code>I love [img of octocat] beach and you do [img of joy] not like it
</code>```

Javascript needs to capture what's inside : and replace

I've tried several things without success. can anybody help me?

答:
Use String.replace with a callback function querying a map {'pattern': 'replacement'}:

let str = 'I love :octocat: beach and you do :joy: not like it';

let replacements = {
  'octocat': '[img of octocat]',
  'joy': '[img of joy]'
};

let result = str.replace(/:(\w+):/g, (match, word) => replacements[word]);
console.log(result);```

Body:
How to replace all occurrences that are within two characters.
Example:

I love :octocat: beach and you do :joy: not like it

Replace with a url that will be generated based on what's inside the delimiters

I love [img of octocat] beach and you do [img of joy] not like it

Javascript needs to capture what's inside : and replace

I've tried several things without success. can anybody help me?


问:
Get elements of a sublist in python based on indexes of a different list
I have two lists of lists.

I want to get the elements from second list of lists, based on a value from the first list of lists.

I if I have simple lists, everything go smooth, but once I have list of list, I'm missing something at the end.

Here is the code working for two lists (N = names, and V = values):

```<code>N = ['name 1', 'name 2','name 3','name 4','name 5','name 6','name 7','name 8','name 9','name 10']

V = ['val 1', 'val 2','val 3','val 4','val 5','val 6','val 7','val 8','val 9','val 10']

bool_ls = []
NN = N
for i in NN:
        if i == 'name 5':
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)

# GOOD INDEXES = GI

GI = [i for i, x in enumerate(bool_ls) if x == 'y']

# SELECT THE GOOD VALUES = "GV" FROM V

GV = [V[index] for index in GI]
</code>```

if I define a function, works well applied to the two lists:

```<code>def GV(N,V,name):
    bool_ls = []
    NN = N
    for i in NN:
        if i == name:
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)
    GI = [i for i, x in enumerate(bool_ls) if x == 'y']
    GV = [V[index] for index in GI]

    return GV
</code>```

Once I try "list of list", I cannot get the similar results. My code looks like below so far:

```<code>NN = [['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3']]

VV = [['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3']]

def GV(NN,VV,name):
    bool_ls = []
    NNN = NN
    for j in NNN:
        for i in j:
            if i == name:
                i = 'y'
            else:
                i = 'n'
            bool_ls.append(i)

# here is where I'm lost
</code>```

Help greatly appreciated! Thank you.

答:
You can generate pair-wise combinations from both list using zip and then filter in a list comprehension.

For the flat lists:

```<code>def GV(N, V, name):
    return [j for i, j in zip(N, V) if i==name]
</code>```

For the nested lists, you'll add an extra nesting:

```<code>def GV(NN,VV,name):
    return [j for tup in zip(NN, VV) for i, j in zip(*tup) if i==name]
</code>```

In case you want a list of lists, you can move the nesting into new lists inside the parent comprehension.

Body:
I have two lists of lists.

I want to get the elements from second list of lists, based on a value from the first list of lists.

I if I have simple lists, everything go smooth, but once I have list of list, I'm missing something at the end.

Here is the code working for two lists (N = names, and V = values):

N = ['name 1', 'name 2','name 3','name 4','name 5','name 6','name 7','name 8','name 9','name 10']

V = ['val 1', 'val 2','val 3','val 4','val 5','val 6','val 7','val 8','val 9','val 10']

bool_ls = []
NN = N
for i in NN:
        if i == 'name 5':
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)

# GOOD INDEXES = GI

GI = [i for i, x in enumerate(bool_ls) if x == 'y']

# SELECT THE GOOD VALUES = "GV" FROM V

GV = [V[index] for index in GI]

if I define a function, works well applied to the two lists:

def GV(N,V,name):
    bool_ls = []
    NN = N
    for i in NN:
        if i == name:
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)
    GI = [i for i, x in enumerate(bool_ls) if x == 'y']
    GV = [V[index] for index in GI]

    return GV

Once I try "list of list", I cannot get the similar results. My code looks like below so far:

NN = [['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3']]

VV = [['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3']]

def GV(NN,VV,name):
    bool_ls = []
    NNN = NN
    for j in NNN:
        for i in j:
            if i == name:
                i = 'y'
            else:
                i = 'n'
            bool_ls.append(i)

# here is where I'm lost

Help greatly appreciated! Thank you.

Body:
You can generate pair-wise combinations from both list using zip and then filter in a list comprehension.

For the flat lists:

def GV(N, V, name):
    return [j for i, j in zip(N, V) if i==name]

For the nested lists, you'll add an extra nesting:

def GV(NN,VV,name):
    return [j for tup in zip(NN, VV) for i, j in zip(*tup) if i==name]

In case you want a list of lists, you can move the nesting into new lists inside the parent comprehension.


问:
How can a map be used to search the list of employe objects on the basis of different parameters?
I was asked this question in an interview today to which I explained the best to my abilities. But I still don't understand if this is the correct answer.

There is a cache which has Employee object as the key. The cache is populated with data from the database. Now there is a UI where we can enter either or all of the 3 attributes from the Employee object- name, ID and date of joining. Now this search would lead to multiple matching results.  To achieve this we need to check in the cache for the data.

To this I replied saying that my map would be of the structure - >. for the same EmployeeDetails object ,
 I will have multiple keys in the map(EmployeeDetails class is the object which contains complete detail of the Employee including address etc. Employee object just has 3 attributes - name, ID and date of joining.).

One of the objects with only name populated. The other with ID populated and the third one with date of joining populated. And now with the combination of attributes. So the map will be having the following keys -
Employee object with only the name populated -> Value would be list of of all the Employee objects with the same name.
Employee object with only the ID populated ->  Value would be list of of all the Employee objects with the same ID. Ideally the list size in this case should be 1.
Employee objects with only the Date Of Joining -> List of all the employee objects with the same date of joining.

Similarly there would be number of other Employee objects. For one such employee , all the three attributes - name , ID and date of joining would be populated.

In this way, I could have achieved the requirement to display all the employee results in case only some of the attributes out of name, ID and value is set on the UI.

I just want to understand if this is the correct way to achieve the outcome (display of list of matching results on the UI). Since I did not get selected, I believe there is something else which I possibly missed!

答:
One way is create mapping with mapping Employee-EmployeeDetails then for search for a given employee id then you have to iterate over all key and search.The complexity will be O(N).

Second to improve the time complexity even in database we do indexing to avoid full scan.You can try  the similar thing here i.e create mapping id-Employee,email-Employee like this when add employee to main map also update to the index map.

Third if possible you can create a TRIE and at end node you can put employee.After getting the employee You can get employee details


问:
Scaling :hover effect isn't working in css on

Short and simple, I'm trying to use a hover effect, and I can't seem to get it to work within this DIV at the moment and I've never came across this problem and I can't find out where I went wrong.

.navbar {
      border: solid 0px; background-color: #E6E6E6; padding-top: 15px; padding-
      bottom: 15px;
      position: absolute; top: 230px; left: 320px;
      font-family: sans-serif;
      }
     .shopping,
     .food,
     .hotels,
     .entertainment,
     .guide {
      display: inline;
      padding-right: 90px;
      padding-left: 90px;
      }
      .shopping:hover,
      .food:hover,
      .hotels:hover,
      .entertainment:hover,
      .guide:hover {
       color: yellow;
       -webkit-transform: scale(1.3);
       -ms-transform: scale(1.3);
       transform: scale(1.3);
       }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="navbar">
      <p class="shopping">Shopping</p>
      <p class="food">href="food.html">Food</p>
      <p class="hotels">href="hotels.html">Hotels</p>
      <p class="entertainment">href="entertainment.html">Entertainment</p>
      <p class="guide">href="guide.html">The total NOLA guide.</p>
     </div>
     </code>```

The weird part is that the color yellow ends up being shown but the hover that I want the scaling portion is not working and I can't figure it out.

答:
I think your approach is wrong. You can use font-size: to achive the same goal.

p:hover {
  font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Shopping</p></code>```

Using scale on HTML text messes things up sometimes, and it's best not to use it for text.

Using your code, this would be:

.navbar {
  border: solid 0px;
  background-color: #E6E6E6;
  padding-top: 15px;
  padding-bottom: 15px;
  position: absolute;
  top: 230px;
  left: 320px;
  font-family: sans-serif;
}
.shopping, .food, .hotels, .entertainment, .guide {
  padding-right: 90px;
  padding-left: 90px;
  height: 20px;
}
.grow:hover > a {
  color: yellow;
  font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <div class="navbar">
    <div class="shopping grow">Shopping</div>
    <div class="food grow">Food</div>
    <div class="hotels grow">Hotels</div>
    <div class="entertainment grow">Entertainment</div>
    <div class="guide grow">The total NOLA guide.</div>
  </div>
</body>
</html></code>```

Title: Scaling :hover effect isn't working in css on <p>

Body:
Short and simple, I'm trying to use a hover effect, and I can't seem to get it to work within this DIV at the moment and I've never came across this problem and I can't find out where I went wrong.

.navbar {
      border: solid 0px; background-color: #E6E6E6; padding-top: 15px; padding-
      bottom: 15px;
      position: absolute; top: 230px; left: 320px;
      font-family: sans-serif;
      }
     .shopping,
     .food,
     .hotels,
     .entertainment,
     .guide {
      display: inline;
      padding-right: 90px;
      padding-left: 90px;
      }
      .shopping:hover,
      .food:hover,
      .hotels:hover,
      .entertainment:hover,
      .guide:hover {
       color: yellow;
       -webkit-transform: scale(1.3);
       -ms-transform: scale(1.3);
       transform: scale(1.3);
       }

Shopping

Food

Hotels

Entertainment

The total NOLA guide.

The weird part is that the color yellow ends up being shown but the hover that I want the scaling portion is not working and I can't figure it out.

Body:
I think your approach is wrong. You can use font-size: to achive the same goal.

p:hover {
  font-size: 20px;
}

<p>Shopping</p>

Using scale on HTML text messes things up sometimes, and it's best not to use it for text.

Using your code, this would be:

.navbar {
  border: solid 0px;
  background-color: #E6E6E6;
  padding-top: 15px;
  padding-bottom: 15px;
  position: absolute;
  top: 230px;
  left: 320px;
  font-family: sans-serif;
}
.shopping, .food, .hotels, .entertainment, .guide {
  padding-right: 90px;
  padding-left: 90px;
  height: 20px;
}
.grow:hover > a {
  color: yellow;
  font-size: 20px;
}

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <div class="navbar">
    <div class="shopping grow"><a href="shopping.html">Shopping</a></div>
    <div class="food grow"><a href="food.html">Food</a></div>
    <div class="hotels grow"><a href="hotels.html">Hotels</a></div>
    <div class="entertainment grow"><a href="entertainment.html">Entertainment</a></div>
    <div class="guide grow"><a href="guide.html">The total NOLA guide.</a></div>
  </div>
</body>
</html>