问:
Why is this JavaScript code not working in document ready, but does when I wrap it inside script type?
I have the following function in JavaScript:

```<code>function valueChanged(){
   if (jQuery('#home_room_type_kitchen').is(":checked")) {
      console.log('shown');jQuery('#product_section_one').show();
   } else {
      console.log('hiden');jQuery('#product_section_one').hide();
   }
}

valueChanged();
</code>```

when I put this inside an existing jQuery(document).ready(function(){}); .js file declaration, the script does not run and returns Uncaught ReferenceError: valueChanged is not defined at HTMLInputElement.onchange.

Yet when I put this inside the html file and wrap it inside , the code runs fine.

I am really confused why this is the case, and what I am missing here. I thought putting this function inside a document ready .js file would work fine?

答:
The function declaration should be outside of the ready function separately defined, then just call it inside the ready fuction, like  :

```<code><script type="text/javascript">
    jQuery(document).ready(function(){
        valueChanged();
    });

    function valueChanged(){
      if (jQuery('#home_room_type_kitchen').is(":checked")) {
        console.log('shown');jQuery('#product_section_one').show();
      } else {
        console.log('hiden');jQuery('#product_section_one').hide();
      }
    }
</script>
</code>```

Hope this helps.

Body:
I have the following function in JavaScript:

function valueChanged(){
   if (jQuery('#home_room_type_kitchen').is(":checked")) {
      console.log('shown');jQuery('#product_section_one').show();
   } else {
      console.log('hiden');jQuery('#product_section_one').hide();
   }
}

valueChanged();

when I put this inside an existing jQuery(document).ready(function(){}); .js file declaration, the script does not run and returns Uncaught ReferenceError: valueChanged is not defined at HTMLInputElement.onchange.

Yet when I put this inside the html file and wrap it inside , the code runs fine.

I am really confused why this is the case, and what I am missing here. I thought putting this function inside a document ready .js file would work fine?

Body:
The function declaration should be outside of the ready function separately defined, then just call it inside the ready fuction, like  :

<script type="text/javascript">
    jQuery(document).ready(function(){
        valueChanged();
    });

    function valueChanged(){
      if (jQuery('#home_room_type_kitchen').is(":checked")) {
        console.log('shown');jQuery('#product_section_one').show();
      } else {
        console.log('hiden');jQuery('#product_section_one').hide();
      }
    }
</script>

Hope this helps.


来源: stackexchange

问:
Multi-Line Dictionary to Single-Line Dictionary
How would you go about converting a multi-line dictionary into one dictionary?

For example, the current dictionary, if printed to the screen, is of the form:

```<code>{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
</code>```

...and so on for over 100 hundred lines. How do you convert this to the following form:

```<code>{'keyword':'value','keyword':'value','keyword':'value','keyword':'value'}
</code>```

答:
Given

```<code>dicts = [{'a':1}, {'b':2}, {'c':3, 'd':4}]
</code>```

Do

```<code>{k:v for d in dicts for (k, v) in d.items()}
</code>```

or

```<code>from itertools import chain
dict(chain(*map(dict.items, dicts)))
</code>```

resulting in

```<code>{'a': 1, 'b': 2, 'c': 3, 'd': 4}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How would you go about converting a multi-line dictionary into one dictionary?

For example, the current dictionary, if printed to the screen, is of the form:

{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}

...and so on for over 100 hundred lines. How do you convert this to the following form:

{'keyword':'value','keyword':'value','keyword':'value','keyword':'value'}

Body:
Given

dicts = [{'a':1}, {'b':2}, {'c':3, 'd':4}]

Do

{k:v for d in dicts for (k, v) in d.items()}

or

from itertools import chain
dict(chain(*map(dict.items, dicts)))

resulting in

{'a': 1, 'b': 2, 'c': 3, 'd': 4}


问:
How to send push notification from user to user?
Trying to send push notification from user-to-user, UserA is bidding on the value for an item. Scenario, UserA updates a value in the app and clicks send, and at the same time UserB gets a notification of the updated value.

```<code>       If UserB approves of the message(value) {
           UserA gets gets the notification of approval and proceeds to
      final step of buying the item.
 }  else {
sends no and UserA is updated of the denial and he sends a new value for approval
}
</code>```

A guide to accomplish the task would be greatly appreciated.

P.S using firebase as backend

答:
Since you are already using Firebase, you have it pretty easy.

This tutorial explains everything you need to do this:

https://www.raywenderlich.com/140836/firebase-tutorial-real-time-chat-2

Essentially you need to do two things:

Save data to the Firebase database. (User A)

Listen for new data being saved to the database. (User B)

Additionally, the firebase docs themselves explain this pretty well: https://firebase.google.com/docs/cloud-messaging/ios/topic-messaging

Body:
Trying to send push notification from user-to-user, UserA is bidding on the value for an item. Scenario, UserA updates a value in the app and clicks send, and at the same time UserB gets a notification of the updated value.

       If UserB approves of the message(value) {
           UserA gets gets the notification of approval and proceeds to
      final step of buying the item.
 }  else {
sends no and UserA is updated of the denial and he sends a new value for approval
}

A guide to accomplish the task would be greatly appreciated.

P.S using firebase as backend


问:
How to response with file stream and json object as single response of web API
Web API,
My current web API is responding JSON object with 2 properties as below.
I'd: 1, FieldName:somename

Now, need to include one FILE (.CERT) in response along with existing JSON properties.

How to accomplish this ?

[Authorize]

```<code>[Route("getfileAndProperties")]
public HttpResponseMessage GetTestFile()
{
    HttpResponseMessage result = null;
    var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.cer");

   var p = new Person() {Id=1,userField="name"};
//need to include this Person object into response along with file.
    if (!File.Exists(localFilePath))
    {
        result = Request.CreateResponse(HttpStatusCode.Gone);
    }
    else
    {
        // Serve the file to the client
        result = Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "SampleImg";
    }

    return result;
}
</code>```

答:
Found the solution using Base64String conversion of file and include into JSON response.

Thanks

Body:
Web API,
My current web API is responding JSON object with 2 properties as below.
I'd: 1, FieldName:somename

Now, need to include one FILE (.CERT) in response along with existing JSON properties.

How to accomplish this ?

[Authorize]

[Route("getfileAndProperties")]
public HttpResponseMessage GetTestFile()
{
    HttpResponseMessage result = null;
    var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.cer");

   var p = new Person() {Id=1,userField="name"};
//need to include this Person object into response along with file.
    if (!File.Exists(localFilePath))
    {
        result = Request.CreateResponse(HttpStatusCode.Gone);
    }
    else
    {
        // Serve the file to the client
        result = Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "SampleImg";
    }

    return result;
}


问:
jQuery Syntax Help
I'm looking for some help explaining exactly what this line of code does in jQuery;

```<code>myString += $(settings.mySelector,this).css('display') === 'none' ? 'closed' : 'not-closed';
</code>```

I'm unfamiliar with the syntax and some of the operators used.

答:
It means this:

```<code>if ($(settings.mySelector,this).css('display') === 'none')
{
    myString = myString + 'closed';
}
else
{
    myString = myString + 'not-closed';
}
</code>```

The strict equality operator (===) performs an equality check without allowing type-coercions.

ContentLicense: CC BY-SA 2.5

Title: jQuery Syntax Help

Body:
I'm looking for some help explaining exactly what this line of code does in jQuery;

myString += $(settings.mySelector,this).css('display') === 'none' ? 'closed' : 'not-closed';

I'm unfamiliar with the syntax and some of the operators used.

Body:
It means this:

if ($(settings.mySelector,this).css('display') === 'none')
{
    myString = myString + 'closed';
}
else
{
    myString = myString + 'not-closed';
}

The strict equality operator (===) performs an equality check without allowing type-coercions.


问:
Dropdown menu is not fully functional (bootstrap4.0)
I am trying to create a simple drop-down menu using bootstrap beta version 4.0. All I am using is the original code found in the bootstrap documentation. The code includes the necessary cdns in order for bootstrap to work. While also jquery is implemented. Can not find the reason why this is happening. Any help, please? Thanks in advance.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" href="css/font-awesome.min.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

  <title>Document</title>

      <button class="btn btn-primary dropdown-toggle" type="button" id="about-us" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">About Us</button>

        Our Story
        Our Team

        Contact Us

```

答:
You have to include Bootstrap CDN (Content Delivery Network) and you must also include jQuery.</p>

```<code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

Body:
You have to include Bootstrap CDN (Content Delivery Network) and you must also include jQuery.

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


问:
setTimeout pass parameter in for loop
I created an array. I want to send ajax request with settimeout. But I can't get parameter in settimeout. When I print console log variable i is undefined. How can I solve this problem?

Console Log result

```<code>i undefined
</code>```

Javascript Code

```<code>$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);
        $scope.params = {
            lat: $scope.lat,
            lng: $scope.lng,
            time: $scope.time,
            type: $scope.type[i]
        }
        console.log("params", $scope.params);
        return;
        $.ajax({
            type: 'post',
            url: "bz.php",
            dataType: 'json',
            async: true,
            cache: false,
            data: $scope.params,
            success: function (data) {
                if (data.response) {
                    console.log("data.response", data.response);
                    return;
                    if (!$scope.$$phase) $scope.$apply();
                } else if (data.response == null) {

                } else if (data.error) {

                }
            },
            error: function (data) {
            }
        });
    }.bind(this), i * 2000);
}
</code>```

答:
You don't need .bind(). Either use let or const instead of var...

const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (let i = 0; i < $scope.type.length; i++) {
    setTimeout(function () {
        console.log("i", i);

        // your code

    }, i * 2000);
}```
</div>
</div>
</p>

<p>or just pass <code>i</code> as an additional argument to <code>setTimeout</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);

        // your code

    }, i * 2000, i);
}</code>```

Title: setTimeout pass parameter in for loop

Body:
I created an array. I want to send ajax request with settimeout. But I can't get parameter in settimeout. When I print console log variable i is undefined. How can I solve this problem?

Console Log result

i undefined

Javascript Code

$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);
        $scope.params = {
            lat: $scope.lat,
            lng: $scope.lng,
            time: $scope.time,
            type: $scope.type[i]
        }
        console.log("params", $scope.params);
        return;
        $.ajax({
            type: 'post',
            url: "bz.php",
            dataType: 'json',
            async: true,
            cache: false,
            data: $scope.params,
            success: function (data) {
                if (data.response) {
                    console.log("data.response", data.response);
                    return;
                    if (!$scope.$$phase) $scope.$apply();
                } else if (data.response == null) {

                } else if (data.error) {

                }
            },
            error: function (data) {
            }
        });
    }.bind(this), i * 2000);
}

Body:
You don't need .bind(). Either use let or const instead of var...

const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (let i = 0; i < $scope.type.length; i++) {
    setTimeout(function () {
        console.log("i", i);

        // your code

    }, i * 2000);
}

or just pass i as an additional argument to setTimeout.

const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);

        // your code

    }, i * 2000, i);
}


问:
Suffixes being added to extra model files during save
When I execute the below code

```<code>sim_model = gensim.similarities.MatrixSimilarity(corp)
sim_model.save("sim_model.pkl")
</code>```

Instead of getting "sim_model.pkl" I get two files "sim_model.pkl.index.npy" and "sim_model.pkl" why is this behavior.

答: For larger models, a single save() can result in multiple files being written, with extra suffixes. See Why are multiple model files created in gensim word2vec? for more details.

Body:
When I execute the below code

sim_model = gensim.similarities.MatrixSimilarity(corp)
sim_model.save("sim_model.pkl")

Instead of getting "sim_model.pkl" I get two files "sim_model.pkl.index.npy" and "sim_model.pkl" why is this behavior.


答:
You can use Firebase with the cloud messaging. So UserA creates the item. UserB is interested so he would subscribe to a topic about that item.

And every time there is an update, he would get a notification. Check this https://firebase.google.com/docs/cloud-messaging/ios/topic-messaging

Title: How to send push notification from user to user?


问:
AJAX timing in IE
Chrome has its developer tools that times ajax latency, firefox has firebug, but what do you do in IE? I would have thought firebug lite, but apparently it doesn't time ajax calls (at least not in IE6). How do you do it?</p>

答: You use dynatrace ajax edition. Not only will it give you what you are looking for, it will give you an incredible amount of performance profiling data including the browsers rendering time as well as page load times, execution time of javascript etc. :)</p>

Title: AJAX timing in IE


问:
How to access request object inside Item Pipeline Scrapy
I have a item pipeline to process prices. I am having errors while processing item in this pipeline. But scrapy error doesn't tells which url produced error. Is there any way i can access the request object inside the pipeline</p>

```<code>def process_item(self, item, spider):
    """
        :param self:
        :param item:
        :param spider:
    """
    print dir(spider) # No request object here...
    quit()
    if not all(item['price']):
        raise DropItem

    item['price']['new'] = float(re.sub(
        "\D", "", item['price']['new']))
    item['price']['old'] = float(re.sub(
        "\D", "", item['price']['old']))
    try:
        item['price']['discount'] = math.ceil(
            100 - (100 * (item['price']['new'] /
                          item['price']['old'])))
    except ZeroDivisionError as e:
        print "Error in calculating discount {item} {request}".format(item=item, request=spider.request) # here I want to see the culprit url...
        raise DropItem

    return item
</code>```

答:
In your spider class, whatever class variables you define here, can be accessed within your pipeline via spider.variable_name

```<code>class MySpider(scrapy.Spider):
    name = "walmart"
    my_var = "TEST"
    my_dict = {'test': "test_val"}
</code>```

Now in your pipeline you can do spider.name, spider.my_var, spider.my_dict.

Body:
I have a item pipeline to process prices. I am having errors while processing item in this pipeline. But scrapy error doesn't tells which url produced error. Is there any way i can access the request object inside the pipeline

def process_item(self, item, spider):
    """
        :param self:
        :param item:
        :param spider:
    """
    print dir(spider) # No request object here...
    quit()
    if not all(item['price']):
        raise DropItem

    item['price']['new'] = float(re.sub(
        "\D", "", item['price']['new']))
    item['price']['old'] = float(re.sub(
        "\D", "", item['price']['old']))
    try:
        item['price']['discount'] = math.ceil(
            100 - (100 * (item['price']['new'] /
                          item['price']['old'])))
    except ZeroDivisionError as e:
        print "Error in calculating discount {item} {request}".format(item=item, request=spider.request) # here I want to see the culprit url...
        raise DropItem

    return item

Body:
In your spider class, whatever class variables you define here, can be accessed within your pipeline via spider.variable_name

class MySpider(scrapy.Spider):
    name = "walmart"
    my_var = "TEST"
    my_dict = {'test': "test_val"}

Now in your pipeline you can do spider.name, spider.my_var, spider.my_dict.


问:
Invalid default value for 'dateAdded'
I got a stupid problem with SQL that I can't fix.

```ALTER TABLE  `news`
 ADD  `dateAdded` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AUTO_INCREMENT ,
 ADD PRIMARY KEY (  `dateAdded` )
```

Error:

```<code>(#1067)Invalid default value for 'dateAdded'
</code>```

Can somebody help me?

答:
Change the type from datetime to timestamp and it will work!
I had the same issue for mysql 5.5.56-MariaDB - MariaDB Server
Hope it can help... sorry if depricated</p>

Title: Invalid default value for 'dateAdded'

Body:
I got a stupid problem with SQL that I can't fix.

ALTER TABLE  `news`
 ADD  `dateAdded` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AUTO_INCREMENT ,
 ADD PRIMARY KEY (  `dateAdded` )

Error:

(#1067)Invalid default value for 'dateAdded'

Can somebody help me?


问:
How to create case-insensitive field on Java POJO. Looking for a good design.
So I'm using GigaSpaces XAP with Hibernate plugin to load my DB table into the their grid cache, unfortunately for querying the grid they do not support directly case insensitive searches.

They offered 2 solutions:

1- Use LIKE query (same as SQL) which is slow (Wont even bother with this)

2- Create a separate property of the fields I want to have case insensitive.

So now my choices are:

1- Create an extra column in DB to have case-insensitive field (Not in this life time)

2- Create a custom data loader plugin for XAP such that the moment the data is loaded the field is stored in a "ToLower" properperty. (Supported but will leave as last resort)

I'm definitely not going with #1 and I will leave the custom data loader as a last result. So my idea is to...

```<code>class Person {
    String firstName
    String firstNameLower

    public void setFirstName(String firstName) {
        this.firstName = firstName

        this.firstNameLower = firstName.toLowerCase(...);
    }
}
</code>```

Will this work with Hibernate? As the GigaSpace dataloader uses Hibernate and my pojo is pretty much an Entity class. I'm using Hibernate XML mapping not annotations. The "ToLower" fields will not be mapped. Does Hibernate call setXXX() on all fields that are mapped or does it do some fancy code replacement under the hood and doesn't call the setXXX() methods.

I'm also thinking an annotation would be good use here but not sure how to implement them or even if it's possible for this case.

答:
For anyone interested.

Simply create a "tolower()" method of the field and add the index annotation on that and you can map your pojo to hibernate the usual way.

Body:
So I'm using GigaSpaces XAP with Hibernate plugin to load my DB table into the their grid cache, unfortunately for querying the grid they do not support directly case insensitive searches.

They offered 2 solutions:

1- Use LIKE query (same as SQL) which is slow (Wont even bother with this)

2- Create a separate property of the fields I want to have case insensitive.

So now my choices are:

1- Create an extra column in DB to have case-insensitive field (Not in this life time)

2- Create a custom data loader plugin for XAP such that the moment the data is loaded the field is stored in a "ToLower" properperty. (Supported but will leave as last resort)

I'm definitely not going with #1 and I will leave the custom data loader as a last result. So my idea is to...

class Person {
    String firstName
    String firstNameLower

    public void setFirstName(String firstName) {
        this.firstName = firstName

        this.firstNameLower = firstName.toLowerCase(...);
    }
}

Will this work with Hibernate? As the GigaSpace dataloader uses Hibernate and my pojo is pretty much an Entity class. I'm using Hibernate XML mapping not annotations. The "ToLower" fields will not be mapped. Does Hibernate call setXXX() on all fields that are mapped or does it do some fancy code replacement under the hood and doesn't call the setXXX() methods.

I'm also thinking an annotation would be good use here but not sure how to implement them or even if it's possible for this case.


问:
How to get the first numbers in a SQL string
I need to get the first number(s) in a string:

1-2-3 --> 1

45-6  --> 45

777 8 --> 777

9ab10 --> 9

How can I do that with SQL?

答:
This can be achieved with a bit of string splitting and window functions, in a completely set based manner that utilises no User Defined Functions:

```<code>-- Test Data
declare @v table(v nvarchar(10));
insert into @v values('1-2-3'),('45-6'),('777 8'),('a9b10'),('abc9b10'),('123'),('abc');

            -- Create table with 10 rows in it
with t(t) as (select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1)
            -- Self join this table 6 times to cover very large string lengths (10*10*10*10*10*10 = 1,000,000 rows) and row number to get incremental list
    ,n(n) as (select top (select max(len(v)) from @v) row_number() over (order by (select null)) from t t1,t t2,t t3,t t4,t t5,t t6)
            -- Split the strings using this list of incremental numbers and use window functions to determine:
    ,v    as (select v.v
                    ,n.n
                        -- The actual character at this position
                    ,substring(v.v,n.n,1) as l
                        -- Is it numeric?
                    ,case when substring(v.v,n.n,1) like '[0-9]' then 1 else 2 end as i
                        -- Order all the numeric values
                    ,rank() over (partition by v.v order by case when substring(v.v,n.n,1) like '[0-9]' then 1 else 2 end, n.n) as c
                        -- Group the numeric rows together by summing up the numeric checks
                    ,sum(case when substring(v.v,n.n,1) like '[0-9]' then 0 else 1 end) over (partition by v.v order by n.n) as g
              from n
                  join @v as v
                      on n.n <= len(v.v)
             )
select v.v
                -- Use a FOR XML statement to concatenate the additional values together
      ,v.l + isnull((select '' + v2.l
                    from v as v2
                    where v.v = v2.v
                        and v.n < v2.n
                        and (v2.c = 1
                            or v.g = v2.g
                            )
                    for xml path('')
                    ),'') as n
from v
where c = 1     -- Only select the first grouping of numbers
    and i = 1
order by v.v;
</code>```

Output:

```<code>+---------+-----+
|    v    |  n  |
+---------+-----+
| 123     | 123 |
| 1-2-3   |   1 |
| 45-6    |  45 |
| 777 8   | 777 |
| a9b10   |   9 |
| abc9b10 |   9 |
+---------+-----+
</code>```

Body:
This can be achieved with a bit of string splitting and window functions, in a completely set based manner that utilises no User Defined Functions:

-- Test Data
declare @v table(v nvarchar(10));
insert into @v values('1-2-3'),('45-6'),('777 8'),('a9b10'),('abc9b10'),('123'),('abc');

            -- Create table with 10 rows in it
with t(t) as (select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1)
            -- Self join this table 6 times to cover very large string lengths (10*10*10*10*10*10 = 1,000,000 rows) and row number to get incremental list
    ,n(n) as (select top (select max(len(v)) from @v) row_number() over (order by (select null)) from t t1,t t2,t t3,t t4,t t5,t t6)
            -- Split the strings using this list of incremental numbers and use window functions to determine:
    ,v    as (select v.v
                    ,n.n
                        -- The actual character at this position
                    ,substring(v.v,n.n,1) as l
                        -- Is it numeric?
                    ,case when substring(v.v,n.n,1) like '[0-9]' then 1 else 2 end as i
                        -- Order all the numeric values
                    ,rank() over (partition by v.v order by case when substring(v.v,n.n,1) like '[0-9]' then 1 else 2 end, n.n) as c
                        -- Group the numeric rows together by summing up the numeric checks
                    ,sum(case when substring(v.v,n.n,1) like '[0-9]' then 0 else 1 end) over (partition by v.v order by n.n) as g
              from n
                  join @v as v
                      on n.n <= len(v.v)
             )
select v.v
                -- Use a FOR XML statement to concatenate the additional values together
      ,v.l + isnull((select '' + v2.l
                    from v as v2
                    where v.v = v2.v
                        and v.n < v2.n
                        and (v2.c = 1
                            or v.g = v2.g
                            )
                    for xml path('')
                    ),'') as n
from v
where c = 1     -- Only select the first grouping of numbers
    and i = 1
order by v.v;

Output:

+---------+-----+
|    v    |  n  |
+---------+-----+
| 123     | 123 |
| 1-2-3   |   1 |
| 45-6    |  45 |
| 777 8   | 777 |
| a9b10   |   9 |
| abc9b10 |   9 |
+---------+-----+


问:
Python - ImportError: No module Cloud Dataproc
I am having an issue with Google Cloud Dataproc with the structuring of my python project. I have a number of files which are all in the same folders and which call one another through import. The overall program runs fine locally.

However, when I place it in Google Cloud Dataproc, I have an issue with import. I have tried the answers presented in this Python can't find my module answer but to no effect.

The error is the following:

```<code>from model import PolicyEmergence
ImportError: No module named model
</code>```

I tried to force the path using sys.path.insert(0, 'gs://bucket-name/') but to no avail. I am not sure if this is due to the changing path every time I run the job.

Any help would be welcome, thanks.

答:
The from [...] import [...] requires as first argument a [directory.]file
  where your classes are and secondly a specific name of your class or * you want to import from there.

for example:

```<code>     # The .py must be omitted!
     from mymodule import *
</code>```

To import your class (PolicyEmergence) from that file (model.py) you should delete the [.py]:

```<code>from model import PolicyEmergence
</code>```

Tusr

Body:
I am having an issue with Google Cloud Dataproc with the structuring of my python project. I have a number of files which are all in the same folders and which call one another through import. The overall program runs fine locally.

However, when I place it in Google Cloud Dataproc, I have an issue with import. I have tried the answers presented in this Python can't find my module answer but to no effect.

The error is the following:

from model import PolicyEmergence
ImportError: No module named model

I tried to force the path using sys.path.insert(0, 'gs://bucket-name/') but to no avail. I am not sure if this is due to the changing path every time I run the job.

Any help would be welcome, thanks.

Body:
The from [...] import [...] requires as first argument a [directory.]file
  where your classes are and secondly a specific name of your class or * you want to import from there.

for example:

     # The .py must be omitted!
     from mymodule import *

To import your class (PolicyEmergence) from that file (model.py) you should delete the [.py]:

from model import PolicyEmergence

Tusr


问:
How to include tax in minimum order amount magento
on a french ecommerce, we always display prices including taxes.

I have enabled the minimum order amount.

I've test it, it works but the system is based on subtotal excluding taxes.
I need the system based for the this case on global amount (including taxes)
Is it possible ?

Of course I tried to work with a minimum amount excluding taxes, but I manage two tax rates. So It can't be good.

Thanks for your help.

答:
Rewrite the model Mage_Sales_Model_Quote_Address and override the method validateMinimumAmount:

```<code><?php

class StackExchange_MinimumOrderValue_Model_Quote_Address extends Mage_Sales_Model_Quote_Address
{

    /**
     * Validate minimum amount
     *
     * @return bool
     */
    public function validateMinimumAmount()
    {
        $storeId = $this->getQuote()->getStoreId();
        if (!Mage::getStoreConfigFlag('sales/minimum_order/active', $storeId)) {
            return true;
        }

        if ($this->getQuote()->getIsVirtual() && $this->getAddressType() == self::TYPE_SHIPPING) {
            return true;
        } elseif (!$this->getQuote()->getIsVirtual() && $this->getAddressType() != self::TYPE_SHIPPING) {
            return true;
        }

        $amount = Mage::getStoreConfig('sales/minimum_order/amount', $storeId);
        // $this->getBaseSubtotalInclTax() is sometimes null, so that we calculate it ourselves
        $referenceAmount = $this->getBaseSubtotal() + $this->getBaseTaxAmount() + $this->getBaseHiddenTaxAmount() - $this->getBaseShippingTaxAmount() - abs($this->getBaseDiscountAmount());
        if ($referenceAmount < $amount) {
            return false;
        }
        return true;
    }

}
</code>```

The interesting thing is that $this->getBaseSubtotalInclTax() does not work. It is sometimes null - specifically, if you proceed from the cart to the checkout page. Hence, we calculate the subtotal inclusive tax ourselves. I hope my formula is correct, but it seems to work:

```<code>$referenceAmount = $this->getBaseSubtotal() + $this->getBaseTaxAmount() + $this->getBaseHiddenTaxAmount() - $this->getBaseShippingTaxAmount() - abs($this->getBaseDiscountAmount());
</code>```

Body:
Rewrite the model Mage_Sales_Model_Quote_Address and override the method validateMinimumAmount:

<?php

class StackExchange_MinimumOrderValue_Model_Quote_Address extends Mage_Sales_Model_Quote_Address
{

    /**
     * Validate minimum amount
     *
     * @return bool
     */
    public function validateMinimumAmount()
    {
        $storeId = $this->getQuote()->getStoreId();
        if (!Mage::getStoreConfigFlag('sales/minimum_order/active', $storeId)) {
            return true;
        }

        if ($this->getQuote()->getIsVirtual() && $this->getAddressType() == self::TYPE_SHIPPING) {
            return true;
        } elseif (!$this->getQuote()->getIsVirtual() && $this->getAddressType() != self::TYPE_SHIPPING) {
            return true;
        }

        $amount = Mage::getStoreConfig('sales/minimum_order/amount', $storeId);
        // $this->getBaseSubtotalInclTax() is sometimes null, so that we calculate it ourselves
        $referenceAmount = $this->getBaseSubtotal() + $this->getBaseTaxAmount() + $this->getBaseHiddenTaxAmount() - $this->getBaseShippingTaxAmount() - abs($this->getBaseDiscountAmount());
        if ($referenceAmount < $amount) {
            return false;
        }
        return true;
    }

}

The interesting thing is that $this->getBaseSubtotalInclTax() does not work. It is sometimes null - specifically, if you proceed from the cart to the checkout page. Hence, we calculate the subtotal inclusive tax ourselves. I hope my formula is correct, but it seems to work:

$referenceAmount = $this->getBaseSubtotal() + $this->getBaseTaxAmount() + $this->getBaseHiddenTaxAmount() - $this->getBaseShippingTaxAmount() - abs($this->getBaseDiscountAmount());


问:
the data insert every-time reload the page
I created form that insert data in database but every time I reload the page the data insert again .
I use unset($_POST) to fix it but it don't fix .

How I can make it insert only one time .

```<code> <form method="post" class="job">
            <input type="text" placeholder=" course name" name="name" class="form-control input-lg">
            <input type="text" placeholder=" country " name="country" class="form-control input-lg">
            <input type="text" placeholder=" company " name="company" class="form-control input-lg">
            <input type="date" placeholder=" start " name="start" class="form-control input-lg">
            <input type="date" placeholder=" end " name="end" class="form-control input-lg">
            <input type="text" placeholder="link" name="link" class="form-control input-lg">
            <button type="submit" class="btn btn-warning btn-lg btn-block" name="addcourse" id="addcourse"> ADD COURSE </button>
</form>
</div>
<div class="col-lg-4"></div>
</div>
<?php
include("connect.php");
if (isset($_POST['addcourse'])){
        $name = $_POST["name"];
        $country = $_POST["country"];
        $company = $_POST["company"];
        $link = $_POST["link"];
        $start=$_POST["start"];
        $end=$_POST["end"];

        $newcourse="INSERT INTO courses (name,country,company,start,end,link) VALUES ('$name','$country','$company','$start','$end','$link')";
        if(!empty($name)&&!empty($country)&&!empty($company)&&!empty($link)&&!empty($start)&&!empty($end)){
        if(mysql_query($newcourse)){
            unset($_POST);
            echo "<script> alert('insert successful');  </script>";

            }
        else{ unset($_POST);
              echo "<script>alert('error');  </script>";
        }}
        else { unset($_POST);
               echo "<script>alert('fill in all field');  </script>";}
}
?>
</code>```

答:
First, I think you should understand that PHP is stateless, every time you call a script, it doesn't take into account previous actions like the unset of the POST array, which means the unset($_POST) is useless.

Your problem is that everytime you reload the page, the $_POST['addcourse'] is always set.
I would suggest changing this if (isset($_POST['addcourse'])){ with this if (!empty($_POST['name'])){ which would meant that the query would only be executed if the name field was set and the name wasn't empty.

You should also use the mysqli functions and prepared statements to prevent sql injection like in this example.

Body:
I created form that insert data in database but every time I reload the page the data insert again .
I use unset($_POST) to fix it but it don't fix .

How I can make it insert only one time .

 <form method="post" class="job">
            <input type="text" placeholder=" course name" name="name" class="form-control input-lg">
            <input type="text" placeholder=" country " name="country" class="form-control input-lg">
            <input type="text" placeholder=" company " name="company" class="form-control input-lg">
            <input type="date" placeholder=" start " name="start" class="form-control input-lg">
            <input type="date" placeholder=" end " name="end" class="form-control input-lg">
            <input type="text" placeholder="link" name="link" class="form-control input-lg">
            <button type="submit" class="btn btn-warning btn-lg btn-block" name="addcourse" id="addcourse"> ADD COURSE </button>
</form>

<?php
include("connect.php");
if (isset($_POST['addcourse'])){
        $name = $_POST["name"];
        $country = $_POST["country"];
        $company = $_POST["company"];
        $link = $_POST["link"];
        $start=$_POST["start"];
        $end=$_POST["end"];

        $newcourse="INSERT INTO courses (name,country,company,start,end,link) VALUES ('$name','$country','$company','$start','$end','$link')";
        if(!empty($name)&&!empty($country)&&!empty($company)&&!empty($link)&&!empty($start)&&!empty($end)){
        if(mysql_query($newcourse)){
            unset($_POST);
            echo "";

            }
        else{ unset($_POST);
              echo "";
        }}
        else { unset($_POST);
               echo "";}
}
?>


问:
sheets.count vs workbook activation
In the following code, the "Sheets.Count" in "Master.Activate" works only when the "Source" workbook is manually selected by mouse click before running the macro. Otherwise "Master.Activate" will activate the first worksheet of "Master" workbook instead of performing Sheets.Count and selecting the last sheet. That basically means that the macro has to be run from "Master" workbook but only after clicking on "Source" workbook. I would be grateful for any suggestions on how to fix that.

```<code>Dim Source As Worksheet
Set Source = Workbooks("Source.xlsx").Worksheets("Settlements")
Dim Master As Worksheet
Set Master = Workbooks("Master Bonviva.xlsm").Worksheets(Sheets.Count)

Source.Activate

For Each cell In Source.Columns("M").Cells
    If Not IsEmpty(cell) Then
        Master.Activate
            For Each cell2 In Master.Columns("J").Cells
                If Not IsEmpty(cell2) Then
                    If cell = cell2 Then
                        cell2.Offset(0, 9).Value = cell.Offset(0, -2).Value
                        cell2.Offset(0, 8).Value = cell.Offset(0, -8).Value
                    End If
                End If
            Next cell2
     End If
Next cell

End Sub
</code>```

Regards,
Bartek

答:
The error is in

```<code> Set Master = Workbooks("Master Bonviva.xlsm").Worksheets(Sheets.Count)
</code>```

Without qualification Sheets.count refers to the number of sheets in whichever workbook is open at the moment it is run. Replace with this

```<code>Dim wb as workbook
Set wb =Workbooks("Master Bonviva.xlsm")
Set Master = wb.worksheets(wb.sheets.count)
</code>```

Title: sheets.count vs workbook activation

Body:
In the following code, the "Sheets.Count" in "Master.Activate" works only when the "Source" workbook is manually selected by mouse click before running the macro. Otherwise "Master.Activate" will activate the first worksheet of "Master" workbook instead of performing Sheets.Count and selecting the last sheet. That basically means that the macro has to be run from "Master" workbook but only after clicking on "Source" workbook. I would be grateful for any suggestions on how to fix that.

Dim Source As Worksheet
Set Source = Workbooks("Source.xlsx").Worksheets("Settlements")
Dim Master As Worksheet
Set Master = Workbooks("Master Bonviva.xlsm").Worksheets(Sheets.Count)

Source.Activate

For Each cell In Source.Columns("M").Cells
    If Not IsEmpty(cell) Then
        Master.Activate
            For Each cell2 In Master.Columns("J").Cells
                If Not IsEmpty(cell2) Then
                    If cell = cell2 Then
                        cell2.Offset(0, 9).Value = cell.Offset(0, -2).Value
                        cell2.Offset(0, 8).Value = cell.Offset(0, -8).Value
                    End If
                End If
            Next cell2
     End If
Next cell

End Sub

Regards,
Bartek

Body:
The error is in

 Set Master = Workbooks("Master Bonviva.xlsm").Worksheets(Sheets.Count)

Without qualification Sheets.count refers to the number of sheets in whichever workbook is open at the moment it is run. Replace with this

Dim wb as workbook
Set wb =Workbooks("Master Bonviva.xlsm")
Set Master = wb.worksheets(wb.sheets.count)


问:
Dts.Pipeline.ComponentVersionMismatchException - Script Component
I'm trying to execute an SSIS package I created and deployed to SQL Server 2016, but I get the following errors when I attempt to execute it (I don't get this locally when running it via VS2015). I initially created this package using VS2017. However judging by the error message, I needed to use an older version? So I used VS2015 to open the solution and recreate the Script Component that's the source of the problem. I did this successfully, tested, rebuilt, but I'm STILL getting the same set of error messages on our PROD server after removing the old package from there, and deploying the "new" one from VS2015. I've run out of ideas. Could someone please tell me what I need to do to get the failing Script Component to execute without these errors?

Additional Info: I initially was testing these packages (via running them in Visual Studio) against our DEV database which is running SQL Server 2008, and am attempting to deploy against SQL Server 2016.

答:
Turns out it's best to deploy SSIS packages via Visual Studio 20XX as that does the proper conversions that are needed for the targeted SSIS SQL Server. The first answer at the link below is the fix I used which worked like a charm.

SSIS script task fail version 15.0 script?


问:
Using Assembly.GetEntryAssembly().Location to detect if file exists
I am trying to detect if a given file exists. For example, let's say I'm looking for Joystick.png in this directory: F:\FrontEnd\Themes\Custom\Images\Platform\Controller\Joystick.png

I cannot hard code the directory structure because the application might be installed elsewhere. the directory structure however, doesn't change.

I had been using this

```<code>string path = $"pack://siteoforigin:,,,/Themes/Custom/Images/Controls/{game.Platform}/{controller}.png";
</code>```

to send the path to an image on the wpf but I've come to leanr that I cannot pass this same variable into File.Exists. So I had to come up with an alternative.

I've  discovered this:

```<code>string exists = Assembly.GetEntryAssembly().Location;
</code>```

which gets me this result: F:\FrontEnd\FrontEnd.exe

So my question is, how do I modify the var exists so that is matches the structure of var path?

答:
You can use the different members of System.IO.Path to manipulate the path strings.

```<code>var exePath = @"F:\FrontEnd\FrontEnd.exe";
var filePath = @"/Themes/Custom/Images/Controls/{game.Platform}/{controller}.png";
var relPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(exePath),filePath);
var packPath = @"pack://siteoforigin:,,," + relPath;
</code>```

Body:
I am trying to detect if a given file exists. For example, let's say I'm looking for Joystick.png in this directory: F:\FrontEnd\Themes\Custom\Images\Platform\Controller\Joystick.png

I cannot hard code the directory structure because the application might be installed elsewhere. the directory structure however, doesn't change.

I had been using this

string path = $"pack://siteoforigin:,,,/Themes/Custom/Images/Controls/{game.Platform}/{controller}.png";

to send the path to an image on the wpf but I've come to leanr that I cannot pass this same variable into File.Exists. So I had to come up with an alternative.

I've  discovered this:

string exists = Assembly.GetEntryAssembly().Location;

which gets me this result: F:\FrontEnd\FrontEnd.exe

So my question is, how do I modify the var exists so that is matches the structure of var path?

Body:
You can use the different members of System.IO.Path to manipulate the path strings.

var exePath = @"F:\FrontEnd\FrontEnd.exe";
var filePath = @"/Themes/Custom/Images/Controls/{game.Platform}/{controller}.png";
var relPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(exePath),filePath);
var packPath = @"pack://siteoforigin:,,," + relPath;


问:
Graph Algorithm in Python
I have this example graph

```<code>graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }
</code>```

And I have this two algorithm for generating edges and finding isolated nodes:

```<code>def edges(g):
    edges = []
    for node in g[node]:
        edges.append((node, g[node]))
    return edges

def isolated(g):
    result = []
    for node in g[node]:
        if not g[node]:
            result += node
    return result
</code>```

What am I doing wrong?

答:
Here is a way to list the edges in the form of a list of tuples containing a node source and a node destination.

And a way to list the nodes with no outgoing edges:

It assumes that the adjacency lists represent the edges twice: once going out, and once going in, typical of an undirected graph.

```<code>def edges(g):
    """return a list of tuples representing an edge
    """
    edges = []
    for source in g:
        for destination in g[source]:
            edges.append((source, destination))
    return edges

def isolated_nodes(g):
    """returns a list of the nodes with no outgoing edges
    """
    disconnected_nodes = []
    for node in g:
        if len(g[node]) == 0:
            disconnected_nodes.append(node)
    return disconnected_nodes

graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }

print(edges(graph))
print(isolated_nodes(graph))
</code>```

output:

```<code>[('v1', 'v3'), ('v2', 'v3'), ('v2', 'v5'), ('v3', 'v1'), ('v3', 'v2'), ('v3', 'v4'), ('v3', 'v5'), ('v4', 'v3'), ('v5', 'v3'), ('v5', 'v2')]
['v6']
</code>```

Title: Graph Algorithm in Python

Body:
I have this example graph

graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }

And I have this two algorithm for generating edges and finding isolated nodes:

def edges(g):
    edges = []
    for node in g[node]:
        edges.append((node, g[node]))
    return edges

def isolated(g):
    result = []
    for node in g[node]:
        if not g[node]:
            result += node
    return result

What am I doing wrong?

Body:
Here is a way to list the edges in the form of a list of tuples containing a node source and a node destination.

And a way to list the nodes with no outgoing edges:

It assumes that the adjacency lists represent the edges twice: once going out, and once going in, typical of an undirected graph.

def edges(g):
    """return a list of tuples representing an edge
    """
    edges = []
    for source in g:
        for destination in g[source]:
            edges.append((source, destination))
    return edges

def isolated_nodes(g):
    """returns a list of the nodes with no outgoing edges
    """
    disconnected_nodes = []
    for node in g:
        if len(g[node]) == 0:
            disconnected_nodes.append(node)
    return disconnected_nodes

graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }

print(edges(graph))
print(isolated_nodes(graph))

output:

[('v1', 'v3'), ('v2', 'v3'), ('v2', 'v5'), ('v3', 'v1'), ('v3', 'v2'), ('v3', 'v4'), ('v3', 'v5'), ('v4', 'v3'), ('v5', 'v3'), ('v5', 'v2')]
['v6']


问:
Inherited Devise controller tweaking for admin role
I am trying to customise a Devise model (Admin) and perform a few check on login. I have then added a few fields that need to be validated before a sessions is created.

controllers and views have been generated for Admin model.

The inherited sessions controller looks like this :

```<code>class Admins::SessionsController < Devise::SessionsController
  # before_action :configure_sign_in_params, only: [:create]

  # GET /resource/sign_in
  # def new
  #   super
  # end

  # POST /resource/sign_in
  # def create
  #   super
  # end

  # DELETE /resource/sign_out
  # def destroy
  #   super
  # end

  protected

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_sign_in_params
  #   devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
  # end
end
</code>```

One of these validation is checking the currently logging admin IP address against a stored value (with dedicated field populated manually after admin creation).

I have two questions :

Let's say I modify the create method, do I still inherit every protected and private method from the original controller (here : https://github.com/plataformatec/devise/blob/master/app/controllers/devise/sessions_controller.rb )

Also is it safe to modify the create method with only super in it, and append an after_action :check_validity which will check  the IP of the newly logged in admin? Or should I hard tweak the original create method ?

答:
To answer your questions:

All of the protected methods will be inherited from the parent controller.  However, you will not be able to call the parent's private methods directly from the Admins::SessionsController.  All of the before_actions will execute normally and you will not need to replicate them in the inherited class.

I agree with MrYoshiji here.  You should probably make your ip check a before_action so that it happens before the parent's create method renders a page to the user.  However, you will not have a current_admin available until after super executes, so you will either need to find another way of identifying the admin user or you should modify the create method completely without using super.

You might also take a look at this question for a solution.

Body:
I am trying to customise a Devise model (Admin) and perform a few check on login. I have then added a few fields that need to be validated before a sessions is created.

controllers and views have been generated for Admin model.

The inherited sessions controller looks like this :

class Admins::SessionsController < Devise::SessionsController
  # before_action :configure_sign_in_params, only: [:create]

  # GET /resource/sign_in
  # def new
  #   super
  # end

  # POST /resource/sign_in
  # def create
  #   super
  # end

  # DELETE /resource/sign_out
  # def destroy
  #   super
  # end

  protected

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_sign_in_params
  #   devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
  # end
end

One of these validation is checking the currently logging admin IP address against a stored value (with dedicated field populated manually after admin creation).

I have two questions :

Let's say I modify the create method, do I still inherit every protected and private method from the original controller (here : https://github.com/plataformatec/devise/blob/master/app/controllers/devise/sessions_controller.rb )

Also is it safe to modify the create method with only super in it, and append an after_action :check_validity which will check  the IP of the newly logged in admin? Or should I hard tweak the original create method ?


问:
Sum values in R where values in column between two numbers
I'm trying to take a data.frame and aggregate the values of one column, sorted by values in other columns, and where the values in a final column are between certain criteria. In SQL I'd do a simple Group By and write a loop, but I'm just getting started in R and am having a hard time figuring out syntax. Basically I have a dataset that looks like this:

```<code>Type    Type2   Bucket  Value
   A    1       1       1
   A    2       1       2
   A    3       1       1
   A    4       1       3
   A    5       1       1
   A    1       2       1
   A    2       2       2
   A    3       2       1
   A    4       2       3
</code>```

I want the output to be something like this:

```<code>Type    Type2   Bucket  Value
A       <4      1       4
A       >=4     1       4
A       <4      2       5
A       >=4     2       3
</code>```

In my head, it's easy, but I'm coming from a SQL background, and trying to do it in R. I've messed with some functions like split and ddply with bits of success, but can't quite put it all together. Thanks.

答:
You can do this with dplyr. Assuming you have more than one Type:

```<code>library(dplyr)

df %>%
  group_by(Type, Bucket, Type2 = ifelse(Type2 < 4, "<4", ">=4")) %>%
  summarize(Value = sum(Value)) %>%
  select(Type, Type2, Bucket, Value)
</code>```

Result:

```<code># A tibble: 4 x 4
# Groups:   Type, Bucket [2]
    Type Type2 Bucket Value
  <fctr> <chr>  <int> <int>
1      A    <4      1     4
2      A   >=4      1     4
3      A    <4      2     4
4      A   >=4      2     3
</code>```

Since you mentioned you have SQL background, here is a sqldf solution for you:

```<code>library(sqldf)

sqldf("select Type,
              case when Type2 < 4 then '<4' else '>=4' end as Type_2,
              Bucket,
              sum(Value) as Value
          from df
          group by Type, Bucket, Type_2")
</code>```

Result:

```<code>  Type Type_2 Bucket Value
1    A     <4      1     4
2    A    >=4      1     4
3    A     <4      2     4
4    A    >=4      2     3
</code>```

Data:

```<code>df = structure(list(Type = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), .Label = "A", class = "factor"), Type2 = c(1L, 2L, 3L,
4L, 5L, 1L, 2L, 3L, 4L), Bucket = c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L), Value = c(1L, 2L, 1L, 3L, 1L, 1L, 2L, 1L, 3L)), .Names = c("Type",
"Type2", "Bucket", "Value"), class = "data.frame", row.names = c(NA,
-9L))
</code>```

Body:
I'm trying to take a data.frame and aggregate the values of one column, sorted by values in other columns, and where the values in a final column are between certain criteria. In SQL I'd do a simple Group By and write a loop, but I'm just getting started in R and am having a hard time figuring out syntax. Basically I have a dataset that looks like this:

Type    Type2   Bucket  Value
   A    1       1       1
   A    2       1       2
   A    3       1       1
   A    4       1       3
   A    5       1       1
   A    1       2       1
   A    2       2       2
   A    3       2       1
   A    4       2       3

I want the output to be something like this:

Type    Type2   Bucket  Value
A       <4      1       4
A       >=4     1       4
A       <4      2       5
A       >=4     2       3

In my head, it's easy, but I'm coming from a SQL background, and trying to do it in R. I've messed with some functions like split and ddply with bits of success, but can't quite put it all together. Thanks.

Body:
You can do this with dplyr. Assuming you have more than one Type:

library(dplyr)

df %>%
  group_by(Type, Bucket, Type2 = ifelse(Type2 < 4, "<4", ">=4")) %>%
  summarize(Value = sum(Value)) %>%
  select(Type, Type2, Bucket, Value)

Result:

# A tibble: 4 x 4
# Groups:   Type, Bucket [2]
    Type Type2 Bucket Value
  <fctr> <chr>  <int> <int>
1      A    <4      1     4
2      A   >=4      1     4
3      A    <4      2     4
4      A   >=4      2     3

Since you mentioned you have SQL background, here is a sqldf solution for you:

library(sqldf)

sqldf("select Type,
              case when Type2 < 4 then '<4' else '>=4' end as Type_2,
              Bucket,
              sum(Value) as Value
          from df
          group by Type, Bucket, Type_2")

Result:

  Type Type_2 Bucket Value
1    A     <4      1     4
2    A    >=4      1     4
3    A     <4      2     4
4    A    >=4      2     3

Data:

df = structure(list(Type = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), .Label = "A", class = "factor"), Type2 = c(1L, 2L, 3L,
4L, 5L, 1L, 2L, 3L, 4L), Bucket = c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L), Value = c(1L, 2L, 1L, 3L, 1L, 1L, 2L, 1L, 3L)), .Names = c("Type",
"Type2", "Bucket", "Value"), class = "data.frame", row.names = c(NA,
-9L))


问:
Multiplying by a number in a for loop
```<code>d = 2;
for x = [1:10]
    x
    d = ((2/d)*(sqrt(d^2+4)-2))
    d*(2^(x+1))
end
</code>```

produces a sequence which tends to pi BUT,

```<code>d = 2;
for x = [1:10]
    x
    d = ((2/d)*(sqrt(d^2+4)-2)) * (2^(x+1))
end
</code>```

does not. This gives a sequence (I've rounded a bit) : 3 , 9 , 25 , ... , 4E3

What is going on? To me those lines look exactly the same.

答:
The difference between these two is that for the first one, you multiply by d

```<code>d*(2^(x+1))
</code>```

And every time it does a loop, the value of d is changed because of your whole equation. For the second code,
  (2^(x+1))
you multiply by a constant 2 instead, which doesn't change every loop.

So  d*(2^(x+1)) depends on d and x, but (2^(x+1)) only depends on x.

Title: Multiplying by a number in a for loop

Body:
d = 2;
for x = [1:10]
    x
    d = ((2/d)*(sqrt(d^2+4)-2))
    d*(2^(x+1))
end

produces a sequence which tends to pi BUT,

d = 2;
for x = [1:10]
    x
    d = ((2/d)*(sqrt(d^2+4)-2)) * (2^(x+1))
end

does not. This gives a sequence (I've rounded a bit) : 3 , 9 , 25 , ... , 4E3

What is going on? To me those lines look exactly the same.

Body:
The difference between these two is that for the first one, you multiply by d

d*(2^(x+1))

And every time it does a loop, the value of d is changed because of your whole equation. For the second code,
  (2^(x+1))
you multiply by a constant 2 instead, which doesn't change every loop.

So  d*(2^(x+1)) depends on d and x, but (2^(x+1)) only depends on x.


问:
Storing Windows passwords
I'm writing (in C# with .NET 3.5) an administrative application which will poll multiple Windows systems for various bits of data. In many cases it will use WMI, but in some cases it may need to read remote registry or remotely execute some command or script on the polled system. This polling will happen at repeating intervals - usually nightly, but can be configured to happen more (or less) frequently. So the poll could happen as often as every 10 minutes or as rarely as once a month. It needs to happen in an automated way, without any human intervention.

These functions will require admin-level access to the polled systems. Now, I expect that in most use cases, there will be a domain, and the polling application can run as a service with Domain Admin (or equivalent) privileges, which means I do not have to worry about storing passwords - the admin setting up the app will define the service's username/password via standard Windows mechanisms.

But there's always a few black sheep out there. The program may run in nondomain environments, or in cases where some polled systems are not members of the domain. In these cases we will have to define a username and password, store them securely, then invoke this user/pass pair at the time we poll that system. So keep in mind - in this case the program being written is the user who sends password to the authenticating system.

I am not sure whether I will need to use a reversible hash which I then decrypt to plaintext at time of use, or if there is some Windows mechanism which would allow me to store and then reuse the hash only. Obviously the second mechanism is preferable; I'd like my program to either never know the password's plaintext value, or know it for the shortest amount of time possible.

I need suggestions for smart and secure ways to accomplish this.

Thanks for looking!

答: Well it seems that your program needs to impersonate a user other than the context under which it is already running. Although, it does look like a pretty automated process, but if it's not, can you simply not ask the administrator to put in username and password at the time this 'black-sheep' computer is being polled?</p>

OwnerDisplayName: quux

Title: Storing Windows passwords

LastEditorDisplayName: quux

OwnerDisplayName: Vaibhav


问:
C++ Vector Magnitude
I have been tasked with making a vector magnitude function in C++ as part of a maths library for a class project, however I am unsure how to go about this, if someone could recommend some pages to read and or give me some help that would be great

Edit: My C++ knowledge isn't that great, I'm looking for pages to help me learn how to do functions for vectors

答:
Take a revisit to GCSE maths:</p>

```<code>c² = a² + b²

double magnitude = sqrt((Vector.x*Vector.x) + (Vector.y*Vector.y));
</code>```

Title: C++ Vector Magnitude

Body:
Take a revisit to GCSE maths:

c² = a² + b²

double magnitude = sqrt((Vector.x*Vector.x) + (Vector.y*Vector.y));


问:
How to create a VBA function to find the max of each row in an array
I want to create a customised function to find the max value of each "row" in an array. For example, I have a sample 5x3 dimensions array as below:

```<code>[ 0     0      0
  0     1      1
  1     0      1
  1     1      1
  0     0      0]
</code>```

And I want to get the max value of each row which should come in the form of:
    [0
    1
    1
    1
    0]

Please note that this is just one example. I'm facing quite a number of matrices which require this task. I did some research online but couldn't find an easy solution for this. There is one which I found requires output into the spreadsheet before finding the max values (the outputting into spreadsheet is not preferred though). This code is below:

```<code>Function Max_Each_Row(Data_Range As Range) As Variant
    Dim TempArray() As Double, i As Long
    If Data_Range Is Nothing Then Exit Function
    With Data_Range
    ReDim TempArray(1 To .Rows.count)
    For i = 1 To .Rows.count
        TempArray(i) = Application.Max(.Rows(i))
    Next
    End With
    Max_Each_Row = TempArray
End Function
</code>```

Could someone point me to the right direction? i.e. creating a function () to find the desired array with the max value in each row, without outputting anything into the spreadsheet.

Thanks for your help!

答:
Try this it will work fine

```<code> Option Explicit
    Option Base 1
    'by jlqmoreno@gmail.com
    Public Function MAX_IN_EACH_ROW(Rango As Object) As Variant
     Dim n%, i%, j%, MR() As Variant
      n = Rango.Rows.Count
       ReDim MR(n)
       For i = 1 To n Step 1
            MR(i) = Application.Max(Application.Index(Rango, i, 0)) '#In here I am slicing the original range into rows
       Next i
         MAX_IN_EACH_ROW = MR
    End Function
</code>```

Hope it helps

Body:
I want to create a customised function to find the max value of each "row" in an array. For example, I have a sample 5x3 dimensions array as below:

[ 0     0      0
  0     1      1
  1     0      1
  1     1      1
  0     0      0]

And I want to get the max value of each row which should come in the form of:
    [0
    1
    1
    1
    0]

Please note that this is just one example. I'm facing quite a number of matrices which require this task. I did some research online but couldn't find an easy solution for this. There is one which I found requires output into the spreadsheet before finding the max values (the outputting into spreadsheet is not preferred though). This code is below:

Function Max_Each_Row(Data_Range As Range) As Variant
    Dim TempArray() As Double, i As Long
    If Data_Range Is Nothing Then Exit Function
    With Data_Range
    ReDim TempArray(1 To .Rows.count)
    For i = 1 To .Rows.count
        TempArray(i) = Application.Max(.Rows(i))
    Next
    End With
    Max_Each_Row = TempArray
End Function

Could someone point me to the right direction? i.e. creating a function () to find the desired array with the max value in each row, without outputting anything into the spreadsheet.

Thanks for your help!

Body:
Try this it will work fine

 Option Explicit
    Option Base 1
    'by jlqmoreno@gmail.com
    Public Function MAX_IN_EACH_ROW(Rango As Object) As Variant
     Dim n%, i%, j%, MR() As Variant
      n = Rango.Rows.Count
       ReDim MR(n)
       For i = 1 To n Step 1
            MR(i) = Application.Max(Application.Index(Rango, i, 0)) '#In here I am slicing the original range into rows
       Next i
         MAX_IN_EACH_ROW = MR
    End Function

Hope it helps


问:
Display informational message to user when installation finished for install Shield Suite project
I have created setup.exe using  install Shield Suite project. I want to display informational message to user when installation finished i.e when user clicks on finish.<img src="https://i.stack.imgur.com/d13Vl.png" alt="enter image description here"> How to achieve this? </p>

答:
There are few way to achieve this. For Basic MSI project, probably the simplest way is to add Custom Action (CA) which will display the dialog with information you want to show. This CA may also launch for example "Notepad" to display text or some other application. After call this CA on click of the "Finish" button. To attach your CA to this event use IDE to go to the following path ...

User Interface "Dialogs" -> SetupCompleteSuccess "Behavior" -> OK Push Button "DoAction"

Inside DoAction pick the CA you've created, add conditions if needed. Other than DoAction you may also choose to SpawnDialog which will gives you new modal dialog (Displaying Dialogs During Basic MSI Installations).

The note from myself: I don't believe this is all good idea. As the user I would expect the setup wizard to quit when I press "Finish" button. Users (including myself) don't like any popups or even worth, additional dialogs after finishing installation. On other hand, probably this is your requirements and this is what you want to do.

Body: I have created setup.exe using  install Shield Suite project. I want to display informational message to user when installation finished i.e when user clicks on finish. How to achieve this?


问:
Webpack failed to compile, trying to integrate a searchbox component
I'm trying to integrate react-search-box to an existing project but when starting I get:

```<code>ERROR in ./~/react-search-box/dist/styles.css
Module parse failed: C:\Users\User\gitcvs\project1\node_modules\react-search-box\dist\styles.css Unexpected token (3:0)
You may need an appropriate loader to handle this file type.
</code>```

This is my webpack.config

```<code>module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './',
    port: 8078
  }
};
</code>```

Searching on the web seems to indicate I need to add a css loader in webpack? Not sure how to do that.

答:
you must install via npm css-loader and style-loader, then add his rule to your weback.config.js under module.rules field

```<code>module.exports: {
    module: {
        rules: [
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            }
        ]
    }
}
</code>```

Body:
I'm trying to integrate react-search-box to an existing project but when starting I get:

ERROR in ./~/react-search-box/dist/styles.css
Module parse failed: C:\Users\User\gitcvs\project1\node_modules\react-search-box\dist\styles.css Unexpected token (3:0)
You may need an appropriate loader to handle this file type.

This is my webpack.config

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './',
    port: 8078
  }
};

Searching on the web seems to indicate I need to add a css loader in webpack? Not sure how to do that.

Body:
you must install via npm css-loader and style-loader, then add his rule to your weback.config.js under module.rules field

module.exports: {
    module: {
        rules: [
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            }
        ]
    }
}


问:
Is it possible to add border and background to post grids? [Wordpress]
I would like to add some border and background to my post grids to which they will be fit to my website look. Is that possible? The default one is;

Default

And
I want to make like this

Thanks!

My website is; BattlegroundsTurkiye.com

答:
Test this :)</p>

```<code>.post{border : 1px red solid}
</code>```

Body:
Test this :)

.post{border : 1px red solid}


问:
Dropdown menu is not fully functional (bootstrap4.0)
I am trying to create a simple drop-down menu using bootstrap beta version 4.0. All I am using is the original code found in the bootstrap documentation. The code includes the necessary cdns in order for bootstrap to work. While also jquery is implemented. Can not find the reason why this is happening. Any help, please? Thanks in advance.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" href="css/font-awesome.min.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

  <title>Document</title>

      <button class="btn btn-primary dropdown-toggle" type="button" id="about-us" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">About Us</button>

        Our Story
        Our Team

        Contact Us

```

答:
You should include neceesry CDN s as in Bootstrap 4 document

```<code><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</code>```

and bootstrap 4 CSS

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

  <link rel="stylesheet" href="css/font-awesome.min.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

  <title>Document</title>

      <button class="btn btn-primary dropdown-toggle" type="button" id="about-us" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">About Us</button>

        Our Story
        Our Team

        Contact Us

```

Body:
You should include neceesry CDN s as in Bootstrap 4 document

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

and bootstrap 4 CSS

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

  <!--Fontawsome-->
  <link rel="stylesheet" href="css/font-awesome.min.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

  <title>Document</title>
</head>

<body>

  <header>
    <div class="dropdown">
      <button class="btn btn-primary dropdown-toggle" type="button" id="about-us" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">About Us</button>
      <div class="dropdown-menu" aria-labelledby="about-us">
        <a class="dropdown-item" href="#">Our Story</a>
        <a class="dropdown-item" href="#">Our Team</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">Contact Us</a>
      </div>
    </div>
  </header>
  <!--Jquery-->

  <script src="js/jquery-3.2.1.min.js"></script>
  <!--Bootstrap Script-->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

  <!-- Mod Script -->

</body>

</html>


问:
Add images into string? Translate word into image
I want to create a program that let you input a sentence such as:
I am happy.
And outputs: I am  (happy emoji, in my case an image I've created myself).

So far I am able to replace happy by another word but I need to replace it with an image.
Can I add images to a string?
If so, how?

UPDATE: My code finally works, this is the html and javascript I've used:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Parse emotional expressions with emoticions.</title>
     <style>
      .inline-img {
          height: 40px;
        }
    </style>
     </head>
      <body>
        <font size="+3" face="Helvetica">
       <p id="output"></p>
     </font>
         <script>
         document.addEventListener('DOMContentLoaded', function() {
         function word_replace(replacements, str) {
           var result = str;
            for (var [x, url] of replacements) {
             result = result.replace(x, '<img src="' + url + '" alt="emoji" class="inline-img" />');
                    }
          return result;
          }
            var input = prompt('Input your sentence');
            var output = word_replace([

            [/(happy)/ig, 'https://c1.staticflickr.com/5/4521/38517798662_418a72e9d9_b.jpg'],
            [/(sad|depressed)/ig, 'https://c1.staticflickr.com/5/4553/38517797352_6c8fba1a3d_o.png'],
            [/(confused)/ig, "https://c1.staticflickr.com/5/4519/37833334134_109952bda2_b.jpg"],
            [/(afraid)/ig, 'https://c1.staticflickr.com/5/4516/37833334324_c43f01a30d_b.jpg'],
            [/(angry)/ig, 'https://c1.staticflickr.com/5/4532/26773555349_63894fa4be_b.jpg'],
            [/(determined)/ig, 'https://c1.staticflickr.com/5/4537/37833333874_ff92cb8647_b.jpg'],
            [/(love)/ig, 'https://c1.staticflickr.com/5/4530/37833331724_8a90312ddb_b.jpg'],
            [/(indifferent)/ig, 'https://c1.staticflickr.com/5/4543/37833333744_59da46444d_b.jpg']

          ], input);

          var outputElement = document.getElementById("output");
          outputElement.innerHTML = output;
      });

    </script>
  </body>
</html>
</code>```

答:
If your intention is to simply have the text displayed as HTML somewhere a simple modification to your replacement function will insert a  tag to the text.

This way all you need to do is provide a link to your images.

I changed your regex to include parenthesis in order to use the capture groups for the alt text of the  tags.

I also used a class to limit the height of the images with css.

function mreplace(replacements, str) {
  let result = str;
  for (let [x, y] of replacements) {
    result = result.replace(x, '');
  }
  return result;
}

let input = prompt('Input your sentence');
let output = mreplace([
  [/(happy)/ig, 'https://icon-icons.com/icons2/860/PNG/512/happy_icon-icons.com_67810.png'],
  [/(sad)/ig, 'https://images.vexels.com/media/users/17482/106930/raw/fcba42ccb55e21d86c6cc25078f0431e-cute-and-sad-icon-vector.png'],
  [/(confused)/ig, "http://i0.kym-cdn.com/photos/images/original/001/157/196/bcf.gif"]
], input);

$("#input").html(input);
$("#output").html(output);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.inline-img {
  height: 20px;
}</code>```

```

Body:
I want to create a program that let you input a sentence such as:
I am happy.
And outputs: I am  (happy emoji, in my case an image I've created myself).

So far I am able to replace happy by another word but I need to replace it with an image.
Can I add images to a string?
If so, how?

UPDATE: My code finally works, this is the html and javascript I've used:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Parse emotional expressions with emoticions.</title>

Body:
If your intention is to simply have the text displayed as HTML somewhere a simple modification to your replacement function will insert a <img> tag to the text.

This way all you need to do is provide a link to your images.

I changed your regex to include parenthesis in order to use the capture groups for the alt text of the <img> tags.

I also used a class to limit the height of the images with css.

function mreplace(replacements, str) {
  let result = str;
  for (let [x, y] of replacements) {
    result = result.replace(x, '<img src="' + y + '" alt="$1" class="inline-img" />');
  }
  return result;
}

let input = prompt('Input your sentence');
let output = mreplace([
  [/(happy)/ig, 'https://icon-icons.com/icons2/860/PNG/512/happy_icon-icons.com_67810.png'],
  [/(sad)/ig, 'https://images.vexels.com/media/users/17482/106930/raw/fcba42ccb55e21d86c6cc25078f0431e-cute-and-sad-icon-vector.png'],
  [/(confused)/ig, "http://i0.kym-cdn.com/photos/images/original/001/157/196/bcf.gif"]
], input);

$("#input").html(input);
$("#output").html(output);

.inline-img {
  height: 20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input"></div>
<div id="output"></div>


问:
Matlab integer strings decoding ... speed optimization
I have the following problem:

I need decode integer sequences "c" to char string messages "m" by following association:

```<code>  numpos = 10 % ( = size(c,2)/2)
  c = [3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3]
</code>```

Each row of "c" represents 2*numpos integers, where first numpos parameters encoded position of

```<code>types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'}
</code>```

and second numpos parameters are applied only if type contains character '@' like this:

```<code>  m = ' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
</code>```

My current solution is as follows:

```<code>  function m = c2m(c,types)

  numpos = size(c,2)/2;

  F = cellfun(@(f) [' ' f], strrep(types,'@',':%d@'),'unif',0);
  m = arrayfun(@(f,k) sprintf(f{1},k),F(c(:,1:numpos)),c(:,numpos+(1:numpos)),'unif', 0);
  m = arrayfun(@(i) horzcat(m{i,:}), (1:numlines)', 'unif', 0)

  end
</code>```

and the testing code is as follows:

```<code>  numlines = 10;
  c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3],numlines,1);
  types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};

  m = c2m(c,types);

  m =

    10×1 cell array

      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
</code>```

The code is still too slow for me, I am looking for any speed up. In this case the most significant fraction of CPU time is spent at built-in function "sprintf".

Typical realistic sizes of problem are:

```<code>   numpos ~ 30 ... 60
   numlines ~ 1e4 ... 1e5
</code>```

Any idea?

答:
Here's an alternative for your c2m function that is 2 to 3 times faster for the typical ranges of numpos and numlines you list above:

```<code>function m = c2m(c, types)
  numpos = size(c, 2)/2;
  [pre, post] = strtok(types(c(:, 1:numpos)), '@');
  mid = strsplit(sprintf(' :%i', 1:max(max(c(:, numpos+1:2*numpos)))));
  mid = mid(c(:, numpos+1:2*numpos).*~cellfun(@isempty, post)+1);
  m = cellstr(char(join(strcat(pre, mid, post))));
end
</code>```

First, the first half of c is split at the '@' using strtok. Then a cell array mid is created containing the strings {'' ':1' ':2' ... ':N'}, where N is the maximum value found in the second half of c. This allows us to avoid costly conversion functions applied to the whole matrix (like sprintf, num2str, int2str, etc.) by simply indexing into mid to get the string we want. The index is just the right half of c multiplied by a logical array representing whether '@' is present or not (gotten using cellfun) and incremented by 1.

Finally, the three different strings (pre, mid, and post) are concatenated using strcat, collected row-wise into strings using join (present since R2016b), then converted to a cell array of character arrays with cellstr and char.

Testing it with these value:

```<code>numpos = 10;
numlines = 10;
c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3], numlines, 1);
types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};
</code>```

We get the desired result:

```<code>m =

  10×1 cell array

    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
</code>```

Body:
I have the following problem:

I need decode integer sequences "c" to char string messages "m" by following association:

  numpos = 10 % ( = size(c,2)/2)
  c = [3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3]

Each row of "c" represents 2*numpos integers, where first numpos parameters encoded position of

types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'}

and second numpos parameters are applied only if type contains character '@' like this:

  m = ' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'

My current solution is as follows:

  function m = c2m(c,types)

  numpos = size(c,2)/2;

  F = cellfun(@(f) [' ' f], strrep(types,'@',':%d@'),'unif',0);
  m = arrayfun(@(f,k) sprintf(f{1},k),F(c(:,1:numpos)),c(:,numpos+(1:numpos)),'unif', 0);
  m = arrayfun(@(i) horzcat(m{i,:}), (1:numlines)', 'unif', 0)

  end

and the testing code is as follows:

  numlines = 10;
  c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3],numlines,1);
  types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};

  m = c2m(c,types);

  m =

    10×1 cell array

      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}

The code is still too slow for me, I am looking for any speed up. In this case the most significant fraction of CPU time is spent at built-in function "sprintf".

Typical realistic sizes of problem are:

   numpos ~ 30 ... 60
   numlines ~ 1e4 ... 1e5

Any idea?

Body:
Here's an alternative for your c2m function that is 2 to 3 times faster for the typical ranges of numpos and numlines you list above:

function m = c2m(c, types)
  numpos = size(c, 2)/2;
  [pre, post] = strtok(types(c(:, 1:numpos)), '@');
  mid = strsplit(sprintf(' :%i', 1:max(max(c(:, numpos+1:2*numpos)))));
  mid = mid(c(:, numpos+1:2*numpos).*~cellfun(@isempty, post)+1);
  m = cellstr(char(join(strcat(pre, mid, post))));
end

First, the first half of c is split at the '@' using strtok. Then a cell array mid is created containing the strings {'' ':1' ':2' ... ':N'}, where N is the maximum value found in the second half of c. This allows us to avoid costly conversion functions applied to the whole matrix (like sprintf, num2str, int2str, etc.) by simply indexing into mid to get the string we want. The index is just the right half of c multiplied by a logical array representing whether '@' is present or not (gotten using cellfun) and incremented by 1.

Finally, the three different strings (pre, mid, and post) are concatenated using strcat, collected row-wise into strings using join (present since R2016b), then converted to a cell array of character arrays with cellstr and char.

Testing it with these value:

numpos = 10;
numlines = 10;
c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3], numlines, 1);
types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};

We get the desired result:

m =

  10×1 cell array

    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
    'c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'


问:
super.super.func()? - Java polymorphism
Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?

I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().

Edit:
Thanks everyone; 'Skeen is back at the drawing board'.

答: You should probably rethink how you are handling your class hierarchy if you need to place a call to a function that is defined two levels up the hierarchy.  Consider writing new methods that are implemented by each subclass in a different way.</p>

Title: super.super.func()? - Java polymorphism


问:
How do I read CSV file row by row and update Python script?
I have the following Python 2.7 script:

```<code>import urllib as ul
tracking_id = "abcde=="
encodedtrackingid = ul.quote(tracking_id)
mcid = "123456"

URL = "https://example.com/id?abcd&d_mid="+mcid+"&=124"+encodedtrackingid+"%011"
print URL

from mechanize import Browser
br = Browser()
br.set_handle_robots(False)
response = br.open(URL)
print response.read()

import requests

url = "https://example.net/rest/v1/mbox/4513452615415"

querystring = {"client":"example"}

payload = "{\r\n              \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\""+mcid+"\",\r\n              \"thirdPartyId\": \""+tracking_id+"\",\r\n              \"contentAsJson\": \"true\",\r\n                             \"mboxParameters\": \r\n                             {        \r\n                             \"mboxMCGLH\": \"6\"     \r\n                             }\r\n}\r\n"
headers = {
    'content-type': "application/json",
    'cache-control': "no-cache",
    'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5"
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print(response.text)
</code>```

What I want to do is the following:

a) Repeat this script by updating the tracking_id and the mcid variable from a CSV file.

The CSV file has no headers and has the following columns:

Column: A - tracking_id
Column: B - mcid

I need the script to read the CSV file run the script for row 1, then repeat the same process for row2, row3, row4 etc. Each time the script runs the tracking_id and the mcid variable updates, and the output of the response variable is stored into a CSV file.

The end result would be a CSV file  that would have the following:
Column A - tracking_id
Column B - mcid
Column C - response

Any help is much appreciated.

Thanks

答:
First of all, I would wrap the initial script up in a function (myfunction in the code below) taking the tracking_id and the mcid as parameters and returning the value you wish to retrieve.

```<code>import csv

# Loading csv
with open("mycsv.csv", 'r') as csv_file:
    reader = csv.reader(csv_file)
    # Reading row by row
    for row in reader:
        tracking_id = row[0]
        mcid = row[1]

        # Getting result
        result = myfunction(tracking_id, mcid)

        # Opening csv result file in append mode
        with open("mycsv_result.csv", "a+") as csv_save:
            writer = csv.writer(csv_save)
            writer.writerow([tracking_id, mcid, result])
            csv_save.close()
</code>```

Then this script should do the trick.

EDIT :

Here is the function missing. I also suggest you to read this in order to learn how to create basic functions.

```<code>def myfunction(tracking_id, mcid):
    import urllib as ul

    encodedtrackingid = ul.quote(tracking_id)

    URL = "https://example.com/id?abcd&d_mid=" + mcid + "&=124" + encodedtrackingid + "%011"
    print
    URL

    from mechanize import Browser

    br = Browser()
    br.set_handle_robots(False)
    response = br.open(URL)
    print
    response.read()

    import requests

    url = "https://example.net/rest/v1/mbox/4513452615415"

    querystring = {"client": "example"}

    payload = "{\r\n              \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\"" + mcid + "\",\r\n              \"thirdPartyId\": \"" + tracking_id + "\",\r\n              \"contentAsJson\": \"true\",\r\n                             \"mboxParameters\": \r\n                             {        \r\n                             \"mboxMCGLH\": \"6\"     \r\n                             }\r\n}\r\n"
    headers = {
        'content-type': "application/json",
        'cache-control': "no-cache",
        'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5"
    }

    response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

    return response
</code>```

Body:
I have the following Python 2.7 script:

import urllib as ul
tracking_id = "abcde=="
encodedtrackingid = ul.quote(tracking_id)
mcid = "123456"

URL = "https://example.com/id?abcd&d_mid="+mcid+"&=124"+encodedtrackingid+"%011"
print URL

from mechanize import Browser
br = Browser()
br.set_handle_robots(False)
response = br.open(URL)
print response.read()

import requests

url = "https://example.net/rest/v1/mbox/4513452615415"

querystring = {"client":"example"}

payload = "{\r\n              \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\""+mcid+"\",\r\n              \"thirdPartyId\": \""+tracking_id+"\",\r\n              \"contentAsJson\": \"true\",\r\n                             \"mboxParameters\": \r\n                             {        \r\n                             \"mboxMCGLH\": \"6\"     \r\n                             }\r\n}\r\n"
headers = {
    'content-type': "application/json",
    'cache-control': "no-cache",
    'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5"
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print(response.text)

What I want to do is the following:

a) Repeat this script by updating the tracking_id and the mcid variable from a CSV file.

The CSV file has no headers and has the following columns:

Column: A - tracking_id
Column: B - mcid

I need the script to read the CSV file run the script for row 1, then repeat the same process for row2, row3, row4 etc. Each time the script runs the tracking_id and the mcid variable updates, and the output of the response variable is stored into a CSV file.

The end result would be a CSV file  that would have the following:
Column A - tracking_id
Column B - mcid
Column C - response

Any help is much appreciated.

Thanks

Body:
First of all, I would wrap the initial script up in a function (myfunction in the code below) taking the tracking_id and the mcid as parameters and returning the value you wish to retrieve.

import csv

# Loading csv
with open("mycsv.csv", 'r') as csv_file:
    reader = csv.reader(csv_file)
    # Reading row by row
    for row in reader:
        tracking_id = row[0]
        mcid = row[1]

        # Getting result
        result = myfunction(tracking_id, mcid)

        # Opening csv result file in append mode
        with open("mycsv_result.csv", "a+") as csv_save:
            writer = csv.writer(csv_save)
            writer.writerow([tracking_id, mcid, result])
            csv_save.close()

Then this script should do the trick.

EDIT :

Here is the function missing. I also suggest you to read this in order to learn how to create basic functions.

def myfunction(tracking_id, mcid):
    import urllib as ul

    encodedtrackingid = ul.quote(tracking_id)

    URL = "https://example.com/id?abcd&d_mid=" + mcid + "&=124" + encodedtrackingid + "%011"
    print
    URL

    from mechanize import Browser

    br = Browser()
    br.set_handle_robots(False)
    response = br.open(URL)
    print
    response.read()

    import requests

    url = "https://example.net/rest/v1/mbox/4513452615415"

    querystring = {"client": "example"}

    payload = "{\r\n              \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\"" + mcid + "\",\r\n              \"thirdPartyId\": \"" + tracking_id + "\",\r\n              \"contentAsJson\": \"true\",\r\n                             \"mboxParameters\": \r\n                             {        \r\n                             \"mboxMCGLH\": \"6\"     \r\n                             }\r\n}\r\n"
    headers = {
        'content-type': "application/json",
        'cache-control': "no-cache",
        'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5"
    }

    response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

    return response