问:
Umbraco Examine, nested multiple boolean operators
I am trying to add these filters to an already reasonable complex Umbraco Examine query, and have seen that you can't mix the API with raw lucene query, so the whole thing might have to be done raw, which I was trying to avoid since its a query builder that has quite a few dimensions.

Is this sort of thing possible with the API? I saw the GroupedOr/And but I don't see how that cuts it since those are exclusive/inclusive sql "In" type queries.

```<code>AND ((_nodeTypAlias: 'Event' AND eventDate:(0xx TO 0xx)) OR (NOT _nodeTypAlias: 'Event'))
AND ((_nodeTypAlias: 'Article' AND postDate:(0xx TO 0xx)) OR (NOT _nodeTypAlias: 'Article'))
</code>```

答:
Achieved it with the most excellent Lucence query builder API

```<code>    var q = new QueryBuilder()
            .Must
            .MatchSubQuery(and => and
                .Should
                .MatchSubQuery(qq => qq
                    .Must
                    .MatchTerm("__NodeTypAlias", "Event")
                    .MatchRange(
                        "comparableEventDate",
                        DateTime.Now.ToString("yyyyMMddHHmm00000"),
                        DateTime.Now.AddYears(100).ToString("yyyyMMddHHmm00000"))
                .MatchSubQuery(qq => qq
                    .MustNot
                    .MatchTerm("__NodeTypAlias", "Event"))
            )
            .Query
            .ToString();
</code>```

Outputs:

+((+__NodeTypAlias:Event +eventDate:[42920 TO 79444]) (-__NodeTypAlias:Event))

and pass that into Umbraco Examine:

```<code>ISearchCriteria criteria = searcher.CreateSearchCriteria();
var filter = criteria.RawQuery(q);
var results = searcher.Search(filter, MaxResults);
</code>```

The Should operator translates to "OR" whilst Must translates to AND (Lucene nomenclature).

For reference, you need also to write new comparable date fields to the index in gathering node data:

```<code>    private void ExamineEvents_GatheringNodeData(object sender, IndexingNodeDataEventArgs e, UmbracoHelper umbraco)
    {
        if (e.IndexType != IndexTypes.Content) return;

        try
        {
            var content = new Node(e.NodeId);
            if (e.Fields.ContainsKey("postDate"))
                e.Fields.Add("comparablePostDate", DateTime.Parse(e.Fields["postDate"]).ToString("yyyyMMddHHmm00000"));
            if (e.Fields.ContainsKey("eventDate"))
                e.Fields.Add("comparableEventDate", DateTime.Parse(e.Fields["eventDate"]).ToString("yyyyMMddHHmm00000"));

            AddAuthor(e.Fields, content);
        }
        catch (Exception ex)
        {
            LogHelper.Error(this.GetType(), "Error in Umbers custom ExamineEvents_GatheringNodeData: ", ex);
            //does nowt!
            throw;
        }
    }
</code>```

Body:
I am trying to add these filters to an already reasonable complex Umbraco Examine query, and have seen that you can't mix the API with raw lucene query, so the whole thing might have to be done raw, which I was trying to avoid since its a query builder that has quite a few dimensions.

Is this sort of thing possible with the API? I saw the GroupedOr/And but I don't see how that cuts it since those are exclusive/inclusive sql "In" type queries.

AND ((_nodeTypAlias: 'Event' AND eventDate:(0xx TO 0xx)) OR (NOT _nodeTypAlias: 'Event'))
AND ((_nodeTypAlias: 'Article' AND postDate:(0xx TO 0xx)) OR (NOT _nodeTypAlias: 'Article'))

Body:
Achieved it with the most excellent Lucence query builder API

    var q = new QueryBuilder()
            .Must
            .MatchSubQuery(and => and
                .Should
                .MatchSubQuery(qq => qq
                    .Must
                    .MatchTerm("__NodeTypAlias", "Event")
                    .MatchRange(
                        "comparableEventDate",
                        DateTime.Now.ToString("yyyyMMddHHmm00000"),
                        DateTime.Now.AddYears(100).ToString("yyyyMMddHHmm00000"))
                .MatchSubQuery(qq => qq
                    .MustNot
                    .MatchTerm("__NodeTypAlias", "Event"))
            )
            .Query
            .ToString();

Outputs:

+((+__NodeTypAlias:Event +eventDate:[42920 TO 79444]) (-__NodeTypAlias:Event))

and pass that into Umbraco Examine:

ISearchCriteria criteria = searcher.CreateSearchCriteria();
var filter = criteria.RawQuery(q);
var results = searcher.Search(filter, MaxResults);

The Should operator translates to "OR" whilst Must translates to AND (Lucene nomenclature).

For reference, you need also to write new comparable date fields to the index in gathering node data:

    private void ExamineEvents_GatheringNodeData(object sender, IndexingNodeDataEventArgs e, UmbracoHelper umbraco)
    {
        if (e.IndexType != IndexTypes.Content) return;

        try
        {
            var content = new Node(e.NodeId);
            if (e.Fields.ContainsKey("postDate"))
                e.Fields.Add("comparablePostDate", DateTime.Parse(e.Fields["postDate"]).ToString("yyyyMMddHHmm00000"));
            if (e.Fields.ContainsKey("eventDate"))
                e.Fields.Add("comparableEventDate", DateTime.Parse(e.Fields["eventDate"]).ToString("yyyyMMddHHmm00000"));

            AddAuthor(e.Fields, content);
        }
        catch (Exception ex)
        {
            LogHelper.Error(this.GetType(), "Error in Umbers custom ExamineEvents_GatheringNodeData: ", ex);
            //does nowt!
            throw;
        }
    }


来源: stackexchange

问:
What is the reason behind instable type traits?
I was debugging a failing clang build today. That build essentially broke, because a is_default_constructible evaluated to false. I reduced the issue to a minimal case after several hours of bisecting the issue:

```<code>#include <type_traits>
#include <string>

namespace A {
    // This has been extracted from an old (outdated(?))
    // implementation of an optional type

    struct empty_t {};

    template<class T>
    struct o
    {
    public:
        template<class... U,
                 typename std::enable_if<
                     std::is_constructible<T, U...>::value,
                     bool
                     >::type = false
                 >
        o(empty_t, U&&... u) { }
    };

}

struct B
{
    struct Foo
    {
        //Foo () {};   // uncomment this line and it works
        bool x = true; // comment this line and it works
    };

    std::string c; // comment this line and it works, also change to int
    A::o<Foo> r;   // comment this line and it works

    static const bool b;
};

static_assert(
    std::is_default_constructible<B::Foo>::value,
    "not constructible!");
</code>```

The example above compiles fine with g++ 6.3 and 7.0. It fails with clang++ 4.0.0 and 3.9.1 - the static assertion fails only in that very specific construction, but it still broke our build. As you can try for yourself, some minimal changes fix the issue (e.g. commenting one of the mentioned lines). The result looks somewhat arbitrary.

What I'd like to know is, whether that apparent bug in clang is actually a bug or some undefined behavior. How well defined is that part of the language, actually?

I would also appreciate any advice on how to debug such issues: Is there a good way to get some info out of clang on why exactly it believes that Foo is not default constructible?

Finally, if anyone of you has access to a (standard compliant) third C++ implementation and could report on the results, that would be very nice.

答:
Default data member initializers of the nested class are not instantiated until the outer class is complete (i.e., at the semi-colon of the outer class's definition).  That leads to strange consequences when using type traits to query the nested class when it's complete (i.e., after its definition) but before the outer class is complete.

You can work around this by moving Foo outside B.

ContentLicense: CC BY-SA 3.0

Body:
I was debugging a failing clang build today. That build essentially broke, because a is_default_constructible evaluated to false. I reduced the issue to a minimal case after several hours of bisecting the issue:

#include <type_traits>
#include <string>

namespace A {
    // This has been extracted from an old (outdated(?))
    // implementation of an optional type

    struct empty_t {};

    template<class T>
    struct o
    {
    public:
        template<class... U,
                 typename std::enable_if<
                     std::is_constructible<T, U...>::value,
                     bool
                     >::type = false
                 >
        o(empty_t, U&&... u) { }
    };

}

struct B
{
    struct Foo
    {
        //Foo () {};   // uncomment this line and it works
        bool x = true; // comment this line and it works
    };

    std::string c; // comment this line and it works, also change to int
    A::o<Foo> r;   // comment this line and it works

    static const bool b;
};

static_assert(
    std::is_default_constructible::value,
    "not constructible!");

The example above compiles fine with g++ 6.3 and 7.0. It fails with clang++ 4.0.0 and 3.9.1 - the static assertion fails only in that very specific construction, but it still broke our build. As you can try for yourself, some minimal changes fix the issue (e.g. commenting one of the mentioned lines). The result looks somewhat arbitrary.

What I'd like to know is, whether that apparent bug in clang is actually a bug or some undefined behavior. How well defined is that part of the language, actually?

I would also appreciate any advice on how to debug such issues: Is there a good way to get some info out of clang on why exactly it believes that Foo is not default constructible?

Finally, if anyone of you has access to a (standard compliant) third C++ implementation and could report on the results, that would be very nice.


问:
Selecting multiple elements from an array in Ruby
I would like to select from an array the four highest elements in descending order in terms of length.

I sorted the array in descending order, and picked the elements.

Is there a more elegant way to do this?

答:
```<code>%w(one two three four five size seven eight).max_by(3, &:length)
=> ["seven", "eight", "three"]
</code>```


问:
Google chart: “Uncaught (in promise) Error: Unknown header type: 4.7278” error
I'm trying to display a line chart of currency rates via google charts.

Basically i have 2 type of values:

Date (format iso8601)

Rate (decimal number)

when i'm trying to render the chart i get an error: "Uncaught (in promise) Error: Unknown header type: 4.7278”

Here is my code:

PHP array making:

```<code>        $xml=simplexml_load_file('https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/usd.xml') or die("Error: Cannot create object");
    $arrayForChart[] = ["Date","Rate"];
    foreach ($xml->DataSet->Series->Obs as $key => $value) {
        $dateIso8601Format=(string)$value['TIME_PERIOD'];
        $rateForDate=(string)$value['OBS_VALUE'][0];
        $rateForDate=(float)$rateForDate;
        $arrayForChart[] = [$dateIso8601Format,$rateForDate];
    }
    $arrayForChart = json_encode($arrayForChart);
</code>```

Javascript

```<code>var arrayForChart;
$.ajax({
    type: "POST",
    url: ajaxUrl,
    //data: {configuration: Config },
    success: function (data) {

        arrayForChart = data;
        arrayForChart = $.map(arrayForChart, function (el) {
            return el;
        });//converting js object to js array

    },
    cache: false
});
google.charts.load("current", {packages: ["corechart", "line"]});
google.charts.setOnLoadCallback(drawLineColors);

function drawLineColors() {

    var data = google.visualization.arrayToDataTable([arrayForChart]);

    var options = {
        hAxis: {
            title: "Rate",
            id: "Rate",
            label: "Rate",
            type: "number"
        },
        vAxis: {
            title: "Date",
            id: "Date",
            label: "Date",
            type: "string"
        },
        colors: ["#a52714", "#097138"]
    };

    var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
    chart.draw(data, options);
}
</code>```

Sample of data:

```<code>["Date","Rate","2011-01-03",4.7278,"2011-01-04",4.7301,"2011-01-05",4.6814,"2011-01-06",4.6635]
</code>```

Anybody might know what is the problem?

Many thanks!

答:
Google charts expects an array of arrays. You appear to be providing it with one flat array. Eg

Array('date', 'value', 1,2,3,4);

Should be

```<code>Array(
    Array(date, value),
    Array(1, 2),
    Array(3, 4)
);
</code>```

Body:
I'm trying to display a line chart of currency rates via google charts.

Basically i have 2 type of values:

Date (format iso8601)

Rate (decimal number)

when i'm trying to render the chart i get an error: "Uncaught (in promise) Error: Unknown header type: 4.7278”

Here is my code:

PHP array making:

        $xml=simplexml_load_file('https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/usd.xml') or die("Error: Cannot create object");
    $arrayForChart[] = ["Date","Rate"];
    foreach ($xml->DataSet->Series->Obs as $key => $value) {
        $dateIso8601Format=(string)$value['TIME_PERIOD'];
        $rateForDate=(string)$value['OBS_VALUE'][0];
        $rateForDate=(float)$rateForDate;
        $arrayForChart[] = [$dateIso8601Format,$rateForDate];
    }
    $arrayForChart = json_encode($arrayForChart);

Javascript

var arrayForChart;
$.ajax({
    type: "POST",
    url: ajaxUrl,
    //data: {configuration: Config },
    success: function (data) {

        arrayForChart = data;
        arrayForChart = $.map(arrayForChart, function (el) {
            return el;
        });//converting js object to js array

    },
    cache: false
});
google.charts.load("current", {packages: ["corechart", "line"]});
google.charts.setOnLoadCallback(drawLineColors);

function drawLineColors() {

    var data = google.visualization.arrayToDataTable([arrayForChart]);

    var options = {
        hAxis: {
            title: "Rate",
            id: "Rate",
            label: "Rate",
            type: "number"
        },
        vAxis: {
            title: "Date",
            id: "Date",
            label: "Date",
            type: "string"
        },
        colors: ["#a52714", "#097138"]
    };

    var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
    chart.draw(data, options);
}

Sample of data:

["Date","Rate","2011-01-03",4.7278,"2011-01-04",4.7301,"2011-01-05",4.6814,"2011-01-06",4.6635]

Anybody might know what is the problem?

Many thanks!

Body:
Google charts expects an array of arrays. You appear to be providing it with one flat array. Eg

Array('date', 'value', 1,2,3,4);

Should be

Array(
    Array(date, value),
    Array(1, 2),
    Array(3, 4)
);

ContentLicense: CC BY-SA 4.0


问:
Is it possible to set a dotenv file with rails server command?
Is it possible to pass a specific dotenv file along with the rails s command when starting up a server (something like rails s --dotenv .env.ssl)? I'd like to start my local rails application with ssl (and therefore different environment variables) and in normal mode, where it would just load my normal .env file or something of the kind.

答:
Looking at dotenv, it doesn't appear to have any command line flag like that, however, where you call Dotenv.load you can pass in files Dotenv.load('file1.env', 'file2.env') so you can handle it manually (look for the flag or a specific ENV variable to determine which additional files to load). Alternatively, in the Frequently Asked Questions on the README it mentions

dotenv-rails will load the following files, starting from the bottom. The first value set (or those already defined in the environment) take precedence:

.env - The Original®

.env.development, .env.test, .env.production - Environment-specific settings.

.env.local - Local overrides. This file is loaded for all environments except test.

.env.development.local, .env.test.local, .env.production.local - Local overrides of environment-specific settings.

So I believe this would mean your normal .env would be .env.local and things that you want in your SSH would be .env, without the need for a flag.


问:
Grant access to only one bucket in S3
I´m trying to write a policy to grant a specific user access to only one bucket

this is what I have so far:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::MYBUCKET",
                "arn:aws:s3:::MYBUCKET/*"
            ]
        }
    ]
}
</code>```

I don´t want this user to list all other buckets
so I changed
"Resource": "arn:aws:s3:::*" to "Resource": "arn:aws:s3:::MYBUCKET"
but it didn´t work. I don´t need this user to access the console just programmatically is fine. thank you!!

答:
It is not possible to limit the results of the ListAllMyBuckets command. Either they see the list of all the buckets, or they see none at all.

If they know which bucket they wish to use, then you could simply remove permission to list buckets. They will still be able to list the contents of MYBUCKET and upload/download objects. They just won't be able to request a list of buckets. (And the S3 Management Console won't function because it expects to be able to list all buckets in the account)

Title: Grant access to only one bucket in S3

Body:
I´m trying to write a policy to grant a specific user access to only one bucket

this is what I have so far:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::MYBUCKET",
                "arn:aws:s3:::MYBUCKET/*"
            ]
        }
    ]
}

I don´t want this user to list all other buckets
so I changed
"Resource": "arn:aws:s3:::*" to "Resource": "arn:aws:s3:::MYBUCKET"
but it didn´t work. I don´t need this user to access the console just programmatically is fine. thank you!!


问:
Connect to Azure App Service from Azure VM
I am planning on using an outsourcing team for data processing and want to avoid them downloading or storing client data on their local machines. To facilitate this, I want to create an Azure VM in which they can do all their work (msoft office, etc.) and access an ASP MVC app hosted as an app service in Azure. The MVC app is integrated with the corporate AD and for the outsourcing logins I want to see if the request is coming from my VM or the internet (the latter gets denied). So far I have:

Created a ASP MVC5 app and an Azure VM

Connected the two via VPN (point to site)

When I attempt to go to the public URL for the website on the VM, I get the "this page can't be displayed" thing, which leads me to believe I'm on the right track (now I have to update the hostfile of the machine to the private IP of the mvc app service app?). How do I do the following:

Connect to the app service via web browser (this needs to be over the vnet so that I can pick and choose in the app code who can login outside the network)

Get the network ip of the app service so I can update the VM hostfile

Am I on the right track here? Thanks in advance!

答:
you may want to try using cloud service, though MS recommends App Service, you requirement doesn't fit into App service..

Official documentation from MS: https://learn.microsoft.com/en-us/azure/cloud-services/cloud-services-startup-tasks-common

Block a specific IP address
You can restrict an Azure web role access to a set of specified IP addresses by modifying your IIS web.config file. You also need to use a command file which unlocks the ipSecurity section of the ApplicationHost.config file.


问:
iOS UIImage Binarization for OCR - handling images with varying luminance
I had a C++ binarization routine that I used for later OCR operation.
However I found that it produced unnecessary slanting of text.
Searching for alternatives I found GPUImage of great value and it solved the slanting issue.

I am using GPUImage code like this to binarize my input images before applying OCR.

However the threshold value does not cover the range of images I get.
See two samples from my input images:

I can't handle both with same threshold value.
Low value seems to be fine with later, and higher value is fine with first one.

The second image seems to be of special complexity because I never get all the chars to be binarized right, irrespective of what value I set for threshold. On the other hand, my C++ binarization routine seems to do it right, but I don't have much insights to experiment into it like simplistic threshold value in GPUImage.

How should I handle that?

UPDATE:

I tried with GPUImageAverageLuminanceThresholdFilter with default multiplier = 1. It works fine with first image but the second image continues to be problem.

Some more diverse inputs for binarization:

UPDATE II:

After going through this answer by Brad, tried GPUImageAdaptiveThresholdFilter (also incorporating GPUImagePicture because earlier I was only applying it on UIImage).

With this, I got second image binarized perfect. However first one seems to have lot of noise after binarization when I set blur size is 3.0. OCR results in extra characters added. With lower value of blur size, second image loses precision.

Here it is:

```<code>+(UIImage *)binarize : (UIImage *) sourceImage
{
    UIImage * grayScaledImg = [self toGrayscale:sourceImage];
    GPUImagePicture *imageSource = [[GPUImagePicture alloc] initWithImage:grayScaledImg];
    GPUImageAdaptiveThresholdFilter *stillImageFilter = [[GPUImageAdaptiveThresholdFilter alloc] init];
    stillImageFilter.blurSize = 3.0;

    [imageSource addTarget:stillImageFilter];
    [imageSource processImage];

    UIImage *imageWithAppliedThreshold = [stillImageFilter imageFromCurrentlyProcessedOutput];
  //  UIImage *destImage = [thresholdFilter imageByFilteringImage:grayScaledImg];
    return imageWithAppliedThreshold;
}
</code>```

答:
SWIFT3

SOLUTION 1

```<code>extension UIImage {

func doBinarize() -> UIImage? {

    let grayScaledImg = self.grayImage()
    let imageSource = GPUImagePicture(image: grayScaledImg)
    let stillImageFilter = GPUImageAdaptiveThresholdFilter()
    stillImageFilter.blurRadiusInPixels = 8.0

    imageSource!.addTarget(stillImageFilter)
    stillImageFilter.useNextFrameForImageCapture()
    imageSource!.processImage()

    guard let retImage: UIImage = stillImageFilter.imageFromCurrentFramebuffer(with: UIImageOrientation.up) else {
        print("unable to obtain UIImage from filter")
        return nil
    }

    return retImage
}

func grayImage() -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(self.size, false, 1.0)
    let imageRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)

    self.draw(in: imageRect, blendMode: .luminosity, alpha:  1.0)

    let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return outputImage
}

}
</code>```

The result would be

SOLUTION 2

use GPUImageLuminanceThresholdFilter to achieve 100% black and white effect whithout grey color

```<code>   let stillImageFilter = GPUImageLuminanceThresholdFilter()
   stillImageFilter.threshold = 0.9
</code>```

For example I need to detect flash light and this works for me

Body:
I had a C++ binarization routine that I used for later OCR operation.
However I found that it produced unnecessary slanting of text.
Searching for alternatives I found GPUImage of great value and it solved the slanting issue.

I am using GPUImage code like this to binarize my input images before applying OCR.

However the threshold value does not cover the range of images I get.
See two samples from my input images:

I can't handle both with same threshold value.
Low value seems to be fine with later, and higher value is fine with first one.

The second image seems to be of special complexity because I never get all the chars to be binarized right, irrespective of what value I set for threshold. On the other hand, my C++ binarization routine seems to do it right, but I don't have much insights to experiment into it like simplistic threshold value in GPUImage.

How should I handle that?

UPDATE:

I tried with GPUImageAverageLuminanceThresholdFilter with default multiplier = 1. It works fine with first image but the second image continues to be problem.

Some more diverse inputs for binarization:

UPDATE II:

After going through this answer by Brad, tried GPUImageAdaptiveThresholdFilter (also incorporating GPUImagePicture because earlier I was only applying it on UIImage).

With this, I got second image binarized perfect. However first one seems to have lot of noise after binarization when I set blur size is 3.0. OCR results in extra characters added. With lower value of blur size, second image loses precision.

Here it is:

+(UIImage *)binarize : (UIImage *) sourceImage
{
    UIImage * grayScaledImg = [self toGrayscale:sourceImage];
    GPUImagePicture *imageSource = [[GPUImagePicture alloc] initWithImage:grayScaledImg];
    GPUImageAdaptiveThresholdFilter *stillImageFilter = [[GPUImageAdaptiveThresholdFilter alloc] init];
    stillImageFilter.blurSize = 3.0;

    [imageSource addTarget:stillImageFilter];
    [imageSource processImage];

    UIImage *imageWithAppliedThreshold = [stillImageFilter imageFromCurrentlyProcessedOutput];
  //  UIImage *destImage = [thresholdFilter imageByFilteringImage:grayScaledImg];
    return imageWithAppliedThreshold;
}

Body:
SWIFT3

SOLUTION 1

extension UIImage {

func doBinarize() -> UIImage? {

    let grayScaledImg = self.grayImage()
    let imageSource = GPUImagePicture(image: grayScaledImg)
    let stillImageFilter = GPUImageAdaptiveThresholdFilter()
    stillImageFilter.blurRadiusInPixels = 8.0

    imageSource!.addTarget(stillImageFilter)
    stillImageFilter.useNextFrameForImageCapture()
    imageSource!.processImage()

    guard let retImage: UIImage = stillImageFilter.imageFromCurrentFramebuffer(with: UIImageOrientation.up) else {
        print("unable to obtain UIImage from filter")
        return nil
    }

    return retImage
}

func grayImage() -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(self.size, false, 1.0)
    let imageRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)

    self.draw(in: imageRect, blendMode: .luminosity, alpha:  1.0)

    let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return outputImage
}

}

The result would be

SOLUTION 2

use GPUImageLuminanceThresholdFilter to achieve 100% black and white effect whithout grey color

   let stillImageFilter = GPUImageLuminanceThresholdFilter()
   stillImageFilter.threshold = 0.9

For example I need to detect flash light and this works for me


问:
Method call asks for method as parameter
I'm pretty new to swift so this might be a really simple question, but I am trying to create a method that returns a list upon completion but when I try to call the method, it says I am missing the escaping parameter which I do not know how to satisfy.

Here is the method:

```<code>func fillFromFile(completionBlock: @escaping ([Asset_Content]) -> ()) {
    let url = "URL STRING"

    LoadJSONFile(from: url) { (result) in
        // The code inside this block would be called when LoadJSONFile is completed. this could happen very quickly, or could take a long time

        //.map is an easier way to transform/iterate over an array
        var newContentArray = [Asset_Content]()
        for json in result{
            let category = json["BIGCATEGORY"] as? String
            let diagnosis = json["DIAGNOSIS"] as? String
            let perspective = json["PERSPECTIVE"] as? String
            let name = json["NAME"] as? String
            let title = json["Title"] as? String
            let UnparsedTags = json["TAGS"] as? String
            let filename = json["FILENAME"] as? String

            let tagArray = UnparsedTags?.characters.split(separator: ",")
            for tag in tagArray!{
                if(!self.ListOfTags.contains(String(tag))){
                    self.ListOfTags.append(String(tag))
                }
            }

            let asset = Asset_Content(category!, diagnosis!, perspective!, name!, title!, filename!)
            // This is a return to the map closure. We are still in the LoadJSONFile completion block
            newContentArray.append(asset)

        }
        print("return count ", newContentArray.count)
        // This is the point at which the passed completion block is called.
        completionBlock(newContentArray)
    }
}
</code>```

here is the method call:

```<code>self.ListOfFiles = fillFromFile()
</code>```

and the error is "Missing argument for parameter 'completionblock' in call"

答:
The way you expect the response of a method with completionBlock is like this:

```<code>    fillFromFile { (response) in
        self.ListOfFiles = response
    }
</code>```

Like this you are setting your ´ListOfFiles´ variable, with the new variable that comes in the method.

In the return of your function you should have a DispatchQueue

```<code>DispatchQueue.main.async {
     completionBlock(newContentArray)
}
</code>```

Body:
I'm pretty new to swift so this might be a really simple question, but I am trying to create a method that returns a list upon completion but when I try to call the method, it says I am missing the escaping parameter which I do not know how to satisfy.

Here is the method:

func fillFromFile(completionBlock: @escaping ([Asset_Content]) -> ()) {
    let url = "URL STRING"

    LoadJSONFile(from: url) { (result) in
        // The code inside this block would be called when LoadJSONFile is completed. this could happen very quickly, or could take a long time

        //.map is an easier way to transform/iterate over an array
        var newContentArray = [Asset_Content]()
        for json in result{
            let category = json["BIGCATEGORY"] as? String
            let diagnosis = json["DIAGNOSIS"] as? String
            let perspective = json["PERSPECTIVE"] as? String
            let name = json["NAME"] as? String
            let title = json["Title"] as? String
            let UnparsedTags = json["TAGS"] as? String
            let filename = json["FILENAME"] as? String

            let tagArray = UnparsedTags?.characters.split(separator: ",")
            for tag in tagArray!{
                if(!self.ListOfTags.contains(String(tag))){
                    self.ListOfTags.append(String(tag))
                }
            }

            let asset = Asset_Content(category!, diagnosis!, perspective!, name!, title!, filename!)
            // This is a return to the map closure. We are still in the LoadJSONFile completion block
            newContentArray.append(asset)

        }
        print("return count ", newContentArray.count)
        // This is the point at which the passed completion block is called.
        completionBlock(newContentArray)
    }
}

here is the method call:

self.ListOfFiles = fillFromFile()

and the error is "Missing argument for parameter 'completionblock' in call"

Body:
The way you expect the response of a method with completionBlock is like this:

    fillFromFile { (response) in
        self.ListOfFiles = response
    }

Like this you are setting your ´ListOfFiles´ variable, with the new variable that comes in the method.

In the return of your function you should have a DispatchQueue

DispatchQueue.main.async {
     completionBlock(newContentArray)
}


问:
How to set PKHUD above inputAccessoryView
Is there a way to keep HUD above inputAccessoryView?

See This

答:
If you want to show the HUD above the keyboard you have to do this:

HUD.show(.progress, onView: UIApplication.shared.windows.last)


问:
Move folder but keep preceding structure using shell in CENTOS6.8
I have the following folder structure:

```<code>parent
├── child1
├── child2
└── child3
    └── childofchild
        └── childofchildofchild
            └── file.txt
</code>```

I want to move childofchildofchild into a new folder, but keep the structure preceding it so the end result would be the following:

```<code>newfolder
└── child3
    └── childofchild
        └── childofchildofchild
            └── file.txt
</code>```

Edit: I need the files removed from the original folder, not duplicated.

答:
I don't really understand what are you trying to do, but something as ...?

```<code>mkdir parent/newfolder && mv parent/child3 parent/newfolder
</code>```

I think I'm missing something tho

Body:
I have the following folder structure:

parent
├── child1
├── child2
└── child3
    └── childofchild
        └── childofchildofchild
            └── file.txt

I want to move childofchildofchild into a new folder, but keep the structure preceding it so the end result would be the following:

newfolder
└── child3
    └── childofchild
        └── childofchildofchild
            └── file.txt

Edit: I need the files removed from the original folder, not duplicated.

Body:
I don't really understand what are you trying to do, but something as ...?

mkdir parent/newfolder && mv parent/child3 parent/newfolder

I think I'm missing something tho


问:
Adding, Editing and Deleting data from Datagridview
I'm trying to insert data from a datagridview control into my SQL database. The code is as follows:

Private Sub MCmdSoftwareSave_Click(sender As Object, e As EventArgs) Handles MCmdSoftwareSave.Click
    Dim ID As Integer
    Dim Name, Edition, Version, SubVersion As String
    Try
        SQLcmd.Connection = SQLconn
        SQLconn.Open()
        For row As Integer = 0 To Me.DgdSoftware.Rows.Count - 1
            ID = Me.DgdSoftware.Rows(row).Cells(0).Value
            Name = Me.DgdSoftware.Rows(row).Cells(1).Value
            Edition = Me.DgdSoftware.Rows(row).Cells(2).Value
            Version = Me.DgdSoftware.Rows(row).Cells(3).Value
            SubVersion = Me.DgdSoftware.Rows(row).Cells(4).Value
            SQLcmd.CommandText = "INSERT INTO Software(ID,Name,Edition,Version,SubVersion) VALUES('" & ID & "','" & Name & "','" & Edition & "','" & Version & "','" & SubVersion & "')"
            SQLcmd.ExecuteNonQuery()
        Next
        MsgBox("The infomration was successfully added to the Software database.", MsgBoxStyle.Information, "Successful Operation")
    Catch ex As Exception
        MessageBox.Show(ex.Message)
        SQLconn.Close()
    End Try
End Sub
```

This works when the table is empty, but it also adds another record where the "ID" (Primary key) is 0 and the rest of the fields in that record are null, before adding the desired data.

If I then try to add more data, I get a message saying I cannot add data to the database where the ID of the current record being saved matches that of an ID in the database (i.e. it's trying to re-save the existing data into the table).

What I want to be able to do is load up a form where all the data in the table is loaded into the datagridview control. I then want to be able to add to that table using the same datagridview control by putting in new records, without the code trying to save the existing data. I also want to be able to edit and delete the data in the datagridview control.

Is there any way to do this effectively?

Many thanks,

James

答:
The easiest way I can think of is to have another column in your datagridview which you can think of as an indicator to whether or not the row has already been inserted into your database. Default it to 0, and do a check in the for loop to only insert rows that have a value of 0 for that column and update it to 1 afterwards.

You should also look into using parameterized SQL queries

If you have AllowUserToAddRows set to True, there will be a blank row at the bottom of the datagridview. You can get around this by changing your for loop to go from 0 to Me.DgdSoftware.Rows.Count - 2.

Body:
I'm trying to insert data from a datagridview control into my SQL database. The code is as follows:

Private Sub MCmdSoftwareSave_Click(sender As Object, e As EventArgs) Handles MCmdSoftwareSave.Click
    Dim ID As Integer
    Dim Name, Edition, Version, SubVersion As String
    Try
        SQLcmd.Connection = SQLconn
        SQLconn.Open()
        For row As Integer = 0 To Me.DgdSoftware.Rows.Count - 1
            ID = Me.DgdSoftware.Rows(row).Cells(0).Value
            Name = Me.DgdSoftware.Rows(row).Cells(1).Value
            Edition = Me.DgdSoftware.Rows(row).Cells(2).Value
            Version = Me.DgdSoftware.Rows(row).Cells(3).Value
            SubVersion = Me.DgdSoftware.Rows(row).Cells(4).Value
            SQLcmd.CommandText = "INSERT INTO Software(ID,Name,Edition,Version,SubVersion) VALUES('" & ID & "','" & Name & "','" & Edition & "','" & Version & "','" & SubVersion & "')"
            SQLcmd.ExecuteNonQuery()
        Next
        MsgBox("The infomration was successfully added to the Software database.", MsgBoxStyle.Information, "Successful Operation")
    Catch ex As Exception
        MessageBox.Show(ex.Message)
        SQLconn.Close()
    End Try
End Sub

This works when the table is empty, but it also adds another record where the "ID" (Primary key) is 0 and the rest of the fields in that record are null, before adding the desired data.

If I then try to add more data, I get a message saying I cannot add data to the database where the ID of the current record being saved matches that of an ID in the database (i.e. it's trying to re-save the existing data into the table).

What I want to be able to do is load up a form where all the data in the table is loaded into the datagridview control. I then want to be able to add to that table using the same datagridview control by putting in new records, without the code trying to save the existing data. I also want to be able to edit and delete the data in the datagridview control.

Is there any way to do this effectively?

Many thanks,

James


问:
How to show selected part of website to iframe?
I want to show this part from this website into iframe but have a issues with it. I used this code to get it:

```<code><div style="overflow: hidden; margin: 15px auto; max-width: 575px;">
<iframe scrolling="no" src="https://www.betrush.com/verified/"
style="border: 0px none; margin-left: -96px; height: 1200px; margin-top:
-486px; width: 650px;">
</iframe>
</div>
</code>```

So my question is how to modify my iframe settings to get this part of that website.

答:
You have two options:

Utilise a BetRush API to extract just a segment of their page data. This is by far the easier and more preferable option.

Assuming they don't have an API, your only alternative is to load the entire website, and then use JavaScript to extract the segments that you wish to display:

function loadDoc(target) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;

      var doc = document.getElementById('iframe').contentWindow.document;
      doc.open();
      doc.write(this.responseText);
      doc.close();

    }
  };
  xhttp.open("GET", target, true);
  xhttp.send();
}

loadDoc("http://www.example.com");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe id="iframe"></iframe></code>```

The content is saved as this.reponseText. You'll need to extract data from that based on what you get returned from the website, and then write that to the  with doc.write();.

Having said that, the target also needs to allow scraping. Unfortunately, it would seem as though BetRush has Access-Control-Allow-Origin disabled, meaning that you cannot scrape their site. Therefore, you cannot load part of their website in this way.

Considering BetRush doesn't appear to have an API, and don't allow you to scrape their website, you cannot extract part of their site for inclusion within an iframe.

Hope this helps! :)

Body:
I want to show this part from this website into iframe but have a issues with it. I used this code to get it:

So my question is how to modify my iframe settings to get this part of that website.

Body:
You have two options:

Utilise a BetRush API to extract just a segment of their page data. This is by far the easier and more preferable option.

Assuming they don't have an API, your only alternative is to load the entire website, and then use JavaScript to extract the segments that you wish to display:

function loadDoc(target) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;

      var doc = document.getElementById('iframe').contentWindow.document;
      doc.open();
      doc.write(this.responseText);
      doc.close();

    }
  };
  xhttp.open("GET", target, true);
  xhttp.send();
}

loadDoc("http://www.example.com");

<iframe id="iframe"></iframe>

The content is saved as this.reponseText. You'll need to extract data from that based on what you get returned from the website, and then write that to the <iframe> with doc.write();.

Having said that, the target also needs to allow scraping. Unfortunately, it would seem as though BetRush has Access-Control-Allow-Origin disabled, meaning that you cannot scrape their site. Therefore, you cannot load part of their website in this way.

Considering BetRush doesn't appear to have an API, and don't allow you to scrape their website, you cannot extract part of their site for inclusion within an iframe.

Hope this helps! :)


问:
enable_shared_from_this and inheritance
I've got a type which inherits from enable_shared_from_this<type>, and another type that inherits from this type. Now I can't use the shared_from_this method because it returns the base type and in a specific derived class method I need the derived type. Is it valid to just construct a shared_ptr from this directly?

Edit:
In a related question, how can I move from an rvalue of type shared_ptr<base> to a type of shared_ptr<derived>? I used dynamic_cast to verify that it really was the correct type, but now I can't seem to accomplish the actual move.

答:
Once you obtain the shared_ptr<Base>, you can use static_pointer_cast to convert it to a shared_ptr<Derived>.

You can't just create a shared_ptr directly from this; that would be equivalent to:

```<code>shared_ptr<T> x(new T());
shared_ptr<T> y(x.get()); // now you have two separate reference counts
</code>```

ContentLicense: CC BY-SA 2.5

Title: enable_shared_from_this and inheritance

Body:
Once you obtain the shared_ptr<Base>, you can use static_pointer_cast to convert it to a shared_ptr<Derived>.

You can't just create a shared_ptr directly from this; that would be equivalent to:

shared_ptr<T> x(new T());
shared_ptr<T> y(x.get()); // now you have two separate reference counts


问:
Optional file with retrofit Android
I have a android app when I post 4 params: name, description image 1 and image 2, but image 1 and image 2 are optionals.

With retrofit post ok when I sent all params, but when I sent only name and description and retrofit said "Multipart body must have at least one part."

Please help

答:
You're use the @multipart annotation, which forces you to send at least one part !

you can use two methods instead of that:

first:

void method (int id, String name, String description){}

second:

@multipart
 void method2 (int id, Part image1, Part image2){}

Title: Optional file with retrofit Android


问:
Need help to create sql query MySQLi PHP
I have two tables
COMPANY: company_id, company_name
REVIEW: review_id, company_id, review_text

I am trying to make search functional on site. I try to display all reviews of specific company. Example, I have search field, I enter there "Microsoft" and then I need all reviews about Microsoft.

I try to do such query, but it is not working

```<code>            $company_name = $_POST["company_name"] ?? '';
            $review_text = $_POST["review_text"] ?? '';
            $searchc = $_POST["searchc"] ?? '';

            if(isset($_POST['show'])){
                $result2 = $mysqli->prepare(
                    "SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (HERE I THINK I NEED EMBED QUERY... BUT NOT SURE..) ?");
                $result2->bind_param("s", $searchc);
                $result2->execute();
                $result2->store_result();
                $row2 = mysqli_fetch_assoc($result2);
            }

            <div class="right">
                <form method="post">
                    <br/>
                    <input name="searchc" type="text" value=""><br/>
                    <input type="submit" value="show" name="show">

                  </form>

                    Text: <?=$row2['review_text']?><br />
            </div>
</code>```

答:
Try this:

```<code>SELECT
    REVIEW.*, COMPANY.company_name
FROM
    REVIEW
INNER JOIN COMPANY ON REVIEW.company_id = COMPANY.company_id
WHERE
    COMPANY.company_name = "$search";
</code>```

Results with $search = 'Apple':

```<code>"4" "2" "Apple Review 1"    "Apple"
"5" "2" "Apple Review 2"    "Apple"
"6" "2" "Apple Review 3"    "Apple"
</code>```

Try this:

```<code>SELECT
    REVIEW.*, COMPANY.company_name
FROM
    REVIEW
INNER JOIN COMPANY ON REVIEW.company_id = COMPANY.company_id
WHERE
    COMPANY.company_name = "$search";
</code>```

Results with $search = 'Apple':

```<code>"4" "2" "Apple Review 1"    "Apple"
"5" "2" "Apple Review 2"    "Apple"
"6" "2" "Apple Review 3"    "Apple"
</code>```

EDIT 1:
I use PostgreSQL, the only difference in what I am going to show you, is when you create the tables and insert the data. The SQL statement to do what you need is the same.

First, create the 2 tables company and review

```<code>CREATE TABLE company
(
  company_id integer NOT NULL,
  company_name character varying(255) NOT NULL,
  CONSTRAINT company_pkey PRIMARY KEY (company_id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE company
  OWNER TO postgres;
</code>```

And review table:

```<code>CREATE TABLE review
(
  review_id integer NOT NULL,
  company_id integer NOT NULL,
  review_text character varying(255),
  CONSTRAINT review_pkey PRIMARY KEY (review_id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE review
  OWNER TO postgres;
</code>```

After having created the tables, insert data in them. For your problem I use the following...

```<code>Company Table:
-----------------------------
company_id  |   company_name
-----------------------------
|   1       |   Microsoft   |
|   2       |   Apple       |
|   3       |   NASA        |
-----------------------------
</code>```

And review table:

```<code>-----------------------------------------------------
review_id   |   company_id  |   review_text         |
----------------------------|------------------------
|   1       |   1           |   Microsoft Review 1  |
|   2       |   1           |   Microsoft Review 2  |
|   3       |   1           |   Microsoft Review 3  |
|   4       |   2           |   Apple Review 1      |
|   5       |   2           |   Apple Review 2      |
|   6       |   2           |   Apple Review 3      |
|   7       |   3           |   NASA Review 1       |
|   8       |   3           |   NASA Review 2       |
|   9       |   3           |   NASA Review 3       |
-----------------------------------------------------
</code>```

After this, you can check the output of the following SQL statement with your SQL administrator (Navicat, MySQL Workbench or whatever you use) ...
New SQL query and you write:

```<code>SELECT
    review.*, company.company_name
FROM
    review
INNER JOIN company ON review.company_id = company.company_id
WHERE
    company.company_name = 'Apple';
</code>```

and the output will be...

```<code>---------------------------------------------------------------------
review_id   |   company_id  |   review_text         |   company_name|
---------------------------------------------------------------------
|"4"        |   "2"         |   "Apple Review 1"    |"Apple"        |
|"5"        |   "2"         |   "Apple Review 2"    |"Apple"        |
|"6"        |   "2"         |   "Apple Review 3"    |"Apple"        |
---------------------------------------------------------------------
</code>```

To use that SQL statement in your PHP code, it is simple ...

```<code>$result2 = $mysqli->prepare("SELECT
    review.*, company.company_name
FROM
    review
INNER JOIN company ON review.company_id = company.company_id
WHERE
    company.company_name = $company_name");
</code>```

....

Body:
I have two tables
COMPANY: company_id, company_name
REVIEW: review_id, company_id, review_text

I am trying to make search functional on site. I try to display all reviews of specific company. Example, I have search field, I enter there "Microsoft" and then I need all reviews about Microsoft.

I try to do such query, but it is not working

            $company_name = $_POST["company_name"] ?? '';
            $review_text = $_POST["review_text"] ?? '';
            $searchc = $_POST["searchc"] ?? '';

            if(isset($_POST['show'])){
                $result2 = $mysqli->prepare(
                    "SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (HERE I THINK I NEED EMBED QUERY... BUT NOT SURE..) ?");
                $result2->bind_param("s", $searchc);
                $result2->execute();
                $result2->store_result();
                $row2 = mysqli_fetch_assoc($result2);
            }

                <form method="post">

                    <input name="searchc" type="text" value="">

                    <input type="submit" value="show" name="show">

                  </form>

                    Text: <?=$row2['review_text']?>

Body:
Try this:

SELECT
    REVIEW.*, COMPANY.company_name
FROM
    REVIEW
INNER JOIN COMPANY ON REVIEW.company_id = COMPANY.company_id
WHERE
    COMPANY.company_name = "$search";

Results with $search = 'Apple':

"4" "2" "Apple Review 1"    "Apple"
"5" "2" "Apple Review 2"    "Apple"
"6" "2" "Apple Review 3"    "Apple"

Try this:

SELECT
    REVIEW.*, COMPANY.company_name
FROM
    REVIEW
INNER JOIN COMPANY ON REVIEW.company_id = COMPANY.company_id
WHERE
    COMPANY.company_name = "$search";

Results with $search = 'Apple':

"4" "2" "Apple Review 1"    "Apple"
"5" "2" "Apple Review 2"    "Apple"
"6" "2" "Apple Review 3"    "Apple"

EDIT 1:
I use PostgreSQL, the only difference in what I am going to show you, is when you create the tables and insert the data. The SQL statement to do what you need is the same.

First, create the 2 tables company and review

CREATE TABLE company
(
  company_id integer NOT NULL,
  company_name character varying(255) NOT NULL,
  CONSTRAINT company_pkey PRIMARY KEY (company_id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE company
  OWNER TO postgres;

And review table:

CREATE TABLE review
(
  review_id integer NOT NULL,
  company_id integer NOT NULL,
  review_text character varying(255),
  CONSTRAINT review_pkey PRIMARY KEY (review_id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE review
  OWNER TO postgres;

After having created the tables, insert data in them. For your problem I use the following...

Company Table:
-----------------------------
company_id  |   company_name
-----------------------------
|   1       |   Microsoft   |
|   2       |   Apple       |
|   3       |   NASA        |
-----------------------------

And review table:

-----------------------------------------------------
review_id   |   company_id  |   review_text         |
----------------------------|------------------------
|   1       |   1           |   Microsoft Review 1  |
|   2       |   1           |   Microsoft Review 2  |
|   3       |   1           |   Microsoft Review 3  |
|   4       |   2           |   Apple Review 1      |
|   5       |   2           |   Apple Review 2      |
|   6       |   2           |   Apple Review 3      |
|   7       |   3           |   NASA Review 1       |
|   8       |   3           |   NASA Review 2       |
|   9       |   3           |   NASA Review 3       |
-----------------------------------------------------

After this, you can check the output of the following SQL statement with your SQL administrator (Navicat, MySQL Workbench or whatever you use) ...
New SQL query and you write:

SELECT
    review.*, company.company_name
FROM
    review
INNER JOIN company ON review.company_id = company.company_id
WHERE
    company.company_name = 'Apple';

and the output will be...

---------------------------------------------------------------------
review_id   |   company_id  |   review_text         |   company_name|
---------------------------------------------------------------------
|"4"        |   "2"         |   "Apple Review 1"    |"Apple"        |
|"5"        |   "2"         |   "Apple Review 2"    |"Apple"        |
|"6"        |   "2"         |   "Apple Review 3"    |"Apple"        |
---------------------------------------------------------------------

To use that SQL statement in your PHP code, it is simple ...

$result2 = $mysqli->prepare("SELECT
    review.*, company.company_name
FROM
    review
INNER JOIN company ON review.company_id = company.company_id
WHERE
    company.company_name = $company_name");

....


问:
Missing methods in Python class inheritance?
I am not very experienced with class inheritance. Please help me and have a look at the code below:

```<code>class Handle(STAFHandle):

    def __init__(self, HandleName):
        handle = STAFHandle.__init__(self, HandleName)
        self.initLogger(handle)

    def initLogger(self, handle):
        self.logger = Logging(handle, 'Test')

handle = Handle('test')
handle.logger.info('test')
</code>```

it says submit method is not defined:

```<code>result = handle.submit(system, service, logRequest)
AttributeError: 'NoneType' object has no attribute 'submit'
</code>```

but if I change it to:

```<code>class Handle(STAFHandle):
    def __init__(self, HandleName):
        handle = STAFHandle.__init__(self, HandleName)

    def initLogger(self, handle):
        self.logger = Logging(handle, 'Test')

handle = Handle('test')
handle.initLogger(handle)
handle.logger.info('test')
</code>```

it works. Why there is a difference? Thanks a lot!!

Cheers,
Zhe

答:
STAFHandle.__init__ returns None. You probably want:

```<code>class Handle(STAFHandle):
    def __init__(self, handle_name):
        super(Handle, self).__init__(handle_name)
        self.initLogger()

    def initLogger(self):
        self.logger = Logging(self, 'Test')

handle = Handle('test')
</code>```

Remember that __init__ methods take as their first argument an object, and modify that object. So when you call super(Handle, self).__init__(handleName) you are changing the properties of self instead of returning a new object. The difference between your two examples is that the variable handle in the two calls to initLogger refers to different things.

Notice that I have replaced the explicit STAFHandle.__init__ call with a super proxy; this is equivalent in this case but allows for more flexibility, since you can now change the inheritance of the class without breaking its __init__.

I've also changed HandleName to handle_name to conform with Python conventions (CamelCase refers to classes).

Body:
I am not very experienced with class inheritance. Please help me and have a look at the code below:

class Handle(STAFHandle):

    def __init__(self, HandleName):
        handle = STAFHandle.__init__(self, HandleName)
        self.initLogger(handle)

    def initLogger(self, handle):
        self.logger = Logging(handle, 'Test')

handle = Handle('test')
handle.logger.info('test')

it says submit method is not defined:

result = handle.submit(system, service, logRequest)
AttributeError: 'NoneType' object has no attribute 'submit'

but if I change it to:

class Handle(STAFHandle):
    def __init__(self, HandleName):
        handle = STAFHandle.__init__(self, HandleName)

    def initLogger(self, handle):
        self.logger = Logging(handle, 'Test')

handle = Handle('test')
handle.initLogger(handle)
handle.logger.info('test')

it works. Why there is a difference? Thanks a lot!!

Cheers,
Zhe

Body:
STAFHandle.__init__ returns None. You probably want:

class Handle(STAFHandle):
    def __init__(self, handle_name):
        super(Handle, self).__init__(handle_name)
        self.initLogger()

    def initLogger(self):
        self.logger = Logging(self, 'Test')

handle = Handle('test')

Remember that __init__ methods take as their first argument an object, and modify that object. So when you call super(Handle, self).__init__(handleName) you are changing the properties of self instead of returning a new object. The difference between your two examples is that the variable handle in the two calls to initLogger refers to different things.

Notice that I have replaced the explicit STAFHandle.__init__ call with a super proxy; this is equivalent in this case but allows for more flexibility, since you can now change the inheritance of the class without breaking its __init__.

I've also changed HandleName to handle_name to conform with Python conventions (CamelCase refers to classes).


问:
Easy way to do port translation to bypass our own firewall
so I have 0% experience with web programming, and the project I am working on doesn't have anything to do with it, but I hit a small roadblock and need to solve a small port problem.

So we want to build a cluster of GPU machines on Azure for some Deep Learning calculations, and want to install some applications on them and let our scientists use the app' GUIs to launch and monitor their jobs. The problem is that an app A for example runs on port 5050, but our firewall doesn't let us communicate to unusual ports. The problem is easy to fix from the Azure side, but our IT team won't let us modify our security policies.

That's why I need to find a hacky and fast solution to overcome this, I don't want to spend my whole internship doing something complicated for it, just something that does the job.

What I thought about was to have some kind of server running on the machines (let's say Machine A has public IP address ipbA and private IP ipvA) that when we type "http://ipba/app1" on our browser, the server on A will fetch the page "http://ipva:5050" (or "----://ipba/app2" -> "----://ipva:5051") and display it, but does this work if the page needs to be interactive because we would like to launch jobs?

I have no clue how to do this, if you could please just tell me what I should look into, google and read about, or if there is an easier way to handle it, (maybe some VPN stuff, which I don't prefer since we're moving towards a hybrid cloud architecture and I don't think we would want to VPN into all the different cloud platforms) that would be awesome :)

答:
Two common solutions for your problem:

Set-up a reverse proxy on a standard port (such as 80 or 443 if you want some SSL certificates headaches).

All your domain names will point to the reverse proxy (single IP) but the reverse proxy will forward the traffic transparently to the real servers on their special ports.

https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html

https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension

For the technical details, in short: you keep in file(s) the configuration for each domain or subdomain and where they should be forwarded.

Chain of events:

User types http://interface-1.company.com

Browser resolves interface-1.company.com (DNS: IP Reverse Proxy)

Browser connects on reverse proxy (port 80)

Reverse proxy reads configuration which says where to forward

Proxy forwards request to realserver.company.com:5050

Realserver relays response to reverse proxy

reverse proxy relays response to browser

I think that is what you are trying to achieve.

Set-up a VPN service which will be connectible through the proxy of your company and provide VPN clients to the end-users. OpenVPN clients can use an HTTPS proxy connection (your company proxy) to establish connexion to a remote VPN.

Once connected on the VPN, everyone uses the VPN's IP address + firewall policy, and are therefore no more restricted by the company's firewalling policy. Any kind of traffic can also be forwarded. This is harder to set up and your security team might not accept it. However, it's a fully functional solution and it can also offer additional security features if implemented properly.

I do not recommend going this way for all the paperwork that would involve.


问:
Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)
I am using SQL Server 2008 R2. It is working fine. But recently, I have changed my hosting server and I came to know that they have installed SQL Server 2012 on Server.

Now, Issue is that after connecting with Server Database through SQL Server 2008 R2, When I click on any table name or Stored Procedure, I am getting error : Index was outside the bounds of the array. (Microsoft.SqlServer.smo)

So, is there any issue from my side or It is from Server Side ??? and How can I prevent this issue ?

答:
Restarted worked!
I found the same error to add new table to my database diagram on sql server 2016, restarted sql server management studio, finally solved.</p>


问:
SQL OrderBy two columns as one
I have a table that has two columns: Height and Width

What is the easiest way to sort this table incrementally based on either Height or Width

In other words, it would pick the smallest value from Height and Width for each row and sort it based on this number?

Thanks in advance!

答:
You can use a case statement in your order by clause like this:</p>

```<code>select *
from table
order by
   case when Width > Height then Height else Width end,
   case when Width > Height then Width else Height end
</code>```

Title: SQL OrderBy two columns as one

Body:
You can use a case statement in your order by clause like this:

select *
from table
order by
   case when Width > Height then Height else Width end,
   case when Width > Height then Width else Height end


问:
R ggplot: geomsmooth 95% CI instead of standard error
I have created the following plot:

But the geom_smooth now displays the standard errors, but I would like to 95% CI around the lines. Is there an easy fix for this?

I used the following code:

```<code>MMSEmodel <- (lmer(MMSE~ Age + Eduy + Gender + study +     DateMMSE*AMYLOID_BL*BL_Diaggroups + (1 + DateMMSE|study), seleduy)

fitMMSE <- fitted(MMSEmodel)

MMSEplot <- qplot(DateMMSE, fitMMSE, data=seleduy, geom=c("smooth"), method="glm", color=BL_Diaggroups, linetype=AMYLOID_BL, fill=BL_Diaggroups)+ theme_classic() + xlab("Time (years)") + ylab("MMSE") + scale_x_continuous(expand=c(0,0)) +  coord_cartesian(xlim = c(0,4), ylim = c(15,30)) + scale_color_manual(values=c("#339900", "#FF6600", "#0000CC")) + scale_fill_manual(values=c("#66CC66", "#FF9966", "#3366FF")) + scale_linetype(guide_legend(title = "Amyloid status")) + guides(lty = guide_legend(override.aes = list(col = 'black')))
</code>```

Thanks!

答:
From ggplot2 documentation for stat_smooth :

se

  display confidence interval around smooth? (TRUE by default, see level to control

Since in your code I don't see any arguments to overwrite the default settings- the se bands show the 95% confidence interval. To change these to say 90% or 99% etc look up level

Body:
I have created the following plot:

But the geom_smooth now displays the standard errors, but I would like to 95% CI around the lines. Is there an easy fix for this?

I used the following code:

MMSEmodel <- (lmer(MMSE~ Age + Eduy + Gender + study +     DateMMSE*AMYLOID_BL*BL_Diaggroups + (1 + DateMMSE|study), seleduy)

fitMMSE <- fitted(MMSEmodel)

MMSEplot <- qplot(DateMMSE, fitMMSE, data=seleduy, geom=c("smooth"), method="glm", color=BL_Diaggroups, linetype=AMYLOID_BL, fill=BL_Diaggroups)+ theme_classic() + xlab("Time (years)") + ylab("MMSE") + scale_x_continuous(expand=c(0,0)) +  coord_cartesian(xlim = c(0,4), ylim = c(15,30)) + scale_color_manual(values=c("#339900", "#FF6600", "#0000CC")) + scale_fill_manual(values=c("#66CC66", "#FF9966", "#3366FF")) + scale_linetype(guide_legend(title = "Amyloid status")) + guides(lty = guide_legend(override.aes = list(col = 'black')))

Thanks!


问:
JxBrowser - How to react on a HTML-button click in a Kiosk app without mouse-events
I want to use the JxBrowser in my Kiosk-app (based on Swing). Through its nature, no external-mouse and -keyboard are available. But I want to receive an event, if someone is clicking on a (HTML-) button at a specific website.

Originally, I have used the mouse-listener at the browser-view to receive these events. On my Mac (with an external-mouse) I received the mouse-events, but on my terminal (without an external-mouse) I do not receive any mouse-events from the browser-view. I thought that touch-events are handled like mouse-events - but unfortunately this is not the case.

I tried other event-types but without success. I also tried to add a (transparent) JButton to the browser-view. It was displayed full-screen at top of the browser-view, but without transparency.

Are there any other possibilities to receive such an event?

答:
In general you need to follow these steps:

Wait until a web page is loaded - listen to browser load events:
browser.addLoadListener(new YourLoadAdapter()

Search for all clickable HTML elements on the page (links, buttons, ...), use simple DOM API or more complex XPath expression:

List<DOMElement> hyperlinks = document.findElements(By.tagName("a"));

Attach a listener on each of them:

element.addEventListener(DOMEventType.OnClick, new YourDOMEventListener());

I used JxBrowser for a very similar application a few years ago, on that time the JxBrowser was based on Mozilla. And based on that experience I'm not a big fan of embedding external web browser into Java application.  The same behaviour can be implemented as standard Chrome app or extension with less maintenance problems and unexpected behaviour.


问:
Redux saga typescript type error in yield all
I'm trying very simple example from redux-saga page.

```<code>function* saga(): SagaIterator {
  yield takeEvery(T.GET_CREDENTIALS, getCredentials);
}

export default function* rootSaga() {
  yield all([
    saga(),
  ]);
}
</code>```

But I get typescript error:

```<code>Argument of type 'IterableIterator<RootEffect | TakeEffect |
ChannelTakeEffect<any> | PutEffect<any> | ChannelPutEf...' is not
assignable to parameter of type '{ [key: string]: Effect; }'.
Index signature is missing in type 'IterableIterator<RootEffect |
TakeEffect | ChannelTakeEffect<any> | PutEffect<any> |
ChannelPutEf...'.
</code>```

What I'm doing wrong? Thanks for help

答:
Since links to solutions apparently get downvoted, this is the solution:</p>

```<code>export default function* rootSaga() {
  yield all([
    call(saga()),
  ]);
}
</code>```

Body:
I'm trying very simple example from redux-saga page.

function* saga(): SagaIterator {
  yield takeEvery(T.GET_CREDENTIALS, getCredentials);
}

export default function* rootSaga() {
  yield all([
    saga(),
  ]);
}

But I get typescript error:

Argument of type 'IterableIterator<RootEffect | TakeEffect |
ChannelTakeEffect<any> | PutEffect<any> | ChannelPutEf...' is not
assignable to parameter of type '{ [key: string]: Effect; }'.
Index signature is missing in type 'IterableIterator<RootEffect |
TakeEffect | ChannelTakeEffect<any> | PutEffect<any> |
ChannelPutEf...'.

What I'm doing wrong? Thanks for help

Body:
Since links to solutions apparently get downvoted, this is the solution:

export default function* rootSaga() {
  yield all([
    call(saga()),
  ]);
}


问:
Clojure change object item
I am  new in Clojure. I need found the item in file, change value and save, but I cant change value. I need make a new copy of array?

File:

```<code>{:name "John", :index 0}
{:name "Ivan", :index 1}
{:name "Niki", :index 2}
</code>```

Code:

```<code>(ns test1.core
  (:gen-class))

(use 'clojure.java.io)
(require '[clojure.string :as str])

(def file-data "names.txt")

(def findName "Ivan")

(defn write-data[xs, file]
  (with-open [wrtr (writer file)]
       (doall (map #(.write wrtr (str % "\n")) xs))))

(defn read-data[file]
  (with-open [rdr (reader file)]
       (doall (map #(load-string %) (line-seq rdr)))))

(defn -main []

  (def data (read-data file-data))

  (doseq [line data]
    (if (= (line :name) findName)
      (update-in line [:index] inc)
        (println "No")))
  (println data))
</code>```

答:
Your code is not changing data in any way, which is good because it is immutable and can't be changed anyway. Try wrapping a a call to write-data around your update-in form.

One small thing as well: data should go outside of -main.

Title: Clojure change object item

Body:
I am  new in Clojure. I need found the item in file, change value and save, but I cant change value. I need make a new copy of array?

File:

{:name "John", :index 0}
{:name "Ivan", :index 1}
{:name "Niki", :index 2}

Code:

(ns test1.core
  (:gen-class))

(use 'clojure.java.io)
(require '[clojure.string :as str])

(def file-data "names.txt")

(def findName "Ivan")

(defn write-data[xs, file]
  (with-open [wrtr (writer file)]
       (doall (map #(.write wrtr (str % "\n")) xs))))

(defn read-data[file]
  (with-open [rdr (reader file)]
       (doall (map #(load-string %) (line-seq rdr)))))

(defn -main []

  (def data (read-data file-data))

  (doseq [line data]
    (if (= (line :name) findName)
      (update-in line [:index] inc)
        (println "No")))
  (println data))


问:
Pygame 'groupcollide'?
Below is part of my code for a 'Tetris' game.

What I want to do is simply to make the bottom of the falling shape equal in height(-1) to the top of the static shape, on collision. However, as it is, I can only set the contact position as the bottom of the moving shape; resulting in it appearing to sink into the shape it collides with (which throws off the whole 'block' illusion).

```<code>    stick = pygame.sprite.groupcollide(pieces_mobs, static_mobs, False, False, pygame.sprite.collide_mask)
</code>```

This is what I'm currently using because I'm not sure of how to access the second value in a 'groupcollide' tuple -

```<code>for piece in pieces_mobs:
    for instance in stick:
        contact = instance.rect.bottom
        instance.static(contact)
    piece.update()
</code>```

This is the logic I want -

```<code>for piece in pieces_mobs:
    for pieces, static in stick:
        contact = static.rect.top
        pieces.static(contact)
    piece.update()
</code>```

Probably really simple, but I just can't find any examples.

答:
As per pygame documentation, the output of groupcollide is a dictionary with the key being a sprite from the first group and the value a list of all the sprites from second group the key sprite is colliding with. So to achieve your goal:</p>

```<code>stick = pygame.sprite.groupcollide(pieces_mobs, static_mobs, False, False, pygame.sprite.collide_mask)

for piece_mob, static_mob in stick.items():
    piece_mob.rect.bottom = static_mob[0].rect.top
</code>```

Title: Pygame 'groupcollide'?

Body:
Below is part of my code for a 'Tetris' game.

What I want to do is simply to make the bottom of the falling shape equal in height(-1) to the top of the static shape, on collision. However, as it is, I can only set the contact position as the bottom of the moving shape; resulting in it appearing to sink into the shape it collides with (which throws off the whole 'block' illusion).

    stick = pygame.sprite.groupcollide(pieces_mobs, static_mobs, False, False, pygame.sprite.collide_mask)

This is what I'm currently using because I'm not sure of how to access the second value in a 'groupcollide' tuple -

for piece in pieces_mobs:
    for instance in stick:
        contact = instance.rect.bottom
        instance.static(contact)
    piece.update()

This is the logic I want -

for piece in pieces_mobs:
    for pieces, static in stick:
        contact = static.rect.top
        pieces.static(contact)
    piece.update()

Probably really simple, but I just can't find any examples.

Body:
As per pygame documentation, the output of groupcollide is a dictionary with the key being a sprite from the first group and the value a list of all the sprites from second group the key sprite is colliding with. So to achieve your goal:

stick = pygame.sprite.groupcollide(pieces_mobs, static_mobs, False, False, pygame.sprite.collide_mask)

for piece_mob, static_mob in stick.items():
    piece_mob.rect.bottom = static_mob[0].rect.top


问:
MySQL Join horizontal with vertical table
I have the following structure:

```<code>CREATE TABLE person {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    email VARCHAR(30) NOT NULL UNIQUE
}

CREATE TABLE field {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL
}

CREATE TABLE fieldPerson {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    fieldId INT(11) UNSIGNED,
    personId INT(11) UNSIGNED,
    value VARCHAR(30) NOT NULL,
    FOREIGN KEY (fieldId) REFERENCES field(id),
    FOREIGN KEY (personId) REFERENCES person(id)
}
</code>```

This is well summed up. Basically we have the default fields name and email, and we have the option to create custom fields, such as telephone, address, etc.
We can have n fields. I'm trying to figure out a way to do a SELECT query that returns all fields without making use of subqueries or extra work outside the database (it's ok using joins though).

Example (telephone is a custom field):

```<code>TABLE person:

id    name       email
1     Test 1     test1@gmail.com

----

TABLE field:

id    name
1     telephone
2     address

----

TABLE fieldPerson:

id    fieldId    personId    value
1     1          1           +1 555 555 555
2     2          1           First St.

----

RESULTING QUERY

personId   name          email            telephone       Address
1          Test 1        test1@gmail.com  +1 555 555 555  First St.
</code>```

Is that possible?

Thanks.

EDIT:

If not possible, you may suggest a optimal solution using subqueries, only with SQL though.

答:
So, depending on how much control you have over the query generation, if you can generate the SELECT columns in the same order as the PRIMARY KEY of field, you could try the following. I'm envisioning something where you know there's 2 keys in field, and what they are in advance (from an earlier query?).

```<code>SELECT fp.personId,p.name,p.email,fp.value as telephone,fp2.value as Address
    FROM fieldPerson fp INNER JOIN person p ON p.id = fp.personId
                        INNER JOIN field f ON f.id = fp.fieldId
                        INNER JOIN fieldPerson fp2
    WHERE fp.fieldId = 1 and fp2.fieldId = 2;
</code>```

This gives me the result, given the sample data in the question:

```<code>personId | name   | email           | telephone      | Address   |
       1 | Test 1 | test1@gmail.com | +1 555 555 555 | First St. |
</code>```

This hinges on the notion that you've avoided the sub-query by doing an initial query earlier to know the arbitrary fields defined in the fields table. You didn't specify how dynamic this table is expected to be, so this may not be an unreasonable simplifying assumption to make.

Barring that, you can try something like:

```<code>SELECT fp.personId,p.name,p.email,fp.value as telephone,fp2.value as Address
    FROM fieldPerson fp INNER JOIN person p ON p.id = fp.personId
                        INNER JOIN field f ON f.id = fp.fieldId
                        INNER JOIN fieldPerson fp2
    WHERE fp.fieldId != fp2.fieldId LIMIT 1,1;
</code>```

This gives me the same output without having to know the field id numbers, but I do need to know the names of the fields to generate the column names. The LIMIT is there to remove one of the JOIN products, and has a distinctly unholy feeling to it, I agree. I feel like there's not too much advantage to approach 2, since you have to know the column names anyways.

I would agree with @Mojtaba, however, that if you can't live with a pre-query to know the dynamic field names and ids, then I believe you're going to have to put sub-SELECT statements in there to pull those at query time.

Body:
I have the following structure:

CREATE TABLE person {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    email VARCHAR(30) NOT NULL UNIQUE
}

CREATE TABLE field {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL
}

CREATE TABLE fieldPerson {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    fieldId INT(11) UNSIGNED,
    personId INT(11) UNSIGNED,
    value VARCHAR(30) NOT NULL,
    FOREIGN KEY (fieldId) REFERENCES field(id),
    FOREIGN KEY (personId) REFERENCES person(id)
}

This is well summed up. Basically we have the default fields name and email, and we have the option to create custom fields, such as telephone, address, etc.
We can have n fields. I'm trying to figure out a way to do a SELECT query that returns all fields without making use of subqueries or extra work outside the database (it's ok using joins though).

Example (telephone is a custom field):

TABLE person:

id    name       email
1     Test 1     test1@gmail.com

----

TABLE field:

id    name
1     telephone
2     address

----

TABLE fieldPerson:

id    fieldId    personId    value
1     1          1           +1 555 555 555
2     2          1           First St.

----

RESULTING QUERY

personId   name          email            telephone       Address
1          Test 1        test1@gmail.com  +1 555 555 555  First St.

Is that possible?

Thanks.

EDIT:

If not possible, you may suggest a optimal solution using subqueries, only with SQL though.

Body:
So, depending on how much control you have over the query generation, if you can generate the SELECT columns in the same order as the PRIMARY KEY of field, you could try the following. I'm envisioning something where you know there's 2 keys in field, and what they are in advance (from an earlier query?).

SELECT fp.personId,p.name,p.email,fp.value as telephone,fp2.value as Address
    FROM fieldPerson fp INNER JOIN person p ON p.id = fp.personId
                        INNER JOIN field f ON f.id = fp.fieldId
                        INNER JOIN fieldPerson fp2
    WHERE fp.fieldId = 1 and fp2.fieldId = 2;

This gives me the result, given the sample data in the question:

personId | name   | email           | telephone      | Address   |
       1 | Test 1 | test1@gmail.com | +1 555 555 555 | First St. |

This hinges on the notion that you've avoided the sub-query by doing an initial query earlier to know the arbitrary fields defined in the fields table. You didn't specify how dynamic this table is expected to be, so this may not be an unreasonable simplifying assumption to make.

Barring that, you can try something like:

SELECT fp.personId,p.name,p.email,fp.value as telephone,fp2.value as Address
    FROM fieldPerson fp INNER JOIN person p ON p.id = fp.personId
                        INNER JOIN field f ON f.id = fp.fieldId
                        INNER JOIN fieldPerson fp2
    WHERE fp.fieldId != fp2.fieldId LIMIT 1,1;

This gives me the same output without having to know the field id numbers, but I do need to know the names of the fields to generate the column names. The LIMIT is there to remove one of the JOIN products, and has a distinctly unholy feeling to it, I agree. I feel like there's not too much advantage to approach 2, since you have to know the column names anyways.

I would agree with @Mojtaba, however, that if you can't live with a pre-query to know the dynamic field names and ids, then I believe you're going to have to put sub-SELECT statements in there to pull those at query time.


问:
Reference generated primary key in SQL script
I'm trying to create a bunch of entries in a database with a single script and the problem I'm encountering is how to reference the generated primary key of the previous entry I created.

For example if I created a customer, then tried to create an order for that customer, how do I get the primary key generated for the customer?

I'm using SQLServer.

答:
Like so:

```<code>DECLARE @customerid int;
INSERT INTO customers(name) VALUES('Spencer');
SET @customerid = @@IDENTITY;
</code>```

EDIT:

Apparently it needs to be SCOPE_IDENTITY() in order to function as expected with triggers.

```<code>DECLARE @customerid int;
INSERT INTO customers(name) VALUES('Spencer');
SET @customerid = SCOPE_IDENTITY();
</code>```

OwnerDisplayName: Kenny

Body:
Like so:

DECLARE @customerid int;
INSERT INTO customers(name) VALUES('Spencer');
SET @customerid = @@IDENTITY;

EDIT:

Apparently it needs to be SCOPE_IDENTITY() in order to function as expected with triggers.

DECLARE @customerid int;
INSERT INTO customers(name) VALUES('Spencer');
SET @customerid = SCOPE_IDENTITY();

OwnerDisplayName: Spencer Ruport

LastEditorDisplayName: Spencer Ruport


问:
How solve flickering Font Awesome Icons?
if I using what is everywhere recommended - using CDN attachment for "Font Awesome" everytime flickering "on page load".

```<code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
</code>```

Q how prevent flickering?

答: I had the same issue and it appeared that I have included the FontAwesome stylesheet twice and after removing one of them the problem was gone.</p>

Body:
if I using what is everywhere recommended - using CDN attachment for "Font Awesome" everytime flickering "on page load".

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />

Q how prevent flickering?


问:
Pie and bar charts in Python
I have a pandas dataframe like below:

```<code>Group    id    Count
G1        412   52
G1        413   34
G2        412   2832
G2        413   314
</code>```

I am trying to build a pie chart in Python – for each Group and id, I need to display the respective count. It should have two splits - one for Group and other for Id. Outer circle should be Group and inner circle should be id. Just started with the visualisation, wondering whether there is a python library that can do this.

Is this requirement be achieved using bar charts?

Title: Pie and bar charts in Python

Body:
I have a pandas dataframe like below:

Group    id    Count
G1        412   52
G1        413   34
G2        412   2832
G2        413   314

I am trying to build a pie chart in Python – for each Group and id, I need to display the respective count. It should have two splits - one for Group and other for Id. Outer circle should be Group and inner circle should be id. Just started with the visualisation, wondering whether there is a python library that can do this.

Is this requirement be achieved using bar charts?

Body:
Here's what's required if you use pyexcel and pyexcel-pygal:

>>> import pyexcel as p
>>> sheet = p.get_sheet(file_name='test.csv', delimiter='\t')
>>> sheet
test.csv:
+-------+-----+-------+
| Group | id  | Count |
+-------+-----+-------+
| G1    | 412 | 52    |
+-------+-----+-------+
| G1    | 413 | 34    |
+-------+-----+-------+
| G2    | 412 | 2832  |
+-------+-----+-------+
| G2    | 413 | 314   |
+-------+-----+-------+
>>> sheet.transpose()
>>> sheet
test.csv:
+-------+-----+-----+------+-----+
| Group | G1  | G1  | G2   | G2  |
+-------+-----+-----+------+-----+
| id    | 412 | 413 | 412  | 413 |
+-------+-----+-----+------+-----+
| Count | 52  | 34  | 2832 | 314 |
+-------+-----+-----+------+-----+
>>> sheet.name_rows_by_column(0)
>>> sheet.row['Group']
['G1', 'G1', 'G2', 'G2']
>>> p.save_as(array=[sheet.row['Group'], sheet.row['Count']], dest_chart_type='pie', dest_file_name='group_pie.svg')

>>> p.save_as(array=[sheet.row['id'], sheet.row['Count']], dest_chart_type='pie', dest_file_name='id_pie.svg')


问:
For loops aplied to add +1 to a variable in swift 3
I'm trying to add +1 to a variable called "turn" every time a press "enter" on the textfield. I have tried something, but it seems like is not working.

I want the value to start in -1, and then every time i return on the textfield, it takes a +1 value, and i want it to stop when turn = 1.

I want this because depending on the turn value, when i hit return on the textfield, something different should happen. And when turn = 1, it should stop increasing the value, because i olnu have 3 cases: turn -1; turn 0; turn 1

This is the code that i have in the textFieldShouldReturn

```<code>var turno = -1

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

for var i in -1 ..< 1 where i <= 1  {

    turno = i
    i += 1
}

if inputTextField.text != "" {

    if turn == -1 {
        let text = inputTextField.text
        if (text?.characters.count)! <= 2 {

            dosletras.text = text
            label.text = nil
        }
    }

    if turno == 0 {
        label.text = inputTextField.text
    }

    if turno == 1 {

        //other things happen
    }

}

return true
</code>```

}

I want to do somethig like that because i use that variable "turn" to do other things in my code. The problem that i'm having is with the labels that change the text depending on the turn value and the text of the inputTextfield

Any solutions?
Thanks for the help!

答:
It looks like you're rather confused about how to increment a variable...

Edited Answer:

With your current code, the first thing you do when textFieldShouldReturn() is triggered is:

```<code>    for var i in -1 ..< 1 where i <= 1  {
        turno = i
        i += 1
    }
    // turno now equals 0
</code>```

Regardless of the value of turno when you start that code, the result is zero. It will never be anything else. So, delete that code completely, and never try to use it again :)

Compare that to this code:

```<code>var turno = -1

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if inputTextField.text != "" {

        if turno == -1 {
            let text = inputTextField.text
            if (text?.characters.count)! <= 2 {
                dosletras.text = text
                label.text = nil
                turno = 0
            }
        }
        else if turno == 0 {
            label.text = inputTextField.text
            turno = 1
        }
        else if turno == 1 {
            //other things happen
        }

    }

    return true
}
</code>```

Now, turno starts at -1 ...

First time through, if text <= 2 characters, set the text of the labels and set turno to 0 ...

Next time through, if turno was set to 0 last time, set the label text and set turno to 1 ...

Every time through after that, turno will remain at 1

Original Answer:

```<code>// initialize the variable "turn" to -1
var turn = -1

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    // increment turn by 1
    turn += 1

    // if turn is now > 1, return false
    if turn > 1 {
        return false
    }

    return true
}
</code>```

So, turn starts at -1...

The first time textFieldShouldReturn is called, turn will be incremented by 1 and will now equal 0, so the func returns true.

The next time textFieldShouldReturn is called, turn will be incremented by 1 and will now equal 1, so again the func returns true.

The third time textFieldShouldReturn is called, turn will be incremented by 1 and will now equal 2 (which is greater than 1), so the func returns false.

Body:
I'm trying to add +1 to a variable called "turn" every time a press "enter" on the textfield. I have tried something, but it seems like is not working.

I want the value to start in -1, and then every time i return on the textfield, it takes a +1 value, and i want it to stop when turn = 1.

I want this because depending on the turn value, when i hit return on the textfield, something different should happen. And when turn = 1, it should stop increasing the value, because i olnu have 3 cases: turn -1; turn 0; turn 1

This is the code that i have in the textFieldShouldReturn

var turno = -1

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

for var i in -1 ..< 1 where i <= 1  {

    turno = i
    i += 1
}

if inputTextField.text != "" {

    if turn == -1 {
        let text = inputTextField.text
        if (text?.characters.count)! <= 2 {

            dosletras.text = text
            label.text = nil
        }
    }

    if turno == 0 {
        label.text = inputTextField.text
    }

    if turno == 1 {

        //other things happen
    }

}

return true

}

I want to do somethig like that because i use that variable "turn" to do other things in my code. The problem that i'm having is with the labels that change the text depending on the turn value and the text of the inputTextfield

Any solutions?
Thanks for the help!

Body:
It looks like you're rather confused about how to increment a variable...

Edited Answer:

With your current code, the first thing you do when textFieldShouldReturn() is triggered is:

    for var i in -1 ..< 1 where i <= 1  {
        turno = i
        i += 1
    }
    // turno now equals 0

Regardless of the value of turno when you start that code, the result is zero. It will never be anything else. So, delete that code completely, and never try to use it again :)

Compare that to this code:

var turno = -1

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if inputTextField.text != "" {

        if turno == -1 {
            let text = inputTextField.text
            if (text?.characters.count)! <= 2 {
                dosletras.text = text
                label.text = nil
                turno = 0
            }
        }
        else if turno == 0 {
            label.text = inputTextField.text
            turno = 1
        }
        else if turno == 1 {
            //other things happen
        }

    }

    return true
}

Now, turno starts at -1 ...

First time through, if text <= 2 characters, set the text of the labels and set turno to 0 ...

Next time through, if turno was set to 0 last time, set the label text and set turno to 1 ...

Every time through after that, turno will remain at 1

Original Answer:

// initialize the variable "turn" to -1
var turn = -1

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    // increment turn by 1
    turn += 1

    // if turn is now > 1, return false
    if turn > 1 {
        return false
    }

    return true
}

So, turn starts at -1...

The first time textFieldShouldReturn is called, turn will be incremented by 1 and will now equal 0, so the func returns true.

The next time textFieldShouldReturn is called, turn will be incremented by 1 and will now equal 1, so again the func returns true.

The third time textFieldShouldReturn is called, turn will be incremented by 1 and will now equal 2 (which is greater than 1), so the func returns false.


问:
How to make a fully responsive Google Maps inserted in website
I'm putting an embedded Google Map side by side with a responsive image inside a div. I want the map to be the same size as the image always, and resize as it does.
This is my code, and the map looks really small.

```<code><div class="grid-container">
<div class="grid12-6 no-gutter">
  <img src="http://1.bp.blogspot.com/-MoFU-ybvlUw/TsXyHlX2AlI/AAAAAAAAARQ/kqXxZ8SquX8/s1600/la+fotolego.JPG" alt="" />
</div>
<div class="grid12-6 no-gutter">
  <div class="map-container">
    <div class="mapa">
      <iframe src="https://maps.google.com/maps?q=manquehue%20norte%201255&t=&z=14&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></iframe>
    </div>
  </div>
</div>
</code>```

I want it to look like this

答: Possibly, you will have to keep your parent as a display: flex; and the childrens as flex-items or inline.</p>

Body:
I'm putting an embedded Google Map side by side with a responsive image inside a div. I want the map to be the same size as the image always, and resize as it does.
This is my code, and the map looks really small.

I want it to look like this


问:
ReactiveUI 7.0 interaction handler never called
So, I am learning to use ReactiveUI 7.4 with winforms and I thing I got a pretty good experience with it until I tried to include Interactions for displaying an error popup :

ViewModel

```<code>public class ViewModel : ReactiveObject
{
    [...]

    public ViewModel()
    {
        GetCmd = ReactiveCommand.CreateFromTask(
            _ => myAsyncFunc(),
            CanGetCmd
        );

        GetCmd.ThrownExceptions
              .Subscribe(ex => Interactions.Errors.Handle(ex));   <- breakpoint correctly breaks in there
    }
}
</code>```

Interactions

```<code>public static class Interactions
{
    public static readonly Interaction<Exception, Unit> Errors = new Interaction<Exception, Unit>();
}
</code>```

View

```<code>public ViewCtor()
{
    [viewmodel declaration...]

    this.btnGet.Events().Click
        .Select(_ => Unit.Default)
        .InvokeCommand(this, x => x.ViewModel.GetCmd);

    Interactions.Errors.RegisterHandler(interaction =>
    {
        _popupManager.Show(interaction.Input.Message, "Arf !");   <- but breakpoint never hits here :(
    });
}
</code>```

Basically in debug, breakpoint hits in Handle declaration but never in RegisterHandler function.

I am probably missing something because from ReactiveUI documentation on interactions, I should get an UnhandledInteractionException if I don't set any RegisterHandler (which I tried) and I'm not even getting this exception...

If there are no handlers for a given interaction, or none of the handlers set a result, the interaction is itself considered unhandled. In this circumstance, the invocation of Handle will result in an UnhandledInteractionException being thrown.

(I am also using reactiveui-events-winforms for better event syntax wire up)

答:
Interactions.Errors.Handle(ex) returns a cold observable, i.e. it doesn't actually do anything until you subscribe to it. This should work:

```<code>GetCmd.ThrownExceptions
          .Subscribe(ex => Interactions.Errors.Handle(ex).Subscribe());
</code>```

(You may need to add using System;.)

Body:
So, I am learning to use ReactiveUI 7.4 with winforms and I thing I got a pretty good experience with it until I tried to include Interactions for displaying an error popup :

ViewModel

public class ViewModel : ReactiveObject
{
    [...]

    public ViewModel()
    {
        GetCmd = ReactiveCommand.CreateFromTask(
            _ => myAsyncFunc(),
            CanGetCmd
        );

        GetCmd.ThrownExceptions
              .Subscribe(ex => Interactions.Errors.Handle(ex));   <- breakpoint correctly breaks in there
    }
}

Interactions

public static class Interactions
{
    public static readonly Interaction<Exception, Unit> Errors = new Interaction<Exception, Unit>();
}

View

public ViewCtor()
{
    [viewmodel declaration...]

    this.btnGet.Events().Click
        .Select(_ => Unit.Default)
        .InvokeCommand(this, x => x.ViewModel.GetCmd);

    Interactions.Errors.RegisterHandler(interaction =>
    {
        _popupManager.Show(interaction.Input.Message, "Arf !");   <- but breakpoint never hits here :(
    });
}

Basically in debug, breakpoint hits in Handle declaration but never in RegisterHandler function.

I am probably missing something because from ReactiveUI documentation on interactions, I should get an UnhandledInteractionException if I don't set any RegisterHandler (which I tried) and I'm not even getting this exception...

If there are no handlers for a given interaction, or none of the handlers set a result, the interaction is itself considered unhandled. In this circumstance, the invocation of Handle will result in an UnhandledInteractionException being thrown.

(I am also using reactiveui-events-winforms for better event syntax wire up)

Body:
Interactions.Errors.Handle(ex) returns a cold observable, i.e. it doesn't actually do anything until you subscribe to it. This should work:

GetCmd.ThrownExceptions
          .Subscribe(ex => Interactions.Errors.Handle(ex).Subscribe());

(You may need to add using System;.)


问:
GET Requests vs JavaScript
Alright, I have a JavaScript doing HTTP Requests to a PHP file onto the same directory. Then it's returning it's output.

Let's say there are over 50+ people doing this request simultaneously ... will it slow down anything? Yes, this may seem like a dumb question - but sorry. :|

Thank you.

答:
It really depends on your backend code.

I have a php file for a scrabble type game, which simply checks if the word is valid. This does a database lookup, and responds with a true or false. It sounds like your request is doing something very similar. The way you are doing it is one of the most efficient ways, because you are only checking the results, rather than doing a full page reload.

The result is less than 20ms usually, and under load does not particularly increase that much. But my code is doing very little.

In principle though, what you are doing is fine.

Title: GET Requests vs JavaScript