问:
angular set $scope.value in controller function is not working
I am trying to set a angular variable value in controller function which is created by a directive. Somehow it is not working for some unknown reasons. The value is displayed when set independently but doesn't work when i try to assign value in a controller function.

My code is as below,

```<code><!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

</head>
<body>
    <div ng-app="mainApp">
        <div ng-controller="MyController">
            <div id="Details" class="Details">{{Details}}</div></br>
             <div id="Test" class="Test">
             <collection collection='testdata'></collection>
             </div>
        </div>
    </div>
</body>
<script>
var mainApp = angular.module("mainApp", [])

mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {collection: '=', showFn : '&'},
        template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
    }
})

mainApp.directive('member', function ($compile) {
    var NewChild = "<li><span ng-click=ShowDetailsFunc()>{{member.TagName}}</span></li>";

    return {
        restrict: "E",
        replace: true,
        scope: {member: '=', ShowHideCtrlFunc : '&', ShowDetailsCtrlFunc : '&'},
        template: NewChild,
        controller: 'MyController',
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.children"></collection>';
            if (angular.isArray(scope.member.children)) {
                    $compile(collectionSt)(scope, function(cloned, scope)   {
                        element.attr('xml-path', scope.member.TagPath);
                        element.append(cloned);
                     });
                    scope.ShowDetailsFunc = function() {
                        scope.ShowDetailsCtrlFunc(element,event);
                    }

            }
        }

    }
})

mainApp.controller('MyController', function ($scope) {
    $scope.testdata = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]

    $scope.Details = "defalut value"
    $scope.ShowDetailsCtrlFunc = function(element,event) {
            console.log("in function ShowDetailsCtrlFunc");
            var myxmlpath = $(element).attr("xml-path")
            $scope.Details = getObjects($scope.testdata, 'TagPath', myxmlpath)[0].TagName;
            console.log($scope.Details)
            //event.stopImmediatePropagation();
      };
});
function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}
</script>
</html>
</code>```

Please help me to understand where i am making mistake and how it can be rectified.

Please help. Many thanks in advance.

答:
The problem is that you are nesting MyController-controller when you create the directives in this circular way. The result is that the $scope.Details gets set on the specific nested scope instead of the one which is presenting the value in the view.

You can solve this by $emit the change which will send the new value upstream and finally reach the presenting scope value.

Here's an example

var mainApp = angular.module("mainApp", [])

mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {collection: '=', showFn : '&'},
        template: "
<member ng-repeat='member in collection' member='member'></member>
"
    }
})

mainApp.directive('member', function ($compile) {
    var NewChild = "
{{member.TagName}}
";

    return {
        restrict: "E",
        replace: true,
        scope: {member: '=', ShowHideCtrlFunc : '&', ShowDetailsCtrlFunc : '&'},
        template: NewChild,
        controller: 'MyController',
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.children"></collection>';
            if (angular.isArray(scope.member.children)) {
                    $compile(collectionSt)(scope, function(cloned, scope)   {
                        element.attr('xml-path', scope.member.TagPath);
                        element.append(cloned);
                     });
                    scope.ShowDetailsFunc = function() {
                        scope.ShowDetailsCtrlFunc(element);
                    }

            }
        }

    }
})

mainApp.controller('MyController', function ($scope) {
    $scope.testdata = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]

    $scope.Details = "defalut value";
    $scope.ShowDetailsCtrlFunc = function(element) {
            console.log("in function ShowDetailsCtrlFunc");
            var myxmlpath = angular.element(element).attr("xml-path")
            var detail = getObjects($scope.testdata, 'TagPath', myxmlpath)[0].TagName;
            console.log(detail);
            $scope.$emit('detailSelected',detail);
            //event.stopImmediatePropagation();
      };
      $scope.$on('detailSelected',function($event, message){
      $scope.Details = message;
    });
});
function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<script data-require="angularjs@1.6.4" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>

</head>
<body>
    <div ng-app="mainApp">
        <div ng-controller="MyController">
            <div id="Details" class="Details">{{Details}}</div></br>
             <div id="Test" class="Test">
             <collection collection='testdata'></collection>
             </div>
        </div>
    </div>
</body>

</html></code>```

Body:
I am trying to set a angular variable value in controller function which is created by a directive. Somehow it is not working for some unknown reasons. The value is displayed when set independently but doesn't work when i try to assign value in a controller function.

My code is as below,

<!doctype html>

<meta charset="UTF-8" />

{{Details}}

             <collection collection='testdata'></collection>

Please help me to understand where i am making mistake and how it can be rectified.

Please help. Many thanks in advance.

Body:
The problem is that you are nesting MyController-controller when you create the directives in this circular way. The result is that the $scope.Details gets set on the specific nested scope instead of the one which is presenting the value in the view.

You can solve this by $emit the change which will send the new value upstream and finally reach the presenting scope value.

Here's an example

var mainApp = angular.module("mainApp", [])

mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {collection: '=', showFn : '&'},
        template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
    }
})

mainApp.directive('member', function ($compile) {
    var NewChild = "<li><span ng-click=ShowDetailsFunc()>{{member.TagName}}</span></li>";

    return {
        restrict: "E",
        replace: true,
        scope: {member: '=', ShowHideCtrlFunc : '&', ShowDetailsCtrlFunc : '&'},
        template: NewChild,
        controller: 'MyController',
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.children"></collection>';
            if (angular.isArray(scope.member.children)) {
                    $compile(collectionSt)(scope, function(cloned, scope)   {
                        element.attr('xml-path', scope.member.TagPath);
                        element.append(cloned);
                     });
                    scope.ShowDetailsFunc = function() {
                        scope.ShowDetailsCtrlFunc(element);
                    }

            }
        }

    }
})

mainApp.controller('MyController', function ($scope) {
    $scope.testdata = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]

    $scope.Details = "defalut value";
    $scope.ShowDetailsCtrlFunc = function(element) {
            console.log("in function ShowDetailsCtrlFunc");
            var myxmlpath = angular.element(element).attr("xml-path")
            var detail = getObjects($scope.testdata, 'TagPath', myxmlpath)[0].TagName;
            console.log(detail);
            $scope.$emit('detailSelected',detail);
            //event.stopImmediatePropagation();
      };
      $scope.$on('detailSelected',function($event, message){
      $scope.Details = message;
    });
});
function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}

<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<script data-require="angularjs@1.6.4" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>

</head>
<body>
    <div ng-app="mainApp">
        <div ng-controller="MyController">
            <div id="Details" class="Details">{{Details}}</div></br>
             <div id="Test" class="Test">
             <collection collection='testdata'></collection>
             </div>
        </div>
    </div>
</body>

</html>


来源: stackexchange

问:
Ifelse in R with multiple categorical conditions
I have a data set, dt.train2 with  1500 different observations and 130 variables. One of them is languages and it can be english, french, arabic...

I want to create a ifelse string that gives attributes 1 for english, 2 for french, 3 for spanish and 0 for anything else. I have no idea how to do it.

```<code>dt.train2[, language_string := ifelse(language == "english",
                                      1,
                                      ifelse(language == "french",
                                             2,
                                             ifelse(language == "spanish",3)]
</code>```

I'm using this to run linear model about sales.

答:
You're almost there with the ifelse(), you just need the final else result (and a couple missing closing parentheses).

```<code>dt.train2[, language_string := ifelse(
  language == "english", 1,
    ifelse(language == "french", 2,
      ifelse(language == "spanish", 3, 0)
    )
  )
]
</code>```

A couple other ways you could do this:

Make a lookup table and join:

```<code># sample data
dt = data.table(language = c("english", "french", "spanish", "arabic", "chinese", "pig latin"))

lookup = data.table(language = c("english", "french", "spanish"),
                    language_string = c(1, 2, 3))

dt2 = merge(dt, lookup, by = "language", all.x = TRUE)
dt2[is.na(language_string), language_string := 0]
</code>```

The above lookup table method is probably the nicest for scalability. However, for such a small number of encodings, you could also just set each of them:

```<code># start with the default, 0
dt[, language_string := 0 ]
# then do each of the exceptions
dt[lanuage == "english", language_string := 1]
dt[language == "french", language_string := 2]
dt[language == "spanish", language_string := 3]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data set, dt.train2 with  1500 different observations and 130 variables. One of them is languages and it can be english, french, arabic...

I want to create a ifelse string that gives attributes 1 for english, 2 for french, 3 for spanish and 0 for anything else. I have no idea how to do it.

dt.train2[, language_string := ifelse(language == "english",
                                      1,
                                      ifelse(language == "french",
                                             2,
                                             ifelse(language == "spanish",3)]

I'm using this to run linear model about sales.

Body:
You're almost there with the ifelse(), you just need the final else result (and a couple missing closing parentheses).

dt.train2[, language_string := ifelse(
  language == "english", 1,
    ifelse(language == "french", 2,
      ifelse(language == "spanish", 3, 0)
    )
  )
]

A couple other ways you could do this:

Make a lookup table and join:

# sample data
dt = data.table(language = c("english", "french", "spanish", "arabic", "chinese", "pig latin"))

lookup = data.table(language = c("english", "french", "spanish"),
                    language_string = c(1, 2, 3))

dt2 = merge(dt, lookup, by = "language", all.x = TRUE)
dt2[is.na(language_string), language_string := 0]

The above lookup table method is probably the nicest for scalability. However, for such a small number of encodings, you could also just set each of them:

# start with the default, 0
dt[, language_string := 0 ]
# then do each of the exceptions
dt[lanuage == "english", language_string := 1]
dt[language == "french", language_string := 2]
dt[language == "spanish", language_string := 3]


问:
Intermittent `A conflicting conditional operation is currently in progress against this resource` when creating bucket
We've seen the conflicting conditional operation intermittently in our CI pipeline when creating a new bucket. We create the bucket with a random name so there should be no conflicting operations. We're using the terraform-aws-provider, which uses the aws-sdk-go, to create this bucket. Looks like they call CreateBucket followed by TagResource. We suspect that this error is due to the provider not calling WaitUntilBucketExists before calling TagResource. Does this seems plausible? If so, we can open an issue or PR with the terraform aws provider.

答:
According to the terraform code you're right, they do seem not to use WaitUntilBucketExists, you could check it here https://github.com/terraform-providers/terraform-provider-aws/blob/27e2f31ac052cf5dce63036756337be08f2ffa30/aws/resource_aws_s3_bucket.go#L442

```<code>err := resource.Retry(5*time.Minute, func() *resource.RetryError {
    log.Printf("[DEBUG] Trying to create new S3 bucket: %q", bucket)
    _, err := s3conn.CreateBucket(req)
    if awsErr, ok := err.(awserr.Error); ok {
        if awsErr.Code() == "OperationAborted" {
            log.Printf("[WARN] Got an error while trying to create S3 bucket %s: %s", bucket, err)
            return resource.RetryableError(
                fmt.Errorf("[WARN] Error creating S3 bucket %s, retrying: %s",
                    bucket, err))
</code>```

So basically they retry for 5 min... I guess you can open a Github issue or even better, create a PR :)

BTW, it's weird you hit the 5 minutes limit creating the bucket ... so I wonder if your CI could be hitting the threshold in AWS API rate limit. Could this be the case? Do you create several buckets at a time?

Body:
According to the terraform code you're right, they do seem not to use WaitUntilBucketExists, you could check it here https://github.com/terraform-providers/terraform-provider-aws/blob/27e2f31ac052cf5dce63036756337be08f2ffa30/aws/resource_aws_s3_bucket.go#L442

err := resource.Retry(5*time.Minute, func() *resource.RetryError {
    log.Printf("[DEBUG] Trying to create new S3 bucket: %q", bucket)
    _, err := s3conn.CreateBucket(req)
    if awsErr, ok := err.(awserr.Error); ok {
        if awsErr.Code() == "OperationAborted" {
            log.Printf("[WARN] Got an error while trying to create S3 bucket %s: %s", bucket, err)
            return resource.RetryableError(
                fmt.Errorf("[WARN] Error creating S3 bucket %s, retrying: %s",
                    bucket, err))

So basically they retry for 5 min... I guess you can open a Github issue or even better, create a PR :)

BTW, it's weird you hit the 5 minutes limit creating the bucket ... so I wonder if your CI could be hitting the threshold in AWS API rate limit. Could this be the case? Do you create several buckets at a time?


问:
how can i write a function which will multiply every alphabet of string n times in Haskell
I'm trying to write a function that takes a String and an Int and returns that every element of string  is multiplyed "int" times. That is:

```<code>duplicate :: String -> Int -> String
duplicate " abc " 2
</code>```

the output should be

```<code>Main >> "   aabbcc   "
</code>```

答:
Actually there are many ways to achieve what you want:

You could either do it recursively...

```<code>duplicate :: String -> Int -> String
duplicate (c:s) n
    | s == [] = replicate n c
    | otherwise = replicate n c ++ duplicate s n
</code>```

... or as the others pointed out, by using some of the Prelude functions ...

```<code>duplicate' :: String -> Int -> String
duplicate' s n = concatMap (replicate n) s
</code>```

... or by using fold ...

```<code>duplicate'' :: String -> Int -> String
duplicate'' s n = foldr1 (\c acc -> replicate n c ++ acc) "" s
</code>```

You would use these functions like:

```<code>main :: IO ()
main = do
    print $ duplicate   "abc" 3 -- "aaabbbccc"
    print $ duplicate'  "abc" 3 -- "aaabbbccc"
    print $ duplicate'' "abc" 3 -- "aaabbbccc"
</code>```

Body:
I'm trying to write a function that takes a String and an Int and returns that every element of string  is multiplyed "int" times. That is:

duplicate :: String -> Int -> String
duplicate " abc " 2

the output should be

Main >> "   aabbcc   "

Body:
Actually there are many ways to achieve what you want:

You could either do it recursively...

duplicate :: String -> Int -> String
duplicate (c:s) n
    | s == [] = replicate n c
    | otherwise = replicate n c ++ duplicate s n

... or as the others pointed out, by using some of the Prelude functions ...

duplicate' :: String -> Int -> String
duplicate' s n = concatMap (replicate n) s

... or by using fold ...

duplicate'' :: String -> Int -> String
duplicate'' s n = foldr1 (\c acc -> replicate n c ++ acc) "" s

You would use these functions like:

main :: IO ()
main = do
    print $ duplicate   "abc" 3 -- "aaabbbccc"
    print $ duplicate'  "abc" 3 -- "aaabbbccc"
    print $ duplicate'' "abc" 3 -- "aaabbbccc"


问:
Good implementation/support for java.util.concurrent.Flow.Processor<T,R>
Recently, I found a good support for Publisher by projectreactor.io:

```<code>Flux.create(fluxSink -> {
           for (int i = 0; i < 10; i++)
            fluxSink.next(i);
           fluxSink.complete();
        })
                .map(...)
                .subscribe(...);
</code>```

Is there any good support for Proccessor?
I mean something like or simular:

```<code>XXX process = new XXX((inputValue, output) -> {
    if(inputValue == 0)
       output.error();
    else
       output.next(inputValue);
});

publisher.subscribe(process);
process.subscribe(...);
</code>```

If not, how can I implement my own or why I cannot do this?

Update 1:

After discussion (see comments) it appeared that in my use case I need use flatMap (see answer), my question was Good implementation of processor by this I meant some functionality that if it's fails I able to take control and emit error instead. I think flatMap will give you quite enough functionality. In my case I used:

```<code>        import org.jsoup.Jsoup;

        Flux.just("url")
            .flatMap(url -> {
                try {
                    Document document = Jsoup.connect(url).get();
                    return Flux.just(document);
                } catch (IOException e) {
                    return Flux.error(e);
                }
            })
            .subscribe();
</code>```

答:
You're probably looking for SubmissionPublisher which seems similar to the Flux implementation in reactor:

A Flow.Publisher that asynchronously issues submitted (non-null)
  items to current subscribers until it is closed. Each current
  subscriber receives newly submitted items in the same order unless
  drops or exceptions are encountered. Using a SubmissionPublisher
  allows item generators to act as compliant reactive-streams Publishers
  relying on drop handling and/or blocking for flow control.

Note: A custom sample Flow.Processor is shared in the link which can be further customised to handle onError and consume method implementation as required for your use case.

Body:
Recently, I found a good support for Publisher by projectreactor.io:

Flux.create(fluxSink -> {
           for (int i = 0; i < 10; i++)
            fluxSink.next(i);
           fluxSink.complete();
        })
                .map(...)
                .subscribe(...);

Is there any good support for Proccessor?
I mean something like or simular:

XXX process = new XXX((inputValue, output) -> {
    if(inputValue == 0)
       output.error();
    else
       output.next(inputValue);
});

publisher.subscribe(process);
process.subscribe(...);

If not, how can I implement my own or why I cannot do this?

Update 1:

After discussion (see comments) it appeared that in my use case I need use flatMap (see answer), my question was Good implementation of processor by this I meant some functionality that if it's fails I able to take control and emit error instead. I think flatMap will give you quite enough functionality. In my case I used:

        import org.jsoup.Jsoup;

        Flux.just("url")
            .flatMap(url -> {
                try {
                    Document document = Jsoup.connect(url).get();
                    return Flux.just(document);
                } catch (IOException e) {
                    return Flux.error(e);
                }
            })
            .subscribe();


问:
Sitecore 9, Cannot get Controller Renderings to Render
I'm running into an issue where it seems that Controller Renderings are not being rendered by our install of Sitecore 9.  This is on a fresh install of 9.  I've gone through tutorials on various sites stepping through the creation of Controller Renderings (in hopes I was doing something wrong), have fiddled around with the Controller name (include just the name, do the whole namespace, do the whole namespace with the assembly after it, etc).  I've tried making the Controller inherit from just Controller, tried making it inherit from SitecoreController.  I've tried without a view (returning just Content) and with a view.  No luck.

What's more, I get no error, which I believe is unexpected.  I can put anything I want into the Controller name, any string of garbage text, include this as a control inside a content item placeholder, publish it and I just get a blank screen.  I can even revert the site back to where it was before I deployed any development code out to it, in essence returning it to the site provided by SIF and I get no error with my garbage controller rendering.

Has anyone experienced issues with Sitecore 9 and Controller Renderings?  At the least, I was assuming I'd at least get thrown some error if I was setting up the rendering wrong.

Any help is appreciated.

Thanks much.

答:
Well.  Nevermind.  But here's a great and obvious tip for anyone who comes after me.  The SIF website sample layout is a webforms layout.  Obviously, you cannot just drop a controller rendering or a view rendering into that.  You have to drop it into a razor layout as there's no mixing MVC and webforms.

Didn't see it as the sample layout is not in our development project.  But also would have loved to get some kind of error.

Stupid mistake.  But maybe it'll help somebody else.


问:
Selecting multiple tables for a Query MySQLi PHP
I am trying to create a query, but I don't know how to select multiple tables with the way I have my database set up.

In my query I am trying to display what movies have what actor, but each movie has multiple actors so I have to select from three tables.
This is my movies table:

This is my actor_information table

My last table is the actor_movie table. This table correlates the movie_id with and actor_id

I have the following php to connect to the database, but I am not sure how to write the query portion.

```<code><?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';

$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully <br>";

// this code is wrong, but i get the general idea of how to select from my db.
$sql = "SELECT actor_movie, movies, actor_information FROM actor_movie INNER
JOIN movies ON actor_movie.movie_id = movies.movie_id
INNER JOIN actor_information ON actor_movie.actor_id =
actor_information.actor_id"
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo " Title " . $row["title"]. "". $row["actor_id"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>
</code>```

Here is my uml if it helps:

答:
I think your query should look something like this:

```<code> "SELECT mov.title,act.actor_name FROM movies AS mov JOIN actor_information AS act ON act.actor_id=mov.movie_id"
</code>```

If you want to look for a particular movie or actor, simply append WHERE mov.title='Pulp Fiction', etc

Body:
I am trying to create a query, but I don't know how to select multiple tables with the way I have my database set up.

In my query I am trying to display what movies have what actor, but each movie has multiple actors so I have to select from three tables.
This is my movies table:

This is my actor_information table

My last table is the actor_movie table. This table correlates the movie_id with and actor_id

I have the following php to connect to the database, but I am not sure how to write the query portion.

<?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';

$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully
";

// this code is wrong, but i get the general idea of how to select from my db.
$sql = "SELECT actor_movie, movies, actor_information FROM actor_movie INNER
JOIN movies ON actor_movie.movie_id = movies.movie_id
INNER JOIN actor_information ON actor_movie.actor_id =
actor_information.actor_id"
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo " Title " . $row["title"]. "". $row["actor_id"]. "
";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>

Here is my uml if it helps:

Body:
I think your query should look something like this:

 "SELECT mov.title,act.actor_name FROM movies AS mov JOIN actor_information AS act ON act.actor_id=mov.movie_id"

If you want to look for a particular movie or actor, simply append WHERE mov.title='Pulp Fiction', etc


问:
Activity is resetting values
I have an activity that sum distance according user walks. The problem is when app goes to background and after something around 50 minutes I resume activity, values start again.
I have tried too many things to solve this problem without success.

Does someone have any idea?

Thanks

答: Solution is Run Background service because even in background, app need to be fed</p>

Title: Activity is resetting values


问:
In Java, can a method/constructor declaration appear inside another method/constructor declaration?
In Java, can a method/constructor declaration appear inside another method/constructor declaration? Example:

```<code>void A() {
    int B() { }
}
</code>```

I think not, but I'd love to be reassured.

答: No, Java only allows a method to be defined within a class, not within another method.</p>

ContentLicense: CC BY-SA 2.5

Body:
In Java, can a method/constructor declaration appear inside another method/constructor declaration? Example:

void A() {
    int B() { }
}

I think not, but I'd love to be reassured.


问:
Group By then concat items with commas
Using event hubs, I'm pushing my data to azure stream analytics. SearchWords, ItemId, UserId are some my data property.

What I want to do is, grouping my searchwords and concat the items. For example:

```<code>Data:
    SearchWords ItemId UserID
    wordA - 100 - 1
    wordA - 102 - 1
    wordC - 103 - 2
    wordD - 102 - 3
    wordA - 105 - 5

    Output:
    wordA - 100,102,105
    wordC - 103
    wordD - 102
</code>```

How can i do this in stream analytics query?

答:
You can use user defined aggregates to do this.
https://learn.microsoft.com/en-us/azure/stream-analytics/stream-analytics-javascript-user-defined-aggregates </p>

Title: Group By then concat items with commas

Body:
Using event hubs, I'm pushing my data to azure stream analytics. SearchWords, ItemId, UserId are some my data property.

What I want to do is, grouping my searchwords and concat the items. For example:

Data:
    SearchWords ItemId UserID
    wordA - 100 - 1
    wordA - 102 - 1
    wordC - 103 - 2
    wordD - 102 - 3
    wordA - 105 - 5

    Output:
    wordA - 100,102,105
    wordC - 103
    wordD - 102

How can i do this in stream analytics query?


问:
Warning: Can only update a mounted or mounting component
This is the full error:

index.js:2177 Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

What does it mean? What am I doing that is generating the error?

This is my login page:

```<code>/* global gapi */

class SignIn extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            redirect: false

        }
        this.onSignIn = this.onSignIn.bind(this)
        this.updateRedirect = this.updateRedirect.bind(this)
        // this.test = this.test.bind(this)
    }

     componentWillMount() {
        console.log('componentWillMount ran')
        gapi.load('auth2', () => {
            gapi.auth2.init({
                client_id: '817677528939-dss5sreclldv1inb26tb3tueac98d24r'
            }).then((auth2) => {
                console.log( "signed in: " + auth2.isSignedIn.get())
                this.setState({
                    redirect: auth2.isSignedIn.get()
                })
            })
        })
    }

    updateRedirect() {
        this.setState({
            redirect: true
        })
    }

    componentDidMount() {
        gapi.signin2.render('my-signin2', {
            'scope': 'profile email',
            'width': 300,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': this.onSignIn,
        });
    }

    onSignIn(googleUser) {
        console.log('this ran')
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        this.updateRedirect()
    }

    render() {
        return (
            this.state.redirect ?
            <Redirect to='/options' />
            :
            <div>
                <AppBar title="Pliny" showMenuIconButton={false} zDepth={2} />
                <div id="my-signin2"></div>
            </div>
        )
    }
}

export default SignIn
</code>```

For some reason when the page loads, it is loading the

 for a split second before re-routing. So the user sees the login page flash on the screen and then routed to the correct page.

Is there a way to have it re-route before anything else on the page loads?

Ideally, I'd like to check to see if a user is logged in, and if so, immediately route him to a specific page. If the user isn't logged in, then show them the login page (the
)

答: It looks like you've called this.setState in componentWillMount.  As the name suggests, the component isn't mounted yet at that time -- thus your error.

Body:
This is the full error:

index.js:2177 Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

What does it mean? What am I doing that is generating the error?

This is my login page:

/* global gapi */

class SignIn extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            redirect: false

        }
        this.onSignIn = this.onSignIn.bind(this)
        this.updateRedirect = this.updateRedirect.bind(this)
        // this.test = this.test.bind(this)
    }

     componentWillMount() {
        console.log('componentWillMount ran')
        gapi.load('auth2', () => {
            gapi.auth2.init({
                client_id: '817677528939-dss5sreclldv1inb26tb3tueac98d24r'
            }).then((auth2) => {
                console.log( "signed in: " + auth2.isSignedIn.get())
                this.setState({
                    redirect: auth2.isSignedIn.get()
                })
            })
        })
    }

    updateRedirect() {
        this.setState({
            redirect: true
        })
    }

    componentDidMount() {
        gapi.signin2.render('my-signin2', {
            'scope': 'profile email',
            'width': 300,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': this.onSignIn,
        });
    }

    onSignIn(googleUser) {
        console.log('this ran')
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        this.updateRedirect()
    }

    render() {
        return (
            this.state.redirect ?
            <Redirect to='/options' />
            :

                <AppBar title="Pliny" showMenuIconButton={false} zDepth={2} />

        )
    }
}

export default SignIn

For some reason when the page loads, it is loading the

 for a split second before re-routing. So the user sees the login page flash on the screen and then routed to the correct page.

Is there a way to have it re-route before anything else on the page loads?

Ideally, I'd like to check to see if a user is logged in, and if so, immediately route him to a specific page. If the user isn't logged in, then show them the login page (the
)


问:
Arrange nodes in ns2
I need to arrange 100 nodes in a hexagonal shape in my tcl script. My simulation is wireless (dsr protocol). How can I do this? Which is the best size of the grid? I thought 3000x3000.

Thank you.

答:
The simplest way is to build the network graphically .. you can use nsg tool to build the network and generate the tcl code very easily

http://www.nsnam.com/2013/04/ns2-scenario-generator.html

first you must determine the transition range of nodes, put required number of node-> get network size , or you can compute it mathematically using transmition range and hexagon aria

https://en.wikipedia.org/wiki/Hexagon

If you plan to use nsg to draw a regular hexagon use this simple trick:

if the transmition range is equal to 300 m then make it 250 m

put first node in the center of the network.

put two nodes in the border of first node coverage aria.

put other nodes in the  4 Intersection of coverage area o previous 3 nodes.

repeat previous steps for other hexagons.

return the transmition range to its correct value (300 m).

Title: Arrange nodes in ns2


问:
JavaScript regular expression check number only
I want a regular expression for the following values:

```<code>1) .1 = False.
2) 0.1 = True.
3) 1.1245 = True.
4) 1.2. = False.
5) 1.24.35 = False.
6) 21.152 = true.
</code>```

This regex should check that the string represents an integer or is composed of only numbers and a single . representing a decimal point.

I am using: /^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/ but it takes "1.2." as true.

答:
Your regex seems more complex than it needs to be. In order to live up to your requirements (starts with a number, ends with a number, at most one dot) you can use the following:

```<code>(^\d+\.\d+$)|(^\d+$)
</code>```

Edit:
Or even simpler:

```<code>^\d+(\.\d+)?$
</code>```

Body:
I want a regular expression for the following values:

1) .1 = False.
2) 0.1 = True.
3) 1.1245 = True.
4) 1.2. = False.
5) 1.24.35 = False.
6) 21.152 = true.

This regex should check that the string represents an integer or is composed of only numbers and a single . representing a decimal point.

I am using: /^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/ but it takes "1.2." as true.

Body:
Your regex seems more complex than it needs to be. In order to live up to your requirements (starts with a number, ends with a number, at most one dot) you can use the following:

(^\d+\.\d+$)|(^\d+$)

Edit:
Or even simpler:

^\d+(\.\d+)?$


问:
checkbox - replace check mark with fa-link
I have a checkbox set up. I am trying to get it to show a Font Awesome icon. Namely, fa-link when checked and nothing when not checked.

Here is the code:

input[type="checkbox"] {
    -webkit-appearance: initial;
    appearance: initial;
    outline: 1px solid #A9A9A9;
    width: 25px;
    height: 25px;
    background: #FFFFFF;
    position: relative;
}

input[type="checkbox"]:checked {
    background: #0073C0;
}

input[type="checkbox"]:checked:after {
    content: "\2713";
    color: #fff;
    position: absolute;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    outline: 1px solid #A9A9A9;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <input id="box1" type="checkbox" /></code>```

It should look like this:

I can't seem to figure this out.

答:
To use Font Awesome icons like this you will need to set the font family to FontAwesome where you set the unicode character for the content. Also, make sure you are using the correct unicode character (for the link icon its \f0c1)

Like this:

```<code>input[type="checkbox"]:checked:after {
    font-family: 'FontAwesome';
    content: "\f0c1";
    ....
}
</code>```

See this fiddle for a demo.

Body:
I have a checkbox set up. I am trying to get it to show a Font Awesome icon. Namely, fa-link when checked and nothing when not checked.

Here is the code:

input[type="checkbox"] {
    -webkit-appearance: initial;
    appearance: initial;
    outline: 1px solid #A9A9A9;
    width: 25px;
    height: 25px;
    background: #FFFFFF;
    position: relative;
}

input[type="checkbox"]:checked {
    background: #0073C0;
}

input[type="checkbox"]:checked:after {
    content: "\2713";
    color: #fff;
    position: absolute;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    outline: 1px solid #A9A9A9;
}

    <input id="box1" type="checkbox" />

It should look like this:

I can't seem to figure this out.

Body:
To use Font Awesome icons like this you will need to set the font family to FontAwesome where you set the unicode character for the content. Also, make sure you are using the correct unicode character (for the link icon its \f0c1)

Like this:

input[type="checkbox"]:checked:after {
    font-family: 'FontAwesome';
    content: "\f0c1";
    ....
}

See this fiddle for a demo.


问:
Lambda expression question
```<code>string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/
</code>```

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

答:
Perhaps breaking down what this expression does will help you understand it:

```<code>fruits.Select((fruit, index) =>
                  new { index, str = fruit.Substring(0, index) });
</code>```

Select(...) = With the input, return an output as indicated within.

(fruit, index) = Assign the selected fruit to the variable fruit, and the index (position in Enumerable) into index. As mentioned, this is simply one overload (option) available to you. If you don't care about the index value, simply omit it.

=> = return the following value

new { ... } = Create an instance of an anonymous type. This type will have two properties: index, and str. The value of index will be the variable index. the value of str will be the result of the substring on the fruit.

So, if you simply want the fruit, you could rewrite it like so:

```<code>fruits.Select(fruit => fruit);
</code>```

If you still want the index, with the full name of the fruit:

```<code>fruits.Select((fruit, index) =>
                  new { index, str = fruit});
</code>```

Select is useful for returning a different set of information from what the input was.

By way of example using a slightly more complex scenario:

For instance, if you had classes like so:

```<code>public class Customer {
 public int Id {get; set;}
 public string Name { get; set;}
 public List<Order> Orders { get; set;}
}

public class Order {
 public int Id { get;set;}
 public double TotalOrderValue { get;set}
}
</code>```

You could use a simple Select statement to return the customer, and the sum of how much that customer has ever ordered:

```<code> var customersTotalSpend = customers.Select(
      customer =>
      new {
            customer,
            TotalSpend = customer.Orders.Select(order => order.TotalOrderValue).Sum()
           });
</code>```

We could then do something with that TotalSpend value if we wanted, eg getting the 10 biggest spenders:

```<code>var biggestCustomers = customersTotalSpend.OrderByDescending(customerSpend=> customer.TotalSpend).Take(10);
</code>```

Does that make sense now?

Title: Lambda expression question

Body:
string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

Body:
Perhaps breaking down what this expression does will help you understand it:

fruits.Select((fruit, index) =>
                  new { index, str = fruit.Substring(0, index) });

Select(...) = With the input, return an output as indicated within.

(fruit, index) = Assign the selected fruit to the variable fruit, and the index (position in Enumerable) into index. As mentioned, this is simply one overload (option) available to you. If you don't care about the index value, simply omit it.

=> = return the following value

new { ... } = Create an instance of an anonymous type. This type will have two properties: index, and str. The value of index will be the variable index. the value of str will be the result of the substring on the fruit.

So, if you simply want the fruit, you could rewrite it like so:

fruits.Select(fruit => fruit);

If you still want the index, with the full name of the fruit:

fruits.Select((fruit, index) =>
                  new { index, str = fruit});

Select is useful for returning a different set of information from what the input was.

By way of example using a slightly more complex scenario:

For instance, if you had classes like so:

public class Customer {
 public int Id {get; set;}
 public string Name { get; set;}
 public List<Order> Orders { get; set;}
}

public class Order {
 public int Id { get;set;}
 public double TotalOrderValue { get;set}
}

You could use a simple Select statement to return the customer, and the sum of how much that customer has ever ordered:

 var customersTotalSpend = customers.Select(
      customer =>
      new {
            customer,
            TotalSpend = customer.Orders.Select(order => order.TotalOrderValue).Sum()
           });

We could then do something with that TotalSpend value if we wanted, eg getting the 10 biggest spenders:

var biggestCustomers = customersTotalSpend.OrderByDescending(customerSpend=> customer.TotalSpend).Take(10);

Does that make sense now?


问:
Master Detail Listview
I need to create a listview that looks similar to this:

But how can I add an expander to each row? Currently my XAML is far from what I need, but at least I have an expander and a list.

```<code><ListView Grid.Row="1" Margin="5,0,5,5" ItemsSource="{Binding ListEmployeePerGroup, Source={x:Static vm:AttendanceInfoVM.instance}}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Emp_ID}" />
                        <TextBlock Text="{Binding Emp_Name}" FontWeight="Bold" />
                        <Expander>
                            <StackPanel Orientation="Horizontal">
                                <Label Content="{Binding Emp_ID}"/>
                            </StackPanel>
                        </Expander>
                    </StackPanel>

                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

So what do I need in order to make a listview similar to the one in the picture?

Thank you.

答:
There is expander implemented in WPF but not on listView, it's on DataGrid and is shown well in this tutorial https://wpftutorial.net/DataGrid.html in section Row Details.
Hope it helps.</p>

Title: Master Detail Listview

Body:
I need to create a listview that looks similar to this:

But how can I add an expander to each row? Currently my XAML is far from what I need, but at least I have an expander and a list.

<ListView Grid.Row="1" Margin="5,0,5,5" ItemsSource="{Binding ListEmployeePerGroup, Source={x:Static vm:AttendanceInfoVM.instance}}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Emp_ID}" />
                        <TextBlock Text="{Binding Emp_Name}" FontWeight="Bold" />
                        <Expander>
                            <StackPanel Orientation="Horizontal">

                            </StackPanel>
                        </Expander>
                    </StackPanel>

                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

So what do I need in order to make a listview similar to the one in the picture?

Thank you.


问:
What have I done wrong with my collision detection?
I want to program a game. I have already programmed enemies and a player. Whenever the game objects, it doesn't matter whether enemy or player, move against the cornors (left and top or right and top or left and bottom or right and bottom), the game objects move outside of the field.

There is also a second problem. Sometimes, the enemies stick in the edge of the field for a short time

```<code>#include <Windows.h>
#include <SFML/Graphics.hpp>
#include <vector>
#include <ctime>
#include <cstdlib>
#include "Player.hpp"
#include "Square.hpp"

#define WIDTH 800
#define HEIGHT 600

bool kUp = false, kDown = false, kLeft = false, kRight = false;

Player player(WIDTH / 2 - 10, HEIGHT / 2 - 10, 10, sf::Color::Green);
std::vector<Square> squares(10);

sf::RenderWindow window;

void update(float elapsedTime) {
    if (kUp == true) player.move(0, -300.0f * elapsedTime);
    if (kDown == true) player.move(0, 300.0f * elapsedTime);
    if (kLeft == true) player.move(-300.0f * elapsedTime, 0);
    if (kRight == true) player.move(300.0f * elapsedTime, 0);

    sf::Vector2f playerPos = player.getPosition();
    if (playerPos.x < 0) player.setPosition(0, playerPos.y);
    if (playerPos.y < 0) player.setPosition(playerPos.x, 0);
    if (playerPos.x > WIDTH - 20) player.setPosition(WIDTH - 20, playerPos.y);
    if (playerPos.y > HEIGHT - 20) player.setPosition(playerPos.x, HEIGHT - 20);

    for (int i = 0; i < squares.size(); ++i) {
        sf::Vector2f squareSpeed = squares[i].getSpeed();
        squares[i].move(squareSpeed.x * elapsedTime, squareSpeed.y * elapsedTime);

        sf::Vector2f squarePos = squares[i].getPosition();
        if (squarePos.x < 0) squares[i].setSpeed(-squareSpeed.x, squareSpeed.y);
        if (squarePos.y < 0) squares[i].setSpeed(squareSpeed.x, -squareSpeed.y);
        if (squarePos.x > WIDTH - 5) squares[i].setSpeed(-squareSpeed.x, squareSpeed.y);
        if (squarePos.y > HEIGHT - 5) squares[i].setSpeed(squareSpeed.x, -squareSpeed.y);
    }
}

void draw() {
    for (int i = 0; i < squares.size(); ++i) {
        window.draw(squares[i]);
    }

    window.draw(player);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
    sf::ContextSettings settings;
    settings.antialiasingLevel = 8;

    window.create(sf::VideoMode(WIDTH, HEIGHT), "Runner - The Red Squares", sf::Style::Titlebar | sf::Style::Close, settings);
    window.setVerticalSyncEnabled(true);

    srand(time(0));
    for (int i = 0; i < squares.size(); ++i) {
        squares[i] = Square(rand() % WIDTH, rand() % HEIGHT, 5, 5, sf::Color::Red);
    }

    sf::Clock clock;
    while (window.isOpen()) {
        sf::Time elapsedTime = clock.restart();

        window.clear(sf::Color::Black);

        update(elapsedTime.asSeconds());
        draw();

        window.display();

        sf::Event evt;
        while (window.pollEvent(evt)) {
            if (evt.type == sf::Event::Closed) {
                window.close();
            }

            if (evt.type == sf::Event::KeyPressed) {
                if (evt.key.code == sf::Keyboard::Up) kUp = true;
                if (evt.key.code == sf::Keyboard::Down) kDown = true;
                if (evt.key.code == sf::Keyboard::Left) kLeft = true;
                if (evt.key.code == sf::Keyboard::Right) kRight = true;
            }

            if (evt.type == sf::Event::KeyReleased) {
                if (evt.key.code == sf::Keyboard::Up) kUp = false;
                if (evt.key.code == sf::Keyboard::Down) kDown = false;
                if (evt.key.code == sf::Keyboard::Left) kLeft = false;
                if (evt.key.code == sf::Keyboard::Right) kRight = false;
            }
        }

        sf::sleep(sf::milliseconds(15));
    }

    return 0;
}
</code>```

Does anyone know what I did wrong?

Thanks for each help

答:
The problem is because you're using a copy of the player position (stored in playerPos) while also updating the current player position (using player.getPosition()).  If the x and y positions are both negative, you'll initially set the player x position to 0.  In the next line, since y is negative, you set the player position to a 0 y but the old still negative x position from the copy.

There are several possible solutions, including always getting the player position (and not using the copy) or adding a way to only set the player x or y position without having to set both.

Body:
I want to program a game. I have already programmed enemies and a player. Whenever the game objects, it doesn't matter whether enemy or player, move against the cornors (left and top or right and top or left and bottom or right and bottom), the game objects move outside of the field.

There is also a second problem. Sometimes, the enemies stick in the edge of the field for a short time

#include <Windows.h>
#include <SFML/Graphics.hpp>
#include <vector>
#include <ctime>
#include <cstdlib>
#include "Player.hpp"
#include "Square.hpp"

#define WIDTH 800
#define HEIGHT 600

bool kUp = false, kDown = false, kLeft = false, kRight = false;

Player player(WIDTH / 2 - 10, HEIGHT / 2 - 10, 10, sf::Color::Green);
std::vector<Square> squares(10);

sf::RenderWindow window;

void update(float elapsedTime) {
    if (kUp == true) player.move(0, -300.0f * elapsedTime);
    if (kDown == true) player.move(0, 300.0f * elapsedTime);
    if (kLeft == true) player.move(-300.0f * elapsedTime, 0);
    if (kRight == true) player.move(300.0f * elapsedTime, 0);

    sf::Vector2f playerPos = player.getPosition();
    if (playerPos.x < 0) player.setPosition(0, playerPos.y);
    if (playerPos.y < 0) player.setPosition(playerPos.x, 0);
    if (playerPos.x > WIDTH - 20) player.setPosition(WIDTH - 20, playerPos.y);
    if (playerPos.y > HEIGHT - 20) player.setPosition(playerPos.x, HEIGHT - 20);

    for (int i = 0; i < squares.size(); ++i) {
        sf::Vector2f squareSpeed = squares[i].getSpeed();
        squares[i].move(squareSpeed.x * elapsedTime, squareSpeed.y * elapsedTime);

        sf::Vector2f squarePos = squares[i].getPosition();
        if (squarePos.x < 0) squares[i].setSpeed(-squareSpeed.x, squareSpeed.y);
        if (squarePos.y < 0) squares[i].setSpeed(squareSpeed.x, -squareSpeed.y);
        if (squarePos.x > WIDTH - 5) squares[i].setSpeed(-squareSpeed.x, squareSpeed.y);
        if (squarePos.y > HEIGHT - 5) squares[i].setSpeed(squareSpeed.x, -squareSpeed.y);
    }
}

void draw() {
    for (int i = 0; i < squares.size(); ++i) {
        window.draw(squares[i]);
    }

    window.draw(player);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
    sf::ContextSettings settings;
    settings.antialiasingLevel = 8;

    window.create(sf::VideoMode(WIDTH, HEIGHT), "Runner - The Red Squares", sf::Style::Titlebar | sf::Style::Close, settings);
    window.setVerticalSyncEnabled(true);

    srand(time(0));
    for (int i = 0; i < squares.size(); ++i) {
        squares[i] = Square(rand() % WIDTH, rand() % HEIGHT, 5, 5, sf::Color::Red);
    }

    sf::Clock clock;
    while (window.isOpen()) {
        sf::Time elapsedTime = clock.restart();

        window.clear(sf::Color::Black);

        update(elapsedTime.asSeconds());
        draw();

        window.display();

        sf::Event evt;
        while (window.pollEvent(evt)) {
            if (evt.type == sf::Event::Closed) {
                window.close();
            }

            if (evt.type == sf::Event::KeyPressed) {
                if (evt.key.code == sf::Keyboard::Up) kUp = true;
                if (evt.key.code == sf::Keyboard::Down) kDown = true;
                if (evt.key.code == sf::Keyboard::Left) kLeft = true;
                if (evt.key.code == sf::Keyboard::Right) kRight = true;
            }

            if (evt.type == sf::Event::KeyReleased) {
                if (evt.key.code == sf::Keyboard::Up) kUp = false;
                if (evt.key.code == sf::Keyboard::Down) kDown = false;
                if (evt.key.code == sf::Keyboard::Left) kLeft = false;
                if (evt.key.code == sf::Keyboard::Right) kRight = false;
            }
        }

        sf::sleep(sf::milliseconds(15));
    }

    return 0;
}

Does anyone know what I did wrong?

Thanks for each help


问:
Defining multiple variances of __iter__ in a class
I am writing a game of Connect 4 and have a Grid class that resembles the 2-dimensional grid that the game is played in. The underlying data structure of my Grid class is an instance variable self.grid - a 2-dimensional list.

I have overwritten the __iter__ method as such:

```<code>def __iter__(self):
    for row in range(self.numRows):
        for col in range(self.numCols):
            yield self.grid[row][col]
</code>```

which I can then call as:

```<code>for cell in grid:
    # do something with yielded cell
</code>```

At some points, I need to iterate over just a specified row or a specified column. Instead of writing

```<code>col = 0
for row in range(grid.numRows):
    # do something with grid.grid[row][col]
</code>```

is there any Pythonic, readable way to define a 2nd and 3rd __iter__ method along the lines of:

```<code>def __iter__(self, col)
    for row in range(self.numRows):
        yeild self.grid[row][col]
</code>```

which would be called as:

```<code>for row in grid(col=0):
    # do something with the yielded cell
</code>```

and then the same, but with a specified row?

答:
You can certainly have as many of these methods as you like.  You just can't call them all __iter__(), because Python does not support method overloading.  You could, for example, do this:

```<code>def rows(self, col):
    for row in range(self.numRows):
        yield self.grid[row][col]

def cols(self, row):
    for col in range(self.numCols):
        yield self.grid[row][col]

def cells(self):
    for row in range(self.numRows):
        for col in range(self.numCols):
            yield self.grid[row][col]
</code>```

You would then write something like

```<code>for row in grid.rows(col=0):
    # Do something
</code>```

Body:
I am writing a game of Connect 4 and have a Grid class that resembles the 2-dimensional grid that the game is played in. The underlying data structure of my Grid class is an instance variable self.grid - a 2-dimensional list.

I have overwritten the __iter__ method as such:

def __iter__(self):
    for row in range(self.numRows):
        for col in range(self.numCols):
            yield self.grid[row][col]

which I can then call as:

for cell in grid:
    # do something with yielded cell

At some points, I need to iterate over just a specified row or a specified column. Instead of writing

col = 0
for row in range(grid.numRows):
    # do something with grid.grid[row][col]

is there any Pythonic, readable way to define a 2nd and 3rd __iter__ method along the lines of:

def __iter__(self, col)
    for row in range(self.numRows):
        yeild self.grid[row][col]

which would be called as:

for row in grid(col=0):
    # do something with the yielded cell

and then the same, but with a specified row?

Body:
You can certainly have as many of these methods as you like.  You just can't call them all __iter__(), because Python does not support method overloading.  You could, for example, do this:

def rows(self, col):
    for row in range(self.numRows):
        yield self.grid[row][col]

def cols(self, row):
    for col in range(self.numCols):
        yield self.grid[row][col]

def cells(self):
    for row in range(self.numRows):
        for col in range(self.numCols):
            yield self.grid[row][col]

You would then write something like

for row in grid.rows(col=0):
    # Do something


问:
Extracting values from Haskell type synonyms
I'm writing a Dominoes game for class and can't wrap my head around custom types. I have:

```<code>type DomsPlayer = Hand -> Board -> (Domino,End)
...
playTurn :: DomsPlayer -> (Int, Hand, Board)
playTurn hand1 board1 = (score, hand2, board2)
  where (dom, end) = simplePlayer hand1 board1
                     board2 = resMaybe (playDom dom board1 end)
                     hand2 = remove dom hand1
                     score = scoreBoard board2
</code>```

Trying to load this gives me the errors:

Dominoes.hs:43:3: error:

• Couldn't match expected type ‘(Int, Hand, Board)’
                   with actual type ‘Board -> (Int, b0, Board)’

• The equation(s) for ‘playTurn’ have two arguments,
       but its type ‘DomsPlayer -> (Int, Hand, Board)’ has only one

|
  43 |   playTurn hand1 board1 = (score, hand2, board2)    |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...

Dominoes.hs:44:37: error:

• Couldn't match type ‘Hand -> Board -> (Domino, End)’
                       with ‘[Domino]’

Expected type: Hand
        Actual type: DomsPlayer

• Probable cause: ‘hand1’ is applied to too few arguments

In the first argument of ‘simplePlayer’, namely ‘hand1’

In the expression: simplePlayer hand1 board1

In a pattern binding: (dom, end) = simplePlayer hand1 board1

|
  44 |     where (dom, end) = simplePlayer hand1 board1    |

How do I retrieve the values from DomsPlayer?

答:
If you replace this DomsPlayer with its definition

```<code>type DomsPlayer = Hand -> Board -> (Domino,End)

playTurn :: (Hand -> Board -> (Domino,End)) -> (Int, Hand, Board)
</code>```

you will see that playTurn recieves only one parameter, not two.

I don't know what you are trying to do, but clearly you will need to recieve Hand and Board as separate params:

```<code>playTurn :: Hand -> Board -> ... -> (Int, Hand, Board)
</code>```

And I don't know, maybe also pass a function of type DomsPlayer too, and apply it to those separate arguments.

But that is your error.

Body:
I'm writing a Dominoes game for class and can't wrap my head around custom types. I have:

type DomsPlayer = Hand -> Board -> (Domino,End)
...
playTurn :: DomsPlayer -> (Int, Hand, Board)
playTurn hand1 board1 = (score, hand2, board2)
  where (dom, end) = simplePlayer hand1 board1
                     board2 = resMaybe (playDom dom board1 end)
                     hand2 = remove dom hand1
                     score = scoreBoard board2

Trying to load this gives me the errors:

Dominoes.hs:43:3: error:

• Couldn't match expected type ‘(Int, Hand, Board)’
                   with actual type ‘Board -> (Int, b0, Board)’

• The equation(s) for ‘playTurn’ have two arguments,
       but its type ‘DomsPlayer -> (Int, Hand, Board)’ has only one

|
  43 |   playTurn hand1 board1 = (score, hand2, board2)    |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...

Dominoes.hs:44:37: error:

• Couldn't match type ‘Hand -> Board -> (Domino, End)’
                       with ‘[Domino]’

Expected type: Hand
        Actual type: DomsPlayer

• Probable cause: ‘hand1’ is applied to too few arguments

In the first argument of ‘simplePlayer’, namely ‘hand1’

In the expression: simplePlayer hand1 board1

In a pattern binding: (dom, end) = simplePlayer hand1 board1

|
  44 |     where (dom, end) = simplePlayer hand1 board1    |

How do I retrieve the values from DomsPlayer?

Body:
If you replace this DomsPlayer with its definition

type DomsPlayer = Hand -> Board -> (Domino,End)

playTurn :: (Hand -> Board -> (Domino,End)) -> (Int, Hand, Board)

you will see that playTurn recieves only one parameter, not two.

I don't know what you are trying to do, but clearly you will need to recieve Hand and Board as separate params:

playTurn :: Hand -> Board -> ... -> (Int, Hand, Board)

And I don't know, maybe also pass a function of type DomsPlayer too, and apply it to those separate arguments.

But that is your error.


问:
How can I debug high cpu usage in electron?
I'm writing an Electron app and a few builds back testers started noticing that two electron.exe processes were consuming a lot of CPU time all the time. One pegging a CPU core and the other using about 85% of a core.

I'm certain that this was not always the case as builds several months ago didn't do this. But I'm at a loss to know how to debug what code changes may have introduced this as the code base has evolved dramatically over that time.

process.getIOCounters() reports that several gigabytes of IO is occurring every few minutes. The application is not deadlocked and everything still works it is just chewing through CPU. It happens anytime the app is open even if it is in the background without any user input. I only have windows 10 x64 systems that I've deployed this to as Electron 1.7.9 and also 1.7.5.

Based on the behavior I'm certain that this IO is interprocess communication between the render and main threads, but I'm not manually performing any IPC. I think this problem is being caused by some module we've introduced that improperly resides in the rendered thread.

My question, how does one debug the The Electron render/main thread IPC pipe? Can it be hooked to know what the contents of the gigabytes of traffic are?

答:
Based on the past few days of attempting to debug this I've answer the question for myself:

My question, how does one debug the The Electron render/main thread IPC pipe?

Don't, electron seemed like a good idea, writing all your client and platform code in the same place. But there are a lot of catches, and out of the blue libraries will have strange bugs that are costly to address because they are outside the main stream use case. This certainly has a lot to do with me not being an Electron Expert, but in the real world there are deadlines and timelines and I can't always get up to speed as much as I would like to.

I've updated my architecture to the tried an true Service/GUI model. I'll be maintaining full browser support for the client code as well as an Electron mode with hooks for some features when electron is detected.

This allows me to quickly identify issues that are specific to browser, version or platform framework. It also lets me use which ever version of NodeJS that I would like to for the service which has also been an issue in my case.

I still love Electron though, I'm just going to be more careful as I use it. If I do discover the specifics of why I had this problem I'll check back and report those details.

Update

So this issue was not directly related to Electron like I had supposed, the IPC was not between the renderer and main threads and was a red herring. It was actually a chrome key frame animation issue which was causing a 60 FPS redraw rate, still not sure why this caused GBs of IPC, but whatever. See https://github.com/Microsoft/vscode/issues/22900

I was able to discover this by porting this app back to native browser ( with nodejs service ). I then ran in chrome, edge and firefox. Only chrome behaved this way.


问:
Cycling images with javascript
Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image. </p>

```<code><!DOCTYPE html>
<html>
    <body>
        <script>
            function changeImg() {
                if (document.getElementById("cycle").src == "fox.jpg") {
                    document.getElementById("cycle").src = "hawk.jpg";
                } else {
                    document.getElementById("cycle").src = "ant.jpg";
                }
            }
        </script>

        <button onclick = "changeImg()">change image</button>
        <img id ="cycle" src ="fox.jpg"/>
    </body>
</html>
</code>```

答:
Please add your script tags at the end of the body to make sure that your dom is rendered before accessing any elements. (like in my example)
The problem with your code is, that you need to add a new if for every new image you add. As you noticed yourself, it becomes hard to understand and debug.
For something like cycling, use an array and modulo operation on the index of that array.

With this solution, you can add as many images to the images array as you like, without touching the code/logic;

```<code><!DOCTYPE html>
<html>
<body>
  <button onclick="changeImg()">change image</button>
  <img id="cycle" />

  <script>
    var imageElement = document.getElementById("cycle");
    var images = ["fox.jpg", "hawk.jpg", "ant.jpg"]; // add as many images as you want
    var counter = 0;
    imageElement.src = images[counter] // set the initial image

    function changeImg() {
      counter = (counter + 1) % images.length;
      imageElement.src = images[counter];
    }
  </script>
</body>
</html>
</code>```

Title: Cycling images with javascript

Body:
Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image.

<!DOCTYPE html>

        <button onclick = "changeImg()">change image</button>

Body:
Please add your script tags at the end of the body to make sure that your dom is rendered before accessing any elements. (like in my example)
The problem with your code is, that you need to add a new if for every new image you add. As you noticed yourself, it becomes hard to understand and debug.
For something like cycling, use an array and modulo operation on the index of that array.

With this solution, you can add as many images to the images array as you like, without touching the code/logic;

<!DOCTYPE html>
<html>
<body>
  <button onclick="changeImg()">change image</button>
  <img id="cycle" />

  <script>
    var imageElement = document.getElementById("cycle");
    var images = ["fox.jpg", "hawk.jpg", "ant.jpg"]; // add as many images as you want
    var counter = 0;
    imageElement.src = images[counter] // set the initial image

    function changeImg() {
      counter = (counter + 1) % images.length;
      imageElement.src = images[counter];
    }
  </script>
</body>
</html>


问:
Can I prevent the user of my program to resize the console window? (in C)
So I was searching (a lot) and haven't find anything on how to prevent user from resizing my program's console window. I had found information for language C++ and C# but not for C. I already managed to set the size of the console but if the user changes it afterwards it is not good for my program's looking. Is there anything I can do to perfectly resize the console and keep it that way?

答:
Trap the EVENT_CONSOLE_LAYOUT event by setting an event hook with SetWinEventHook, and in the WinEventProc callback call SetConsoleWindowInfo to immediately restore the desired size.

You might also set the window buffer to the exact dimensions of the visible window using SetWindowScreenBufferSize since it is not possible to make the visible window larger than the buffer size.  This will not prevent making the windows smaller however.


问:
Utalization of classes in python
I'm trying to teach myself about OOP in python and am really struggling.

I have the following:

```<code>        def __init__(self, quantity):
            ''' '''
            self.switchboard = []
            self.state = False
            self.quantity = quantity
            for i in range(quantity):
                self.switchboard.append(i)

        def __str__(self):
            self.on_list = []
            for i in range(self.quantity):
                if i == True:
                    self.on_list.append(i)
            return("The following switches are on " + str(self.on_list))
        def which_switch(self):
            for i in range(len(self.switchboard)):
                self.on_list = []
                if self.switchboard[i] == True:
                    on_list.append(i)
                print(on_list)

        def flip(self, n):
            if self.switchboard[n] == True:
                self.switchboard[n] = False
            else:
                self.switchboard[n] = True
</code>```

When I print it, I get The following switches are on [1]. Even though I put 10 in the parameters. I want it to display all the switches that are on which in this case should be zero since their initial state is 'off'.

答:
In __str__ modify the line:

```<code>if i == True:
</code>```

to:

```<code>if self.switchboard[i]:
</code>```

Remember: i is just an index, what you want is to access the i-th item in switchboard!

There is also another bug, in method which_switch():

```<code>on_list.append(i)
</code>```

should be:

```<code>self.on_list.append(i)
</code>```

and same goes to the print line below it.

Output after the change:

```<code>The following switches are on [1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

Now, I can only guess that what you actually wanted to do in the constructor is:

```<code>def __init__(self, quantity):
    ''' '''
    self.switchboard = []
    self.state = False
    self.quantity = quantity
    for i in range(quantity):
        self.switchboard.append(LightSwitch('off'))  # create light-switch and set it to 'off'
</code>```

and then, when you print them - print only the ones that are on:

```<code>def __str__(self):
    self.on_list = []
    for i in range(self.quantity):
        if self.switchboard[i].state: # check state
            self.on_list.append(i)
    return("The following switches are on " + str(self.on_list))
</code>```

Title: Utalization of classes in python

Body:
I'm trying to teach myself about OOP in python and am really struggling.

I have the following:

        def __init__(self, quantity):
            ''' '''
            self.switchboard = []
            self.state = False
            self.quantity = quantity
            for i in range(quantity):
                self.switchboard.append(i)

        def __str__(self):
            self.on_list = []
            for i in range(self.quantity):
                if i == True:
                    self.on_list.append(i)
            return("The following switches are on " + str(self.on_list))
        def which_switch(self):
            for i in range(len(self.switchboard)):
                self.on_list = []
                if self.switchboard[i] == True:
                    on_list.append(i)
                print(on_list)

        def flip(self, n):
            if self.switchboard[n] == True:
                self.switchboard[n] = False
            else:
                self.switchboard[n] = True

When I print it, I get The following switches are on [1]. Even though I put 10 in the parameters. I want it to display all the switches that are on which in this case should be zero since their initial state is 'off'.

Body:
In __str__ modify the line:

if i == True:

to:

if self.switchboard[i]:

Remember: i is just an index, what you want is to access the i-th item in switchboard!

There is also another bug, in method which_switch():

on_list.append(i)

should be:

self.on_list.append(i)

and same goes to the print line below it.

Output after the change:

The following switches are on [1, 2, 3, 4, 5, 6, 7, 8, 9]

Now, I can only guess that what you actually wanted to do in the constructor is:

def __init__(self, quantity):
    ''' '''
    self.switchboard = []
    self.state = False
    self.quantity = quantity
    for i in range(quantity):
        self.switchboard.append(LightSwitch('off'))  # create light-switch and set it to 'off'

and then, when you print them - print only the ones that are on:

def __str__(self):
    self.on_list = []
    for i in range(self.quantity):
        if self.switchboard[i].state: # check state
            self.on_list.append(i)
    return("The following switches are on " + str(self.on_list))


问:
Jump back some iterations for vectorized remainder loop
I'm vectorizing a loop by hand and processing 4 items at a time.  The total number of items may not be a multiple of 4, so I have some items left at the end of my main loop.  I was thinking that I could do the remainder items with the same main vectorized loop if the count is larger than 4 and redoing some items is safe.  For example, If I need to process 10 items, I could process 0123, 4567, 6789 in three iterations.  I couldn't find any references to this technique.  Is it dumb but I don't see how?</p>

```<code>#include <stdint.h>
#include <stddef.h>

void inc(int32_t const* __restrict in, int32_t* out, size_t count)
{
    if (count < 4)
    {
        for (size_t i = 0; i < count; ++i)
            out[i] = in[i] + 42;
    }
    else
    {
        typedef int32_t v4i __attribute__ ((vector_size (16), aligned(4)));
        for (size_t i = 0;;)
        {
            for (; i + 4 <= count; i += 4)
            {
                (v4i&)out[i] = (v4i&)in[i] + 42;
            }
            if (i == count)
                break;
            i = count - 4;
        }

    }
}
</code>```

答:
When your input and output don't overlap, and it's safe to re-process the same element multiple times, this general idea is great.  This is often the case when the output is write-only.  e.g. out[i] = pure_func(in[i]) is idempotent, but out[i] += func(in[i]) is not.  Reductions like sum += in[i] are also less amenable.

When it's usable, it's often better than a scalar cleanup loop.

When it's not quite this simple, see @Paul R's comments, and this related question: Vectorizing with unaligned buffers: using VMASKMOVPS: generating a mask from a misalignment count? Or not using that insn at all  (TL:DR: actually using vmaskmovps isn't usually good, but other masking and unaligned-load tricks are.)

Your specific implementation (of making the same loop reusable for overlapping last vector) ends up making the inner loop quite bad with clang, doing i+8 and i+4 inside each inner-loop iteration.

gcc manages make a slightly less bad inner loop, but it's still less efficient than it could be with gcc7.2 -O3 -mtune=haswell (asm output on Godbolt).  The inner loop has extra overhead because it's saving the old i every time it does i += 4, because of CSE between that and the i+4 in the loop condition, and/or the i = count - 4 outside the loop.  (gcc is sometimes pretty dumb about putting extra work inside an inner loop instead of recalculating or undoing an operation after.)

Source + asm on the Godbolt compiler explorer (for the original and an improved version (see below)).

```<code># Your original source, built with gcc7.2 -O3
# we get here with some registers already set up when count >= 4
.L2:                     # top of outer "loop"
    lea     rcx, [rax+4]
    cmp     rcx, rdx
    ja      .L4

.L17:                    # Inner loop
    movdqu  xmm0, XMMWORD PTR [rdi+rax*4]
    paddd   xmm0, xmm1
    movups  XMMWORD PTR [rsi+rax*4], xmm0
    mov     rax, rcx               # save RAX for use outside the loop!
    lea     rcx, [rax+4]           # 3 uops of loop overhead
    cmp     rcx, rdx
    jbe     .L17

.L4:
    # missed optimization: do rcx-4 here instead of extra work in every inner-loop iteration
    cmp     rax, rdx
    je      .L1             # ret if we're done (whole number of vectors)
    mov     rax, r8
    jmp     .L2             # else back into the loop for the last vector
</code>```

Using an indexed addressing mode doesn't particularly hurt with SSE2, but is not a good thing with AVX.  AVX allows unaligned memory operands to any instruction (except vmovdqa), so the compiler can fold the load into vpaddd  xmm0, xmm1, [rdi+rax*4] if you build with -march=haswell.  But that can't micro-fuse even on Haswell, so it's still 2 uops for the front-end.

We can fix clang's and gcc's inner loops by using i <= count - 4.  We know count >= 4 at this point, count - 4 will never wrap to a huge number.  (Note that i + 4 could wrap and thus create an infinite loop if count was within 4 of the max value for the type.  This is probably what was giving clang such a hard time and leading to missed optimizations).

Now we get an identical inner loop from gcc7.2 and clang5.0 (both using -O3 -march=haswell).  (Literally identical, even using the same registers, just a different label name.)

```<code>.L16:
    vpaddd  xmm0, xmm1, XMMWORD PTR [rdi+rax*4]
    vmovups XMMWORD PTR [rsi+rax*4], xmm0
    add     rax, 4
    cmp     rax, rcx
    jbe     .L16
</code>```

This is 5 fused-domain uops on Haswell, so can run at best one iteration per 1.25 clocks, bottlenecked on the front-end, not on load, store, or SIMD paddd throughput.  (It may bottleneck on memory bandwidth over large inputs, but unrolling at least a bit is generally a good thing even for that case.)

clang would have unrolled for you when auto-vectorizing, and used AVX2, so you're actually getting worse asm by manually vectorizing in this case where the compiler can do it easily.  (Unless you build with gcc -O2, which doesn't enable auto-vectorization).

You can actually see an example of how clang auto-vectorizes, because it vectorizes the cleanup loop, for some reason not realizing that it can't ever run with count >= 4.  Yes, it checks if count > 3 and jumps to the manually-vectorized loop, then check if it's 0, then checks if it's > 32 and jumps to an auto-vectorized version of the cleanup loop...  /facepalm.)

Actually jumping back into the main loop is mostly incompatible with unrolling in the C source, and will probably defeat compiler unrolling.

As noted above, unrolling the inner loop is usually a win.

In asm, you could certainly set things up so you could jump back into the inner loop for the last 1 or 2 vectors after an unrolled loop, and then maybe again for an unaligned final vector.

This may be bad for branch-prediction, though.  The loop-branch will probably be predicted strongly taken, so might mispredict each time you jump back into the loop.  Separate cleanup code won't have that problem, so if it's a real problem then separate cleanup code (duplicating the inner loop body) will be better.

You can usually wrap your inner loop logic in an inline function that you can use multiple times in an unrolled loop, and once in a cleanup / last-unaligned vector block.

Although your idea doesn't appear the hurt the inner loop in this case if you do it carefully, the amount of extra instructions and extra branching before/after the inner loop is probably more than you'd get with a simpler approach to cleanup.  So again, this might be useful if the loop body was very large, but in this case it's only a few instructions and cheaper to duplicate than to branch around.

One efficient way to solve the same problem is with a possibly-overlapping last vector, so there's no conditional branch that depends on whether the element count is a whole number of full vectors or not.  The final vector has to use unaligned load/store instructions because you don't know its alignment.

On modern x86 (Intel since Nehalem, AMD since Bulldozer, see Agner Fog's guides), unaligned load/store instructions on pointers that are actually aligned at runtime have no penalty.  (Unlike on Core2 where movdqu is always slower even if the data is actually aligned.)  IDK what the situation is on ARM, MIPS, or other SIMD architectures.

You can use this same idea to handle a possibly-unaligned first vector (which doesn't overlap if it is in fact aligned) and then make the main loop use aligned vectors.  With two pointers, one might be misaligned relative to the other, though.  The usual advice (from Intel's optimization manual) is to align the output pointer (that you're storing through.)

You can and should use __restrict on both pointers.  No reason not to unless it actually can alias something else.  If I was only going to do one, I'd use it on the output pointer, but it can matter to do both.

Body:
I'm vectorizing a loop by hand and processing 4 items at a time.  The total number of items may not be a multiple of 4, so I have some items left at the end of my main loop.  I was thinking that I could do the remainder items with the same main vectorized loop if the count is larger than 4 and redoing some items is safe.  For example, If I need to process 10 items, I could process 0123, 4567, 6789 in three iterations.  I couldn't find any references to this technique.  Is it dumb but I don't see how?

#include <stdint.h>
#include <stddef.h>

void inc(int32_t const* __restrict in, int32_t* out, size_t count)
{
    if (count < 4)
    {
        for (size_t i = 0; i < count; ++i)
            out[i] = in[i] + 42;
    }
    else
    {
        typedef int32_t v4i __attribute__ ((vector_size (16), aligned(4)));
        for (size_t i = 0;;)
        {
            for (; i + 4 <= count; i += 4)
            {
                (v4i&)out[i] = (v4i&)in[i] + 42;
            }
            if (i == count)
                break;
            i = count - 4;
        }

    }
}

Body:
When your input and output don't overlap, and it's safe to re-process the same element multiple times, this general idea is great.  This is often the case when the output is write-only.  e.g. out[i] = pure_func(in[i]) is idempotent, but out[i] += func(in[i]) is not.  Reductions like sum += in[i] are also less amenable.

When it's usable, it's often better than a scalar cleanup loop.

When it's not quite this simple, see @Paul R's comments, and this related question: Vectorizing with unaligned buffers: using VMASKMOVPS: generating a mask from a misalignment count? Or not using that insn at all  (TL:DR: actually using vmaskmovps isn't usually good, but other masking and unaligned-load tricks are.)

Your specific implementation (of making the same loop reusable for overlapping last vector) ends up making the inner loop quite bad with clang, doing i+8 and i+4 inside each inner-loop iteration.

gcc manages make a slightly less bad inner loop, but it's still less efficient than it could be with gcc7.2 -O3 -mtune=haswell (asm output on Godbolt).  The inner loop has extra overhead because it's saving the old i every time it does i += 4, because of CSE between that and the i+4 in the loop condition, and/or the i = count - 4 outside the loop.  (gcc is sometimes pretty dumb about putting extra work inside an inner loop instead of recalculating or undoing an operation after.)

<a href="https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSBnVAV2OUxAHIBSAJgGY8AO2QAbZlgDU3fgGEGBfEIIA6BDOzcADAEE%2BgkeKkz5irADM1G7Xt0B6O5PN4AHpnSSik5g0yS80rwAQpIALNJyMgAikmjMyjYAbqh4HsLIEMIE/LwA%2BgSxqEIKAFSSubnEmArEeMgFwqT%2Byjn5ZSwETQx4AF6Y%2BYXxBACUNtwA7EE2kjP%2B5pIQccoRsmGjurPSk9Obs%2BYkC919AwHRkloyIadygwn8IXxTwXjrOrvvkh3cAKxBeD8xM7CH5/AGBEKhXiXHYzCYxTCiXxbKYbD4EACeAAd3Jh5llWgVEqEAhUAIYEAi1ABGzAI/VyCwgiUw9RIuSOfggtAAbMMmqTRHhgEJ3BBQsMJdDUe99sRDr1%2Bg0IjELvdLsNkTCPjNZQtLv4VmclgUALRhfWnYJncVa7UTFFvbUfJnEvi8r6/f7fQH8GIu/68XnAz1gx5hKFq6VOuG2j54eaZZVGljKV5Oj5UqqkgDWUsd6euMWNkjNoTzdvGUTGUZjulrtgbyVSzWQuRIQsyLTyBTQxQIZQqVRqdQaQia%2BO77VpXQVA2Nr3tWvjC2LJjWWsXUc2uogHJOyvOFpWtwI%2BsejxesfeHtB3oPwdvgOC4fLszhkgRSM3%2Bd2GOxFmabJu0kIkSVyclKTwGk6QqRlmVZYh2QVBYeT5SQBSFEV0DFCVRkjH9twOXdZyVM5VSme4NW/dMdSIo8w3CExkyGeirV9dctw%2BaiaM2f03WGG8vR9P1QP4h8hPBF98J4%2BseOXRNomY1MrydTNMBzV8CwPYtS003Z6w3SsxiM3ROD5UQuG%2BThSCELgtGs1AuFkc9nyYVh2ECfhaGsgg7LMvlsxAfh%2BBUXhaG%2BWh%2BC0LQBG5UItG5blSAszhQms2zOHs0hHM4ayGBALRSF8zKzNIOBYBgRAUFQABbTE8FETAyAoRZavqxriBAYBxl4UhnFEOliHyiAqT80gqWEUliHRLhvNINAapqzBlAAeSEUQZpK0gsBq0khGARqxvwKp6jwZl8q2zA3GQWkOE4OasgRMbIJq2bSsFKl8sgPlUExAg8CKC6TQUdBomFZgXKCWhaBLAB1AVRBLFb%2BBLGqCHiTBogQUkGAAdwRRGTV2th1F9bG8YJvKWDYDhaHMyz0rGnKXAADm5E04skYBkGQSRxlChZcEIA59HoSRZDahqms8umfL8iVSEC75CpStLSFe8ZaBUbllZ5XWda0HkkoyrKcrygqivlsrKogJAFvapryEoe2pc6sQ9uAZXCv6wbhtGraJqEKbNrmhaltW9bNqynaPcOrbjpZf7zrGq6WVut7yGUJ6tpet7zKgr6IB%2Bv6AeKLhgcUMGhAhq1gmhuGEaRlGifRkUsZx/HREJ4nkFJqJyc70Qqfc2n6c4KybKZrhWfZzn3f2yRvhULRl8F/AiDlUWmglurXc83hhjlkqFYQdSsE6ovFZAZXkq4NWTYcrhzcK4r7IVwLEpUcYWdCNmAE4/7jG5Pwb4f8QG304Lwayr1aDRWXtFBBiCEH0AftlJ%2Bltj5jygZPLaZsMFvz5MyIapcQChCAA%3D%3D%3D" rel="nofollow noreferrer">Source + asm on the Godbolt compiler explorer (for the original and an improved version (see below)).

# Your original source, built with gcc7.2 -O3
# we get here with some registers already set up when count >= 4
.L2:                     # top of outer "loop"
    lea     rcx, [rax+4]
    cmp     rcx, rdx
    ja      .L4

.L17:                    # Inner loop
    movdqu  xmm0, XMMWORD PTR [rdi+rax*4]
    paddd   xmm0, xmm1
    movups  XMMWORD PTR [rsi+rax*4], xmm0
    mov     rax, rcx               # save RAX for use outside the loop!
    lea     rcx, [rax+4]           # 3 uops of loop overhead
    cmp     rcx, rdx
    jbe     .L17

.L4:
    # missed optimization: do rcx-4 here instead of extra work in every inner-loop iteration
    cmp     rax, rdx
    je      .L1             # ret if we're done (whole number of vectors)
    mov     rax, r8
    jmp     .L2             # else back into the loop for the last vector

Using an indexed addressing mode doesn't particularly hurt with SSE2, but is not a good thing with AVX.  AVX allows unaligned memory operands to any instruction (except vmovdqa), so the compiler can fold the load into vpaddd  xmm0, xmm1, [rdi+rax*4] if you build with -march=haswell.  But that can't micro-fuse even on Haswell, so it's still 2 uops for the front-end.

We can fix clang's and gcc's inner loops by using i <= count - 4.  We know count >= 4 at this point, count - 4 will never wrap to a huge number.  (Note that i + 4 could wrap and thus create an infinite loop if count was within 4 of the max value for the type.  This is probably what was giving clang such a hard time and leading to missed optimizations).

Now we get an identical inner loop from gcc7.2 and clang5.0 (both using -O3 -march=haswell).  (Literally identical, even using the same registers, just a different label name.)

.L16:
    vpaddd  xmm0, xmm1, XMMWORD PTR [rdi+rax*4]
    vmovups XMMWORD PTR [rsi+rax*4], xmm0
    add     rax, 4
    cmp     rax, rcx
    jbe     .L16

This is 5 fused-domain uops on Haswell, so can run at best one iteration per 1.25 clocks, bottlenecked on the front-end, not on load, store, or SIMD paddd throughput.  (It may bottleneck on memory bandwidth over large inputs, but unrolling at least a bit is generally a good thing even for that case.)

clang would have unrolled for you when auto-vectorizing, and used AVX2, so you're actually getting worse asm by manually vectorizing in this case where the compiler can do it easily.  (Unless you build with gcc -O2, which doesn't enable auto-vectorization).

You can actually see an example of how clang auto-vectorizes, because it vectorizes the cleanup loop, for some reason not realizing that it can't ever run with count >= 4.  Yes, it checks if count > 3 and jumps to the manually-vectorized loop, then check if it's 0, then checks if it's > 32 and jumps to an auto-vectorized version of the cleanup loop...  /facepalm.)

Actually jumping back into the main loop is mostly incompatible with unrolling in the C source, and will probably defeat compiler unrolling.

As noted above, unrolling the inner loop is usually a win.

In asm, you could certainly set things up so you could jump back into the inner loop for the last 1 or 2 vectors after an unrolled loop, and then maybe again for an unaligned final vector.

This may be bad for branch-prediction, though.  The loop-branch will probably be predicted strongly taken, so might mispredict each time you jump back into the loop.  Separate cleanup code won't have that problem, so if it's a real problem then separate cleanup code (duplicating the inner loop body) will be better.

You can usually wrap your inner loop logic in an inline function that you can use multiple times in an unrolled loop, and once in a cleanup / last-unaligned vector block.

Although your idea doesn't appear the hurt the inner loop in this case if you do it carefully, the amount of extra instructions and extra branching before/after the inner loop is probably more than you'd get with a simpler approach to cleanup.  So again, this might be useful if the loop body was very large, but in this case it's only a few instructions and cheaper to duplicate than to branch around.

One efficient way to solve the same problem is with a possibly-overlapping last vector, so there's no conditional branch that depends on whether the element count is a whole number of full vectors or not.  The final vector has to use unaligned load/store instructions because you don't know its alignment.

On modern x86 (Intel since Nehalem, AMD since Bulldozer, see Agner Fog's guides), unaligned load/store instructions on pointers that are actually aligned at runtime have no penalty.  (Unlike on Core2 where movdqu is always slower even if the data is actually aligned.)  IDK what the situation is on ARM, MIPS, or other SIMD architectures.

You can use this same idea to handle a possibly-unaligned first vector (which doesn't overlap if it is in fact aligned) and then make the main loop use aligned vectors.  With two pointers, one might be misaligned relative to the other, though.  The usual advice (from Intel's optimization manual) is to align the output pointer (that you're storing through.)

You can and should use __restrict on both pointers.  No reason not to unless it actually can alias something else.  If I was only going to do one, I'd use it on the output pointer, but it can matter to do both.


问:
How to make UIImagePickerController StatusBar lightContent style?

When I present the ImagePickerController the statusBar text color is still black, how to make like this?

答:
This is the quickest solution I could think of. Create the following category:</p>

```<code>@implementation UIImagePickerController (LightStatusBar)

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

@end
</code>```

Body:
This is the quickest solution I could think of. Create the following category:

@implementation UIImagePickerController (LightStatusBar)

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

@end