问:
Filter Array of custom objects using NSPredicate in Objective C
I have one array which contains dictionary of custom objects.I want to filter that array for search functionality in UITableView. Here is my code for single object Filtration using NSPredicate.

```<code>self.searchResultForName = [self.multiPracticeDetailsArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    ObjectHolder *obj = (ObjectHolder*)evaluatedObject;
    return [obj.Name hasPrefix:searchText];
}]];
</code>```

Using above code, I can search only for Name , but i want to search for both By Name and ID.Also search will be case insensitive. How can i do this in Objective-C?.Please Suggest any better way to do this.

答:
Did you tried with || OR operator & lowercaseString.

```<code>self.searchResultForName = [self.multiPracticeDetailsArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    ObjectHolder *obj = (ObjectHolder*)evaluatedObject;
    return [[obj.Name lowercaseString] hasPrefix:[searchText lowercaseString]] || [[obj.ID lowercaseString] hasPrefix:[searchText lowercaseString]] ;
}]];
</code>```

Body:
I have one array which contains dictionary of custom objects.I want to filter that array for search functionality in UITableView. Here is my code for single object Filtration using NSPredicate.

self.searchResultForName = [self.multiPracticeDetailsArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    ObjectHolder *obj = (ObjectHolder*)evaluatedObject;
    return [obj.Name hasPrefix:searchText];
}]];

Using above code, I can search only for Name , but i want to search for both By Name and ID.Also search will be case insensitive. How can i do this in Objective-C?.Please Suggest any better way to do this.

Body:
Did you tried with || OR operator & lowercaseString.

self.searchResultForName = [self.multiPracticeDetailsArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    ObjectHolder *obj = (ObjectHolder*)evaluatedObject;
    return [[obj.Name lowercaseString] hasPrefix:[searchText lowercaseString]] || [[obj.ID lowercaseString] hasPrefix:[searchText lowercaseString]] ;
}]];


来源: stackexchange

问:
How do I hotkey directly to File Search tab in Eclipse
When I use CTRL+H I end up on the Java Search tab. I would very much like a shortcut to go directly to File Search instead. Is that possible?

See image here for what I'm talking about:

答: Another option is to open the search dialog (Ctrl+H) then click customize and hide java and task search tabs, next time you do Ctrl+H, file search will be the only one showing, thus it will be selected by default

OwnerDisplayName: svrist

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: svrist

ContentLicense: CC BY-SA 3.0


问:
Delete some data from a .txt file and then store the rest into two lists..
I have data stored in a .txt file...

```<code>Subset 1    1   350.000 0.096
Subset 1    2   351.000 0.095
Subset 1    3   352.000 0.095
Subset 1    4   353.000 0.097
Subset 1    5   354.000 0.096
Subset 1    6   355.000 0.095
Subset 1    7   356.000 0.097
Subset 1    8   357.000 0.094
Subset 1    9   358.000 0.091
Subset 1    10  359.000 0.091
Subset 1    11  360.000 0.091
Subset 1    12  361.000 0.092
Subset 1    13  362.000 0.091
Subset 1    14  363.000 0.089
Subset 1    15  364.000 0.089
Subset 1    16  365.000 0.090
</code>```

And I want to use only the values 350, 351... and 0.096, 0.95,... . So I need in the first place to delete all the Subset 1  and number 1,2,3,4... and then store 350, 351... and 0.096, 0.95,... in two different lists in order to plot them.

What I tried to do is something like:

```<code>import io
# Load the txt file
text_file = io.open("/home/stagiaire/Bureau/01.Dark Skin.txt","r",
encoding = "utf-16")
# Read the lines and then strip
lines = text_file.readlines()
li = lines.strip(',')
# Delete "susbset1" by replacing it with nothing...
nkia = lines.replace("Subset 1","")
</code>```

But it doesn't work...Any suggestions on how I can do it ? Thank you.

答:
here is one way to do it:</p>

```<code>import io
# Load the txt file
text_file = io.open("/home/stagiaire/Bureau/01.Dark Skin.txt","r",
encoding = "utf-16")
# Output lists
list1 = []
list2 = []
# Read the lines and then make lists
for line in text_file.readlines():
    segments = line.split()
    list1.append(segments[-1])
    list2.append(segments[-2])
</code>```

Body:
I have data stored in a .txt file...

Subset 1    1   350.000 0.096
Subset 1    2   351.000 0.095
Subset 1    3   352.000 0.095
Subset 1    4   353.000 0.097
Subset 1    5   354.000 0.096
Subset 1    6   355.000 0.095
Subset 1    7   356.000 0.097
Subset 1    8   357.000 0.094
Subset 1    9   358.000 0.091
Subset 1    10  359.000 0.091
Subset 1    11  360.000 0.091
Subset 1    12  361.000 0.092
Subset 1    13  362.000 0.091
Subset 1    14  363.000 0.089
Subset 1    15  364.000 0.089
Subset 1    16  365.000 0.090

And I want to use only the values 350, 351... and 0.096, 0.95,... . So I need in the first place to delete all the Subset 1  and number 1,2,3,4... and then store 350, 351... and 0.096, 0.95,... in two different lists in order to plot them.

What I tried to do is something like:

import io
# Load the txt file
text_file = io.open("/home/stagiaire/Bureau/01.Dark Skin.txt","r",
encoding = "utf-16")
# Read the lines and then strip
lines = text_file.readlines()
li = lines.strip(',')
# Delete "susbset1" by replacing it with nothing...
nkia = lines.replace("Subset 1","")

But it doesn't work...Any suggestions on how I can do it ? Thank you.

Body:
here is one way to do it:

import io
# Load the txt file
text_file = io.open("/home/stagiaire/Bureau/01.Dark Skin.txt","r",
encoding = "utf-16")
# Output lists
list1 = []
list2 = []
# Read the lines and then make lists
for line in text_file.readlines():
    segments = line.split()
    list1.append(segments[-1])
    list2.append(segments[-2])


问:
Optional route data with default value in MVC
I have this routing:

```<code>app.UseMvc(routes =>
            {
                routes.MapRoute(
                name: "default",
                template: "{culture=en-US}/{controller=Home}/{action=Index}/{p1?}/{p2?}");
            });
</code>```

The last two items are optional and actually they don't exist in most of pages and is for a specific page (That also I want it to be the landing page) however its not letting to define values for optional parameters.

I tried {p1?=somevalue} and I got an error telling me that ? must be the last character. {p1=somevalue?} doesn't work either.

答:
Try create two routes

1º

```<code>app.UseMvc(routes =>
{
     routes.MapRoute(
     name: "default",
     template: "{culture=en-US}/{controller=Home}/{action=Index}");
});
</code>```

2º

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(
    name: "custonRoute",
    template: "{culture=en-US}/{controller=Home}/{action=Index}/{p1?}/{p2?}");
});
</code>```

Body:
I have this routing:

app.UseMvc(routes =>
            {
                routes.MapRoute(
                name: "default",
                template: "{culture=en-US}/{controller=Home}/{action=Index}/{p1?}/{p2?}");
            });

The last two items are optional and actually they don't exist in most of pages and is for a specific page (That also I want it to be the landing page) however its not letting to define values for optional parameters.

I tried {p1?=somevalue} and I got an error telling me that ? must be the last character. {p1=somevalue?} doesn't work either.

Body:
Try create two routes

1º

app.UseMvc(routes =>
{
     routes.MapRoute(
     name: "default",
     template: "{culture=en-US}/{controller=Home}/{action=Index}");
});

2º

app.UseMvc(routes =>
{
    routes.MapRoute(
    name: "custonRoute",
    template: "{culture=en-US}/{controller=Home}/{action=Index}/{p1?}/{p2?}");
});


问:
Hide Android "voice to Text" Dialog Box
I am working with an Voice to Text Application where I need to keep Voice command Dialog in background, means I don't want to hide it again n again.

Pls shows me how can I do this.

答:
it is not possible
 (unless you hack into a rooted phone)</p>

ContentLicense: CC BY-SA 2.5

Title: Hide Android "voice to Text" Dialog Box


问:
SpriteKit - get absolute size of SKNode
I'm programming a small game in Swift and SpriteKit, which is made of a boxes (4 * 8).

```<code>Scene (1024 * 768)
    boxes (964 * 452)
        row1 (932 * 25)
            col1 (24 * 116)
            col2 (24 * 116)
            col3 (24 * 116)
            ...
        row2...
</code>```

I want to give them a texture, but I don't know how big the image file should be. And the box node's size seems to be relative to its parent node. How can I get the absolute size of an SKNode, the size the node takes on the screen?

答: All SKNodes have a method called calculateAccumulatedFrame

Title: SpriteKit - get absolute size of SKNode

Body:
I'm programming a small game in Swift and SpriteKit, which is made of a boxes (4 * 8).

Scene (1024 * 768)
    boxes (964 * 452)
        row1 (932 * 25)
            col1 (24 * 116)
            col2 (24 * 116)
            col3 (24 * 116)
            ...
        row2...

I want to give them a texture, but I don't know how big the image file should be. And the box node's size seems to be relative to its parent node. How can I get the absolute size of an SKNode, the size the node takes on the screen?


问:
How can I mimic two domains on a single asp.net website? Are RouteConstraints an option?
I'm running a single instance of Orchard CMS on my web server with two custom modules, ModuleFirst and ModuleSecond. For reasons, I want these two to act as separate websites with their own domain and homepage. I can not set up additional websites or use Orchard's built-in Tenants feature.

What I have

The way I went about achieving this is as follows:

Added two bindings to my website in IIS: first-domain.com and second-domain.com

Implemented a ThemeSelector (which I think acts like an ActionFilter) that switches the theme based on the host of the Url in the incoming Request

```<code>if (host.Contains("second-domain.com"))
{
    useSecondTheme = true;
}
</code>```

Make sure all routes are unique

This is working reasonably well for the most part. I can navigate to first-domain.com/foo and second-domain.com/bar and it looks like I'm on different websites.

The problem

For the two "homepages" I can't make a unique route because I don't want to add any suffixes. Both projects define a blank route that should lead to their respective Home/Index but I can't figure out how to make this work.

```<code>new RouteDescriptor {
    Priority = 90,
    Route = new Route(
        "",
        new RouteValueDictionary { // Defaults
            {"area", "ModuleFirst"},
            {"controller", "Home"},
            {"action", "Index"},
        },
        new RouteValueDictionary(), // Constraints
        new RouteValueDictionary { // Datatokens
            {"area", "ModuleFirst"}
        },
        new MvcRouteHandler())
}

new RouteDescriptor {
    Priority = 100,
    Route = new Route(
        "",
        new RouteValueDictionary { // Defaults
            {"area", "ModuleSecond"},
            {"controller", "Home"},
            {"action", "Index"},
        },
        new RouteValueDictionary(), // Constraints
        new RouteValueDictionary { // Datatokens
            {"area", "ModuleSecond"}
        },
        new MvcRouteHandler())
}
</code>```

What I tried

I tried to implement an ActionFilter that Redirects to ModuleFirst/Home/Index when a request with host url first-domain.com reaches ModuleSecond/Home/Index but this obviously doesn't work since it just keeps hitting the highest priority route over and over and breaks the website.

I have also tried to implement a custom RouteConstraint on the route with the highest priority to block all incoming request that don't come from its intended domain, assuming that those would then fall back on the lower priority route.

```<code>public class SecondConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return httpContext.Request.Url.DnsSafeHost.Contains("second-domain.com");
    }
}
</code>```

used as follows:

```<code>new RouteDescriptor {
    Priority = 100,
    Route = new Route(
        "",
        new RouteValueDictionary { // Defaults
            {"area", "ModuleSecond"},
            {"controller", "Home"},
            {"action", "Index"},
        },
        new RouteValueDictionary { // Constraints
            {"isSecond", new SecondConstraint()}
        },
        new RouteValueDictionary { // Datatokens
            {"area", "ModuleSecond"}
        },
        new MvcRouteHandler())
}
</code>```

I can now navigate to second-domain.com just fine and get the correct page but navigating to first-domain.com times out. I haven't managed to find any examples of RouteConstraints in Orchard though, so maybe I'm doing it wrong.

答:
Though I would recommend anyone who is about to do something like this from scratch to use tenants and OAuth instead if possible, as Bertrand suggests in his comment, I thought of a fairly clean way to accomplish what I wanted.

Instead of using two separate modules, I just use one.

In my one module, I implement IRouteProvider to override the default route, which catches both first-domain.com/ and second-domain.com/

```<code>public class Routes : IRouteProvider
{
    public void GetRoutes(ICollection<RouteDescriptor> routes)
    {
        foreach (var routeDescriptor in GetRoutes())
            routes.Add(routeDescriptor);
    }

    public IEnumerable<RouteDescriptor> GetRoutes()
    {
        return new[] {
            new RouteDescriptor {
                Priority = 100,
                Route = new Route(
                    "",
                    new RouteValueDictionary {
                        {"area", "MyModule"},
                        {"controller", "Home"},
                        {"action", "Index"},
                    },
                    new RouteValueDictionary(),
                    new RouteValueDictionary {
                        {"area", "MyModule"}
                    },
                    new MvcRouteHandler())
            }
        };
    }
}
</code>```

Then I created a custom Part with just a single property bool IsHomepage and attached it to the Page Type

```<code>public class SecondHomepagePart : ContentPart<SecondHomepagePartRecord>
{
    public bool IsHomepage
    {
        get { return Retrieve(r => r.IsHomepage); }
        set { Store(r => r.IsHomepage, value); }
    }
}
</code>```

In the driver I make sure that there is only ever one "second homepage"

```<code>protected override DriverResult Editor(SecondHomepagePart part, IUpdateModel updater, dynamic shapeHelper)
{
        if (updater.TryUpdateModel(part, Prefix, null, null))
        {
            if (part.IsHomepage)
            {
                var otherHomepages = _orchardServices.ContentManager.Query<SecondHomepagePart>().Where<SecondHomepagePartRecord>(r => r.IsHomepage && r.Id != part.Id).List();

                foreach (var homepagePart in otherHomepages)
                {
                    homepagePart.IsHomepage = false;
                }
            }
        }

        return Editor(part, shapeHelper);
}
</code>```

Then in my custom HomeController I just check the current domain, fetch the ContentItem with the blank AutoroutePart or the SecondHomepagePart where IsHomepage is set to true depending on the domain, build the Detail Shape of that item and then display that Shape in my custom Index.cshtml view.

Controller:

```<code>public ActionResult Index()
{
        var host = HttpContext.Request.Url.DnsSafeHost;

        var model = new IndexViewModel();
        IContent homepageItem;

        if (host.Contains("first-domain.com"))
        {
            homepageItem = _homeAliasService.GetHomePage();
        }
        else
        {
            homepageItem = _orchardServices.ContentManager.Query<SecondHomepagePart>()
                .Where<SecondHomepagePartRecord>(r => r.IsHomepage)
                .List()
                .FirstOrDefault();
        }

        model.Homepage = _orchardServices.ContentManager.BuildDisplay(homepageItem, "Detail");

        return View(model);
}
</code>```

View:

```<code>@model MyModule.ViewModels.Home.IndexViewModel

@if (Model.Homepage != null)
{
    @Display(Model.Homepage)
}
</code>```

I use the same check in an IConditionProvider and IThemeSelector to have a layer rule for each domain and to set the appropriate theme automatically. Now I essentially have two completely different websites to the outside world but with shared content, widgets, parts, custom settings etc. This is a quick and easy solution for a client who sells the same products from the same stock but under different brandings and under different conditions, along with some exclusive content that's different for both.

Body:
I'm running a single instance of Orchard CMS on my web server with two custom modules, ModuleFirst and ModuleSecond. For reasons, I want these two to act as separate websites with their own domain and homepage. I can not set up additional websites or use Orchard's built-in Tenants feature.

What I have

The way I went about achieving this is as follows:

Added two bindings to my website in IIS: first-domain.com and second-domain.com

Implemented a ThemeSelector (which I think acts like an ActionFilter) that switches the theme based on the host of the Url in the incoming Request

if (host.Contains("second-domain.com"))
{
    useSecondTheme = true;
}

Make sure all routes are unique

This is working reasonably well for the most part. I can navigate to first-domain.com/foo and second-domain.com/bar and it looks like I'm on different websites.

The problem

For the two "homepages" I can't make a unique route because I don't want to add any suffixes. Both projects define a blank route that should lead to their respective Home/Index but I can't figure out how to make this work.

new RouteDescriptor {
    Priority = 90,
    Route = new Route(
        "",
        new RouteValueDictionary { // Defaults
            {"area", "ModuleFirst"},
            {"controller", "Home"},
            {"action", "Index"},
        },
        new RouteValueDictionary(), // Constraints
        new RouteValueDictionary { // Datatokens
            {"area", "ModuleFirst"}
        },
        new MvcRouteHandler())
}

new RouteDescriptor {
    Priority = 100,
    Route = new Route(
        "",
        new RouteValueDictionary { // Defaults
            {"area", "ModuleSecond"},
            {"controller", "Home"},
            {"action", "Index"},
        },
        new RouteValueDictionary(), // Constraints
        new RouteValueDictionary { // Datatokens
            {"area", "ModuleSecond"}
        },
        new MvcRouteHandler())
}

What I tried

I tried to implement an ActionFilter that Redirects to ModuleFirst/Home/Index when a request with host url first-domain.com reaches ModuleSecond/Home/Index but this obviously doesn't work since it just keeps hitting the highest priority route over and over and breaks the website.

I have also tried to implement a custom RouteConstraint on the route with the highest priority to block all incoming request that don't come from its intended domain, assuming that those would then fall back on the lower priority route.

public class SecondConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return httpContext.Request.Url.DnsSafeHost.Contains("second-domain.com");
    }
}

used as follows:

new RouteDescriptor {
    Priority = 100,
    Route = new Route(
        "",
        new RouteValueDictionary { // Defaults
            {"area", "ModuleSecond"},
            {"controller", "Home"},
            {"action", "Index"},
        },
        new RouteValueDictionary { // Constraints
            {"isSecond", new SecondConstraint()}
        },
        new RouteValueDictionary { // Datatokens
            {"area", "ModuleSecond"}
        },
        new MvcRouteHandler())
}

I can now navigate to second-domain.com just fine and get the correct page but navigating to first-domain.com times out. I haven't managed to find any examples of RouteConstraints in Orchard though, so maybe I'm doing it wrong.

Body:
Though I would recommend anyone who is about to do something like this from scratch to use tenants and OAuth instead if possible, as Bertrand suggests in his comment, I thought of a fairly clean way to accomplish what I wanted.

Instead of using two separate modules, I just use one.

In my one module, I implement IRouteProvider to override the default route, which catches both first-domain.com/ and second-domain.com/

public class Routes : IRouteProvider
{
    public void GetRoutes(ICollection<RouteDescriptor> routes)
    {
        foreach (var routeDescriptor in GetRoutes())
            routes.Add(routeDescriptor);
    }

    public IEnumerable<RouteDescriptor> GetRoutes()
    {
        return new[] {
            new RouteDescriptor {
                Priority = 100,
                Route = new Route(
                    "",
                    new RouteValueDictionary {
                        {"area", "MyModule"},
                        {"controller", "Home"},
                        {"action", "Index"},
                    },
                    new RouteValueDictionary(),
                    new RouteValueDictionary {
                        {"area", "MyModule"}
                    },
                    new MvcRouteHandler())
            }
        };
    }
}

Then I created a custom Part with just a single property bool IsHomepage and attached it to the Page Type

public class SecondHomepagePart : ContentPart<SecondHomepagePartRecord>
{
    public bool IsHomepage
    {
        get { return Retrieve(r => r.IsHomepage); }
        set { Store(r => r.IsHomepage, value); }
    }
}

In the driver I make sure that there is only ever one "second homepage"

protected override DriverResult Editor(SecondHomepagePart part, IUpdateModel updater, dynamic shapeHelper)
{
        if (updater.TryUpdateModel(part, Prefix, null, null))
        {
            if (part.IsHomepage)
            {
                var otherHomepages = _orchardServices.ContentManager.Query<SecondHomepagePart>().Where<SecondHomepagePartRecord>(r => r.IsHomepage && r.Id != part.Id).List();

                foreach (var homepagePart in otherHomepages)
                {
                    homepagePart.IsHomepage = false;
                }
            }
        }

        return Editor(part, shapeHelper);
}

Then in my custom HomeController I just check the current domain, fetch the ContentItem with the blank AutoroutePart or the SecondHomepagePart where IsHomepage is set to true depending on the domain, build the Detail Shape of that item and then display that Shape in my custom Index.cshtml view.

Controller:

public ActionResult Index()
{
        var host = HttpContext.Request.Url.DnsSafeHost;

        var model = new IndexViewModel();
        IContent homepageItem;

        if (host.Contains("first-domain.com"))
        {
            homepageItem = _homeAliasService.GetHomePage();
        }
        else
        {
            homepageItem = _orchardServices.ContentManager.Query<SecondHomepagePart>()
                .Where<SecondHomepagePartRecord>(r => r.IsHomepage)
                .List()
                .FirstOrDefault();
        }

        model.Homepage = _orchardServices.ContentManager.BuildDisplay(homepageItem, "Detail");

        return View(model);
}

View:

@model MyModule.ViewModels.Home.IndexViewModel

@if (Model.Homepage != null)
{
    @Display(Model.Homepage)
}

I use the same check in an IConditionProvider and IThemeSelector to have a layer rule for each domain and to set the appropriate theme automatically. Now I essentially have two completely different websites to the outside world but with shared content, widgets, parts, custom settings etc. This is a quick and easy solution for a client who sells the same products from the same stock but under different brandings and under different conditions, along with some exclusive content that's different for both.


问:
javascript if a html element text equal with 0, addClass to an element
I have an element that contains the discount of a product

0
        %

```

I want, if the element with id="mydiscouttext" equal to 0, addClass "hide".

I am looking for a solution with javascript.

Any idea?

答:
```<code>if(!parseInt(document.querySelector("#mydiscouttext").innerText)){
    document.querySelector("#mydiscouttext").style.display = "none";
}
</code>```

this can be help

Body:
I have an element that contains the discount of a product

0
        %

I want, if the element with id="mydiscouttext" equal to 0, addClass "hide".

I am looking for a solution with javascript.

Any idea?

Body:
if(!parseInt(document.querySelector("#mydiscouttext").innerText)){
    document.querySelector("#mydiscouttext").style.display = "none";
}

this can be help


问:
Using JavaCV with Kotlin
I'm currently attempting to start a project using JavaCV in Kotlin. I'm using IntelliJ Idea as my IDE. I'm using JavaCV 1.3.2 and OpenCV 3.20.
This is my setup for the module's dependancies for OpenCV:

and for JavaCV:

I have opencv before javacv in the dependancies.
To test that OpenCV is present and valid, I wrote the below to test. As I can loadLibrary and the version number shows correctly I can assume that OpenCV is actually working.

```<code>import org.opencv.core.Core
import org.opencv.core.Mat
import org.opencv.core.CvType
import org.opencv.core.Scalar
import org.bytedeco.javacv.OpenCVFrameGrabber

fun main(args : Array<String>) {
    println("Test Built Successfully")
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME)
    println("Running OpenCV Version ${Core.VERSION}")
    val grabber = OpenCVFrameGrabber(1)
}
</code>```

The line where we initialize the grabber rasies the following exception:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: no jniopencv_core in java.library.path
Caused by: java.lang.UnsatisfiedLinkError: no opencv_imgproc320 in java.library.path
</code>```

Perhaps I am missing something here, but I have followed the instructions provided by the README.md in the Git repository for JavaCV. I haven't seen anybody else trying to use this library with Kotlin on StackOverflow, though have checked out some posts about the same exception being raised using java.

答: I was able to resolve this by leaving my VM options blank and adding all necessary OpenCV libraries as native library paths in my JavaCV library configuration.</p>

Title: Using JavaCV with Kotlin

Body:
I'm currently attempting to start a project using JavaCV in Kotlin. I'm using IntelliJ Idea as my IDE. I'm using JavaCV 1.3.2 and OpenCV 3.20.
This is my setup for the module's dependancies for OpenCV:

and for JavaCV:

I have opencv before javacv in the dependancies.
To test that OpenCV is present and valid, I wrote the below to test. As I can loadLibrary and the version number shows correctly I can assume that OpenCV is actually working.

import org.opencv.core.Core
import org.opencv.core.Mat
import org.opencv.core.CvType
import org.opencv.core.Scalar
import org.bytedeco.javacv.OpenCVFrameGrabber

fun main(args : Array<String>) {
    println("Test Built Successfully")
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME)
    println("Running OpenCV Version ${Core.VERSION}")
    val grabber = OpenCVFrameGrabber(1)
}

The line where we initialize the grabber rasies the following exception:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no jniopencv_core in java.library.path
Caused by: java.lang.UnsatisfiedLinkError: no opencv_imgproc320 in java.library.path

Perhaps I am missing something here, but I have followed the instructions provided by the README.md in the Git repository for JavaCV. I haven't seen anybody else trying to use this library with Kotlin on StackOverflow, though have checked out some posts about the same exception being raised using java.


问:
Beyond item-to-item recommendations
Simple item-to-item recommendation systems are well-known and frequently implemented. An example is the Slope One algorithm. This is fine if the user hasn't rated many items yet, but once they have, I want to offer more finely-grained recommendations. Let's take a music recommendation system as an example, since they are quite popular. If a user is viewing a piece by Mozart, a suggestion for another Mozart piece or Beethoven might be given. But if the user has made many ratings on classical music, we might be able to make a correlation between the items and see that the user dislikes vocals or certain instruments. I'm assuming this would be a two-part process, first part is to find correlations between each users' ratings, the second would be to build the recommendation matrix from these extra data. So the question is, are they any open-source implementations or papers that can be used for each of these steps?</p>

答:
Taste may have something useful. It's moved to the Mahout project:

http://taste.sourceforge.net/

In general, the idea is that given a user's past preferences, you want to predict what they'll select next and recommend it. You build a machine-learning model in which the inputs are what a user has picked in the past and the attributes of each pick. The output is the item(s) they'll pick. You create training data by holding back some of their choices, and using their history to predict the data you held back.

Lots of different machine learning models you can use. Decision trees are common.

Title: Beyond item-to-item recommendations


问:
Class 'SoapClient' not found on Google Cloud PHP App
I deployed my php app to Google Cloud and getting currently the following error when i call the line.

```<code> $url = "S5WS.wsdl";
 $client = new \SoapClient(dirname(__FILE__) . DIRECTORY_SEPARATOR . $url, array('trace' => true, 'soap_version' => SOAP_1_1));
</code>```

PHP message:

PHP Fatal error: Class 'SoapClient' not found in /app/controllers/TicketController.php on line 211

I opened the terminal in the Google Cloud and typed php -i | grep -i soapso to check the status of the soap and it seemds to be fine.

```<code>baltacii@s5-app-****:/$ php -i | grep -i soap
soap
Soap Client => enabled
Soap Server => enabled
soap.wsdl_cache => 1 => 1
soap.wsdl_cache_dir => /tmp => /tmp
soap.wsdl_cache_enabled => 1 => 1
soap.wsdl_cache_limit => 5 => 5
soap.wsdl_cache_ttl => 86400 => 86400
baltacii@s5-app-167912:/$
</code>```

If i call phpinfo(); in the app.It returns me in contrast to my localhost no Soap Section. There are only 2 lines related with the soap.

```<code>SOAP    Brad Lafountain, Shane Caraveo, Dmitry Stogov
</code>```

and in the configure command section

```<code>'--enable-soap=shared'
</code>```

EDIT: App runs on PHP Version 5.6

答:
So according to documentation some PHP extensions are compiled as shared, but disabled by default.Soap is one of these extensions.In order to activate it. We should create a php.ini in the base folder of the project.

php.ini

```<code>; Enable the Soap extension
extension=soap.so
</code>```

After new deployment to server soap should be available.

Body:
I deployed my php app to Google Cloud and getting currently the following error when i call the line.

 $url = "S5WS.wsdl";
 $client = new \SoapClient(dirname(__FILE__) . DIRECTORY_SEPARATOR . $url, array('trace' => true, 'soap_version' => SOAP_1_1));

PHP message:

PHP Fatal error: Class 'SoapClient' not found in /app/controllers/TicketController.php on line 211

I opened the terminal in the Google Cloud and typed php -i | grep -i soapso to check the status of the soap and it seemds to be fine.

baltacii@s5-app-****:/$ php -i | grep -i soap
soap
Soap Client => enabled
Soap Server => enabled
soap.wsdl_cache => 1 => 1
soap.wsdl_cache_dir => /tmp => /tmp
soap.wsdl_cache_enabled => 1 => 1
soap.wsdl_cache_limit => 5 => 5
soap.wsdl_cache_ttl => 86400 => 86400
baltacii@s5-app-167912:/$

If i call phpinfo(); in the app.It returns me in contrast to my localhost no Soap Section. There are only 2 lines related with the soap.

SOAP    Brad Lafountain, Shane Caraveo, Dmitry Stogov

and in the configure command section

'--enable-soap=shared'

EDIT: App runs on PHP Version 5.6

Body:
So according to documentation some PHP extensions are compiled as shared, but disabled by default.Soap is one of these extensions.In order to activate it. We should create a php.ini in the base folder of the project.

php.ini

; Enable the Soap extension
extension=soap.so

After new deployment to server soap should be available.


问:
SQL Server Conversion Failure when using INSERT
I have an existing table full of data, which can be created using

```<code>CREATE TABLE __EpisodeCost
(
    ActivityRecordID INT NOT NULL,
    ActCstID NVARCHAR(15),
    VolAmt FLOAT,
    ActCnt FLOAT,
    TotCst FLOAT,
    ResCstID NVARCHAR(50)
);
</code>```

This comes from a feed I have no control over and I want to convert this to my own version called EpisodeCost

```<code>CREATE TABLE EpisodeCostCtp
(
    ActivityRecordID INT NOT NULL,
    ActCstID NVARCHAR(6),
    ResCstID NVARCHAR(7),
    ActCnt NVARCHAR(7),
    TotCst DECIMAL(18, 8)
);
</code>```

Now, the problem I am having is with conversions. I can execute the query

```<code>SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp;
</code>```

and it provides data, however, when I try to execute

```<code>INSERT INTO EpisodeCostCtp
    (
        ActivityRecordID,
        ActCstID,
        ResCstID,
        ActCnt,
        TotCst
    )
SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp;
</code>```

I get

Msg 8115, Level 16, State 8, Line 102
  Arithmetic overflow error converting numeric to data type numeric.
  The statement has been terminated.

Why can I SELECT using the relevant casts, but then cannot INSERT into the target table?

Edit. I still don;t fully know what is occurring here.

As per Serg's recommendations, I have attempted to locate the problematic records but the query

```<code>SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp
WHERE TotCst > 9.999999999999999e9;
</code>```

returns zero records. Changing to 9.999999999999999e8 does, and the conversion/cast happens with out error. I have scince changed the INSERT query to use DECIMAL(36, 18) and now the insert succeeds, but I am still none the wiser. Clearly I was hitting a limit on the cast, but why SELECT works and INSERT fails, I still don't know.

答:
I believe that in your TotCst column has values bigger than DECIMAL(18,8).
And the version 2008 of SQL SERVER gets a rounded result if the destination type is not large enough. But it can't insert because the table accepts exact values only.

You can see the result of my two queries on SQL SERVER 2012 :

```<code> DECLARE @float FLOAT
 SET @float = 12345678911.12
 SELECT CAST(@float AS decimal(18,8))
</code>```

Result :
An arithmetic overflow error occurred when converting float to numeric data type.

the same query with DECIMAL(19,8) instead :

```<code> DECLARE @float FLOAT
 SET @float = 12345678911.12
 SELECT CAST(@float AS decimal(19,8))
</code>```

Result : 12345678911.12000100

EDIT : Check if your query tool fetchs all records. If not, maybe among the rest of records there are some values bigger than DECIMAL(18.8)

Body:
I have an existing table full of data, which can be created using

CREATE TABLE __EpisodeCost
(
    ActivityRecordID INT NOT NULL,
    ActCstID NVARCHAR(15),
    VolAmt FLOAT,
    ActCnt FLOAT,
    TotCst FLOAT,
    ResCstID NVARCHAR(50)
);

This comes from a feed I have no control over and I want to convert this to my own version called EpisodeCost

CREATE TABLE EpisodeCostCtp
(
    ActivityRecordID INT NOT NULL,
    ActCstID NVARCHAR(6),
    ResCstID NVARCHAR(7),
    ActCnt NVARCHAR(7),
    TotCst DECIMAL(18, 8)
);

Now, the problem I am having is with conversions. I can execute the query

SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp;

and it provides data, however, when I try to execute

INSERT INTO EpisodeCostCtp
    (
        ActivityRecordID,
        ActCstID,
        ResCstID,
        ActCnt,
        TotCst
    )
SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp;

I get

Msg 8115, Level 16, State 8, Line 102
  Arithmetic overflow error converting numeric to data type numeric.
  The statement has been terminated.

Why can I SELECT using the relevant casts, but then cannot INSERT into the target table?

Edit. I still don;t fully know what is occurring here.

As per Serg's recommendations, I have attempted to locate the problematic records but the query

SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp
WHERE TotCst > 9.999999999999999e9;

returns zero records. Changing to 9.999999999999999e8 does, and the conversion/cast happens with out error. I have scince changed the INSERT query to use DECIMAL(36, 18) and now the insert succeeds, but I am still none the wiser. Clearly I was hitting a limit on the cast, but why SELECT works and INSERT fails, I still don't know.

Body:
I believe that in your TotCst column has values bigger than DECIMAL(18,8).
And the version 2008 of SQL SERVER gets a rounded result if the destination type is not large enough. But it can't insert because the table accepts exact values only.

You can see the result of my two queries on SQL SERVER 2012 :

 DECLARE @float FLOAT
 SET @float = 12345678911.12
 SELECT CAST(@float AS decimal(18,8))

Result :
An arithmetic overflow error occurred when converting float to numeric data type.

the same query with DECIMAL(19,8) instead :

 DECLARE @float FLOAT
 SET @float = 12345678911.12
 SELECT CAST(@float AS decimal(19,8))

Result : 12345678911.12000100

EDIT : Check if your query tool fetchs all records. If not, maybe among the rest of records there are some values bigger than DECIMAL(18.8)


问:
MVC Request - Core .NET - Non HTML Response
I'm new to Core.NET and would greatly appreciate some enlightenment.

I've watched many PluralSight videos, and have Core .NET book 'Pro ASP.NET Core MVC'.

All very well cover Routing / Controller Initialization / Action Method Execution / Action Result / View Engine.  I'm hung up on the Non HTML Response though.  (Please see image below)

In Traditional ASP.NET if I wanted to call some class that did something and returned no value, I'd simply:

```<code>    //  Call Twilio class that sends a test message
        TwilioRest Send_Test_SMS = new TwilioRest();
        Send_Test_SMS.testSMS_Send();
</code>```

My question is:

How do I call the above class's function from the controller.

When adding a controller or when modifying a controller for that - do I need to alter or add something to the Startup.cs file

The course materials I have do a great job at covering returning HTML views - such as:

```<code>    //------book examples below-----
    public IActionResult Index()
    {

        return View();
    }

    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        return View();
    }
</code>```

But I feel like an idiot trying to do something so simple and would appreciate some insight into this.

Thank you in advance.

答:
So I'm not sure whether I got your point, but I guess you want to do sth like that:

```<code>//------book examples below-----
public IActionResult Index()
{
    //  Call Twilio class that sends a test message
    TwilioRest Send_Test_SMS = new TwilioRest();
    Send_Test_SMS.testSMS_Send();

    return Ok(); // Similiar meaning as => return StatusCode(200);
}
</code>```

It's up to your design / contract which status code you want to return here you can find a list of http codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

So to summarize you don't need to return 'HTML response', but obviously 'HTTP response'  must be returned.

If I misunderstood you then apologize.

Body:
I'm new to Core.NET and would greatly appreciate some enlightenment.

I've watched many PluralSight videos, and have Core .NET book 'Pro ASP.NET Core MVC'.

All very well cover Routing / Controller Initialization / Action Method Execution / Action Result / View Engine.  I'm hung up on the Non HTML Response though.  (Please see image below)

In Traditional ASP.NET if I wanted to call some class that did something and returned no value, I'd simply:

    //  Call Twilio class that sends a test message
        TwilioRest Send_Test_SMS = new TwilioRest();
        Send_Test_SMS.testSMS_Send();

My question is:

How do I call the above class's function from the controller.

When adding a controller or when modifying a controller for that - do I need to alter or add something to the Startup.cs file

The course materials I have do a great job at covering returning HTML views - such as:

    //------book examples below-----
    public IActionResult Index()
    {

        return View();
    }

    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        return View();
    }

But I feel like an idiot trying to do something so simple and would appreciate some insight into this.

Thank you in advance.

Body:
So I'm not sure whether I got your point, but I guess you want to do sth like that:

//------book examples below-----
public IActionResult Index()
{
    //  Call Twilio class that sends a test message
    TwilioRest Send_Test_SMS = new TwilioRest();
    Send_Test_SMS.testSMS_Send();

    return Ok(); // Similiar meaning as => return StatusCode(200);
}

It's up to your design / contract which status code you want to return here you can find a list of http codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

So to summarize you don't need to return 'HTML response', but obviously 'HTTP response'  must be returned.

If I misunderstood you then apologize.


问:
Scan for iBeacon upon receiving remote notification
I currently have an app setup to receive remote notifications using Azure Notification Hub.
Now, I would like to scan for iBeacons, see if a specific one is close by and if so, the notification should not be shown to the user. However, if the beacon isn't in sight, the user should receive this notification.

Basically I want the beacon to supress the notifications for this app.

How would one go about doing this?

答:
You can use some opensource library to work with beacons. I used Altbeacon library for example.
Here is the samples : https://altbeacon.github.io/android-beacon-library/samples.html
For your target you need to implement BeaconConsumer interface on Activity or Service. It has a method onBeaconServiceConnect(). Example of implementation:</p>

```<code>    @Override
    public void onBeaconServiceConnect() {
        beaconManager.addRangeNotifier(new RangeNotifier() {
            @Override
            public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
                if (beacons.size() == 0) {
                    Log.i(TAG, "Show your notification here");
                }
            }
        });

        try {
            beaconManager.startRangingBeaconsInRegion(new Region("someRangingUniqueId", null, null, null));
        } catch (RemoteException e) {    }
    }
</code>```

Body:
You can use some opensource library to work with beacons. I used Altbeacon library for example.
Here is the samples : https://altbeacon.github.io/android-beacon-library/samples.html
For your target you need to implement BeaconConsumer interface on Activity or Service. It has a method onBeaconServiceConnect(). Example of implementation:

    @Override
    public void onBeaconServiceConnect() {
        beaconManager.addRangeNotifier(new RangeNotifier() {
            @Override
            public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
                if (beacons.size() == 0) {
                    Log.i(TAG, "Show your notification here");
                }
            }
        });

        try {
            beaconManager.startRangingBeaconsInRegion(new Region("someRangingUniqueId", null, null, null));
        } catch (RemoteException e) {    }
    }


问:
Cannot install Support repository and sync project in Android Studio
I am trying to use the support libraries of version 25.2.0
so I will be able to use the CameraKit library.

I have got the newest build tools downloaded:

and the support repository:

my gradle file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    defaultConfig {
        applicationId "com.sample.myapp"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.1"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
repositories {
    maven {
        url "https://jitpack.io"
    }
    mavenCentral()
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'

    // Google libraries
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.google.android.gms:play-services-vision:10.0.1'
    compile 'com.android.volley:volley:1.0.0'

    // Third party libraries
    compile 'com.flurgle:camerakit:0.9.17'

    compile 'com.android.support:recyclerview-v7:25.2.0'
    compile 'com.android.support:cardview-v7:25.2.0'
}
</code>```

Problem:
For each support-library I get the issue:

```<code>Failed to resolve com.android.support:cardview-v7:25.2.0
</code>```

If I try to click on Install repository and sync project nothing happens.

I have followed that gradle file as an example. Were could be my mistake?

答:
Previously the Android Support Library dependencies were downloaded from Android SDK Manager.

Now all the new versions are available from Google's Maven repository.
In future all android libraries will be distributed through maven.google.com

So, by adding the below code to the repositories will build the project.

```<code>repositories {
    maven {
        url "https://maven.google.com"
    }
}
</code>```

Body:
I am trying to use the support libraries of version 25.2.0
so I will be able to use the CameraKit library.

I have got the newest build tools downloaded:

and the support repository:

my gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    defaultConfig {
        applicationId "com.sample.myapp"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.1"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
repositories {
    maven {
        url "https://jitpack.io"
    }
    mavenCentral()
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'

    // Google libraries
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.google.android.gms:play-services-vision:10.0.1'
    compile 'com.android.volley:volley:1.0.0'

    // Third party libraries
    compile 'com.flurgle:camerakit:0.9.17'

    compile 'com.android.support:recyclerview-v7:25.2.0'
    compile 'com.android.support:cardview-v7:25.2.0'
}

Problem:
For each support-library I get the issue:

Failed to resolve com.android.support:cardview-v7:25.2.0

If I try to click on Install repository and sync project nothing happens.

I have followed that gradle file as an example. Were could be my mistake?

Body:
Previously the Android Support Library dependencies were downloaded from Android SDK Manager.

Now all the new versions are available from Google's Maven repository.
In future all android libraries will be distributed through maven.google.com

So, by adding the below code to the repositories will build the project.

repositories {
    maven {
        url "https://maven.google.com"
    }
}


问:
How do I insert random characters into a sql database column?
I want to populate a column of my database table with 253 lines of 'M' and 'F' randomly placed in the column, is this possible?

Example of what it may look like:

```<code>Gender:
M
M
F
M
F
F
M
F
M
</code>```

答:
For MS SQL you can use NEWID and CHECKSUM functions like:

```<code>  UPDATE Users
  SET Gender = (CASE WHEN ABS(CHECKSUM(NEWID()) % 2) = 1 THEN 'M' ELSE 'F' END)
</code>```

NEWID() will generate random GUID

CHECKSUM() will generate hash of that GUID

ABS() to make it either 1 or 0

WARNING! While some people suggesting to use RAND function - please do not use it for this particular case. The query like this:

```<code>UPDATE Users SET Gender = CASE WHEN (RAND() > 0.5) THEN 'M' ELSE 'F' END
</code>```

.. will result that you have all values either M or either F.

Potentially you can seed RAND function with some value like Id, but distribution of values will be not very good: like first 30-40% all M, then 30-40% all F, then M again.

Body:
I want to populate a column of my database table with 253 lines of 'M' and 'F' randomly placed in the column, is this possible?

Example of what it may look like:

Gender:
M
M
F
M
F
F
M
F
M

Body:
For MS SQL you can use NEWID and CHECKSUM functions like:

  UPDATE Users
  SET Gender = (CASE WHEN ABS(CHECKSUM(NEWID()) % 2) = 1 THEN 'M' ELSE 'F' END)

NEWID() will generate random GUID

CHECKSUM() will generate hash of that GUID

ABS() to make it either 1 or 0

WARNING! While some people suggesting to use RAND function - please do not use it for this particular case. The query like this:

UPDATE Users SET Gender = CASE WHEN (RAND() > 0.5) THEN 'M' ELSE 'F' END

.. will result that you have all values either M or either F.

Potentially you can seed RAND function with some value like Id, but distribution of values will be not very good: like first 30-40% all M, then 30-40% all F, then M again.


问:
What is semantics?
So there are copy semantics, move semantics and maybe more semantics that I don't know of. I have read articles about both but I still do not really get have a good definition of "semantics". As the name suggests, move semantics have something to do with moving things but why is it called move semantics?

The more clear version: What is the meaning of semantics in the context of programming? Example: Move and copy semantics.

答:
Semantics basically means "the meaning of".

It may help to look at a more familiar case to explain the term.

Consider:

```<code>int a = 3;
int b = 5;

int c = a + b;
</code>```

The value of a + b is 8 because the semantics of the + operator is to take the numerical sum of its operands.

Now consider this:

```<code>std::string a = "hello";
std::string b = "world";

std::string c = a + b;
</code>```

The value of a + b is "helloworld" because the semantics of the + operator is to concatenate its operands.

The + operator, when used with std::string is said to have different semantics from when it is used with numerical types.

It has a different meaning.

Now consider copy and move semantics:

```<code>std::string a = "hello";
std::string b;

b = a; // b receives a copy of a's value

b = std::string("hello"); // the temporary value is moved into b
</code>```

We have the same operator = which has a different meaning in different situations. Again we say is has different semantics.

The first case has copy semantics and the second case has move semantics.

Title: What is semantics?

Body:
Semantics basically means "the meaning of".

It may help to look at a more familiar case to explain the term.

Consider:

int a = 3;
int b = 5;

int c = a + b;

The value of a + b is 8 because the semantics of the + operator is to take the numerical sum of its operands.

Now consider this:

std::string a = "hello";
std::string b = "world";

std::string c = a + b;

The value of a + b is "helloworld" because the semantics of the + operator is to concatenate its operands.

The + operator, when used with std::string is said to have different semantics from when it is used with numerical types.

It has a different meaning.

Now consider copy and move semantics:

std::string a = "hello";
std::string b;

b = a; // b receives a copy of a's value

b = std::string("hello"); // the temporary value is moved into b

We have the same operator = which has a different meaning in different situations. Again we say is has different semantics.

The first case has copy semantics and the second case has move semantics.


问:
Does upgrading jQuery UI 1.7.2 to 1.8.7 result in a performance improvement?
My site is only using dialogs and buttons from jQuery UI. In general things are working fine, but from time to time some users are facing light performance issues; the system is not as responsive as it should be in their opinion.

Upgrading from jQuery 1.4.2 to 1.4.4 really did a good job, because there are lots of find()/filter() calls in my code. Should I expect some performance benefits from upgrading jQuery UI?

答:
I would investigate your code first.

Use IDs instead of classes wherever possible.

Keep selection operations to a minimum by caching.
Especially true if you are doing this inside a block that gets called often.

For example:

```<code>if( $('#some-id').find('.foo').length > 0 ) {
  //do something with foos
  console.log($('#some-id').find('.foo'));
}
</code>```

should be

```<code>var $foos = $('#some-id .foo');
if( $foos.length > 0 ) {
  //do something with foos
  console.log($foos);
}
</code>```

AFTER you have investigated your code and tested.

I would go ahead and upgrade then retest on your local machine first in all browsers.
If everything is fine, why not upgrade?

Body:
I would investigate your code first.

Use IDs instead of classes wherever possible.

Keep selection operations to a minimum by caching.
Especially true if you are doing this inside a block that gets called often.

For example:

if( $('#some-id').find('.foo').length > 0 ) {
  //do something with foos
  console.log($('#some-id').find('.foo'));
}

should be

var $foos = $('#some-id .foo');
if( $foos.length > 0 ) {
  //do something with foos
  console.log($foos);
}

AFTER you have investigated your code and tested.

I would go ahead and upgrade then retest on your local machine first in all browsers.
If everything is fine, why not upgrade?


问:
Permutations with repetition without two consecutive equal elements
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

```<code>f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything
</code>```

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

```<code>from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l
</code>```

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

```<code>def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l
</code>```

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

```<code>for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())
</code>```

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

答:
Instead of filtering the elements, you could generate a list directly with only the correct elements. This method uses recursion to create the cartesian product:</p>

```<code>def product_no_repetition(iterable, r, last_element=None):
    if r == 0:
        return [[]]
    else:
        return [p + [x] for x in iterable
            for p in product_no_repetition(iterable, r - 1, x)
            if x != last_element]

for no_repetition in product_no_repetition([0, 1], 12):
    print(no_repetition)
</code>```

Body:
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

Body:
Instead of filtering the elements, you could generate a list directly with only the correct elements. This method uses recursion to create the cartesian product:

def product_no_repetition(iterable, r, last_element=None):
    if r == 0:
        return [[]]
    else:
        return [p + [x] for x in iterable
            for p in product_no_repetition(iterable, r - 1, x)
            if x != last_element]

for no_repetition in product_no_repetition([0, 1], 12):
    print(no_repetition)


问:
Best way of chaining reduce with Java 8
I have the following code that I'm trying to improve:

```<code>BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);
</code>```

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

答:
Or simply a forEach:

```<code>BigDecimal[] total = new BigDecimal[] { BigDecimal.ZERO };
entity.getAssociate().stream().forEach(a -> {
    total[0] = total[0].add(a.getPropertyA());
    // ... and so on for all others
});
</code>```

As a side-not your current implementation is wrong since you are violating the identity of the reduction.

Title: Best way of chaining reduce with Java 8

Body:
I have the following code that I'm trying to improve:

BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

Body:
Or simply a forEach:

BigDecimal[] total = new BigDecimal[] { BigDecimal.ZERO };
entity.getAssociate().stream().forEach(a -> {
    total[0] = total[0].add(a.getPropertyA());
    // ... and so on for all others
});

As a side-not your current implementation is wrong since you are violating the identity of the reduction.


问:
Exporting to Excel with JasperReports: How to add AutoFilter for columns
I am using this code for create report in MS Excel format:

```<code>JRXlsExporter exporter = new JRXlsExporter();
</code>```

From there I don't know if it's possible to tell JasperReports to apply an auto filter on each column.

答: I was facing the same issue i.e in my spreadsheet(.xls) I wanted to add auto filter to all the columns(15), so I have added one property(Properties expression )name = net.sf.jasperreports.export.xls.auto.filter and value as 'Start' at first column header and same property with value as End at last column header and it worked.</p>

Body:
I am using this code for create report in MS Excel format:

JRXlsExporter exporter = new JRXlsExporter();

From there I don't know if it's possible to tell JasperReports to apply an auto filter on each column.


问:
In practice, will a C# struct with a single member be as efficient as using that single member outside of a struct?
I am developing a library which internally passes around integer values which are not really integers but convenient containers of bits.

For my own sanity, I'd prefer to instead do this...

```<code>internal struct MyStruct
{
    private readonly int myInt;
    /* Constructor and get accessors. */
}
</code>```

... and pass around MyStruct values instead of int values. This way I can use my nice get accessors and the compiler will prevent me from using the wrong type.

Can I be reasonably sure that I've not introduced an inefficiency by doing this? It feels like once the compiler has done its thing, all uses of MyStruct should boil down to a simple int, taking up a single register just as an int would.

My experience tells me that single member structs do indeed compile down the way I would want them to, but I'm having trouble pinning that down to anything more than a gut feeling.

答:
This is only half an answer: I believe you are correct in that the struct member is simply part of the struct itself and therefore gets passed around the same way as an int would, as the struct and the int have the same size (though I can't find a definitive answer from the language spec).

However, there is a surprising performance penalty to be paid for making your member readonly. See John Skeet's explanation at https://codeblog.jonskeet.uk/2014/07/16/micro-optimization-the-surprising-inefficiency-of-readonly-fields/

I would therefore make your member non-readonly, and just not create any mutators for it.

Body:
I am developing a library which internally passes around integer values which are not really integers but convenient containers of bits.

For my own sanity, I'd prefer to instead do this...

internal struct MyStruct
{
    private readonly int myInt;
    /* Constructor and get accessors. */
}

... and pass around MyStruct values instead of int values. This way I can use my nice get accessors and the compiler will prevent me from using the wrong type.

Can I be reasonably sure that I've not introduced an inefficiency by doing this? It feels like once the compiler has done its thing, all uses of MyStruct should boil down to a simple int, taking up a single register just as an int would.

My experience tells me that single member structs do indeed compile down the way I would want them to, but I'm having trouble pinning that down to anything more than a gut feeling.


问:
How can I specify /debug:embedded from csproj?
I've authored a dotnet core library, which is packaged using NuGet. I want to embed the debug information (and the source code if that's possible) in the dll. rather than have a separate symbols package.

According to https://github.com/ctaggart/SourceLink it looks like this is possible when invoking the compiler directly by specifying some switches to the compiler. I don't understand how the csproj file relates to invocation of the compiler.

How can I specify the flag /debug:embedded from the csproj?

Here's my csproj:

```<code>    <Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard1.6</TargetFramework>
    <AssemblyName>KamailioApi</AssemblyName>
    <PackageId>KamailioApi</PackageId>
    <PackageTargetFallback>$(PackageTargetFallback);dnxcore50</PackageTargetFallback>
    <NetStandardImplicitPackageVersion>1.6.1</NetStandardImplicitPackageVersion>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
    <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
    <!-- don't change this we hack it in the TeamCity Build-->
    <Version>1.0.1</Version>
    <PackageVersion>1.0.1-beta</PackageVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
    <PackageReference Include="System.Runtime.Serialization.Formatters" Version="4.3.0" />
    <PackageReference Include="System.Xml.XmlDocument" Version="4.0.1" />
    <PackageReference Include="system.xml.xpath.xmldocument" Version="4.0.0" />
  </ItemGroup>

  <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.6' ">
    <PackageReference Include="System.Net.Requests" Version="4.3.0" />
  </ItemGroup>

</Project>
</code>```

答:
You can do this with the <DebugSymbols> and <DebugType> properties, like this:

```<code><PropertyGroup>
  <DebugSymbols>true</DebugSymbols>
  <DebugType>embedded</DebugType>
</PropertyGroup>
</code>```

Here's an example of where I do it with MiniProfiler, note that Directory.build.props applies to all .csproj files at or below that directory level so you can specify common things in larger projects one time.

Body:
I've authored a dotnet core library, which is packaged using NuGet. I want to embed the debug information (and the source code if that's possible) in the dll. rather than have a separate symbols package.

According to https://github.com/ctaggart/SourceLink it looks like this is possible when invoking the compiler directly by specifying some switches to the compiler. I don't understand how the csproj file relates to invocation of the compiler.

How can I specify the flag /debug:embedded from the csproj?

Here's my csproj:

    <Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard1.6</TargetFramework>
    <AssemblyName>KamailioApi</AssemblyName>
    <PackageId>KamailioApi</PackageId>
    <PackageTargetFallback>$(PackageTargetFallback);dnxcore50</PackageTargetFallback>
    <NetStandardImplicitPackageVersion>1.6.1</NetStandardImplicitPackageVersion>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
    <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>

    <Version>1.0.1</Version>
    <PackageVersion>1.0.1-beta</PackageVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
    <PackageReference Include="System.Runtime.Serialization.Formatters" Version="4.3.0" />
    <PackageReference Include="System.Xml.XmlDocument" Version="4.0.1" />
    <PackageReference Include="system.xml.xpath.xmldocument" Version="4.0.0" />
  </ItemGroup>

  <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.6' ">
    <PackageReference Include="System.Net.Requests" Version="4.3.0" />
  </ItemGroup>

</Project>

Body:
You can do this with the <DebugSymbols> and <DebugType> properties, like this:

<PropertyGroup>
  <DebugSymbols>true</DebugSymbols>
  <DebugType>embedded</DebugType>
</PropertyGroup>

Here's an example of where I do it with MiniProfiler, note that Directory.build.props applies to all .csproj files at or below that directory level so you can specify common things in larger projects one time.


问:
ANDROID How can I send result in a new Activity after scanning a QR Code?
Hello to everyone I'm trying to create an app that scan a QR Code.

In the main activity I want to make the scan of the QR Code and I want to send the result in a new Activity.

Here is my code

Main Activity.java:

```<code>public class MainActivity extends AppCompatActivity {

SurfaceView cameraView;
BarcodeDetector barcode;
CameraSource cameraSource;
SurfaceHolder holder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
    }

    cameraView = (SurfaceView) findViewById(R.id.cameraView);
    cameraView.setZOrderMediaOverlay(true);
    holder = cameraView.getHolder();
    barcode = new BarcodeDetector.Builder(this)
            .setBarcodeFormats(Barcode.QR_CODE)
            .build();
    if(!barcode.isOperational()){
        Toast.makeText(getApplicationContext(), "Sorry, Couldn't setup the detector", Toast.LENGTH_LONG).show();
        this.finish();
    }
    cameraSource = new CameraSource.Builder(this, barcode)
            .setFacing(CameraSource.CAMERA_FACING_BACK)
            .setRequestedFps(24)
            .setAutoFocusEnabled(true)
            .setRequestedPreviewSize(1920,1024)
            .build();
    cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try{
                if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
                    cameraSource.start(cameraView.getHolder());
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }
    });
    barcode.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {

        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            final SparseArray<Barcode> barcodes =  detections.getDetectedItems();
            if(barcodes.size() > 0){

                Intent intent = new Intent(MainActivity.this, Result.class);
                startActivityForResult(intent, 100);
                intent.putExtra("barcode", barcodes.valueAt(0));
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    });
}}
</code>```

Result.java:

```<code>public class Result extends AppCompatActivity {

TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    result = (TextView) findViewById(R.id.result);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == 100 && resultCode == RESULT_OK){
        if(data != null){
            final Barcode barcode = data.getParcelableExtra("barcode");
            result.post(new Runnable() {
                @Override
                public void run() {
                    result.setText(barcode.displayValue);
                }
            });
        }
    }
}}
</code>```

But when I try to test the app in the result activity i can't see the result.

What's wrong?

Thank you to everyone

答: You only use startActivityForResult if you want the starting activity to be returned with an result from the called activity. In your case just start the result activity by calling startActivity and get the data in the result activity by using getIntent.

Body:
Hello to everyone I'm trying to create an app that scan a QR Code.

In the main activity I want to make the scan of the QR Code and I want to send the result in a new Activity.

Here is my code

Main Activity.java:

public class MainActivity extends AppCompatActivity {

SurfaceView cameraView;
BarcodeDetector barcode;
CameraSource cameraSource;
SurfaceHolder holder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
    }

    cameraView = (SurfaceView) findViewById(R.id.cameraView);
    cameraView.setZOrderMediaOverlay(true);
    holder = cameraView.getHolder();
    barcode = new BarcodeDetector.Builder(this)
            .setBarcodeFormats(Barcode.QR_CODE)
            .build();
    if(!barcode.isOperational()){
        Toast.makeText(getApplicationContext(), "Sorry, Couldn't setup the detector", Toast.LENGTH_LONG).show();
        this.finish();
    }
    cameraSource = new CameraSource.Builder(this, barcode)
            .setFacing(CameraSource.CAMERA_FACING_BACK)
            .setRequestedFps(24)
            .setAutoFocusEnabled(true)
            .setRequestedPreviewSize(1920,1024)
            .build();
    cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try{
                if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
                    cameraSource.start(cameraView.getHolder());
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }
    });
    barcode.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {

        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            final SparseArray<Barcode> barcodes =  detections.getDetectedItems();
            if(barcodes.size() > 0){

                Intent intent = new Intent(MainActivity.this, Result.class);
                startActivityForResult(intent, 100);
                intent.putExtra("barcode", barcodes.valueAt(0));
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    });
}}

Result.java:

public class Result extends AppCompatActivity {

TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    result = (TextView) findViewById(R.id.result);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == 100 && resultCode == RESULT_OK){
        if(data != null){
            final Barcode barcode = data.getParcelableExtra("barcode");
            result.post(new Runnable() {
                @Override
                public void run() {
                    result.setText(barcode.displayValue);
                }
            });
        }
    }
}}

But when I try to test the app in the result activity i can't see the result.

What's wrong?

Thank you to everyone


问:
Switching MainPage in Xamarin Forms
I have 2 pages: Page1 and Page2. I start application with Page1:

```<code>MainPage = new NavigationPage(new Page1)
</code>```

After that i switch pages witch code:

```<code>MainPage = new NavigationPage(new Page2)
</code>```

And everything is ok. But, when i do this in reverse ( Page2 is first and switch with this method to Page1) i have exception:

ArgumentException: Handle must be valid. Parameter name: instance

Why?

答: You can try FreshMvvm, https://github.com/rid00z/FreshMvvm You can register Navigation stack with name and call CoreMethods.SwitchOutRootNavigation(NavigationContainerNames.MainContainer); to switch navigation stack.

Title: Switching MainPage in Xamarin Forms

Body:
I have 2 pages: Page1 and Page2. I start application with Page1:

MainPage = new NavigationPage(new Page1)

After that i switch pages witch code:

MainPage = new NavigationPage(new Page2)

And everything is ok. But, when i do this in reverse ( Page2 is first and switch with this method to Page1) i have exception:

ArgumentException: Handle must be valid. Parameter name: instance

Why?


问:
Add js scripts in the application.html.erb
I am new to rails, I know that we add our css and js files in application.html.erb file.

But do we also add the js scripts in the same file?

For example this script below

```<code>   <script>
    $(function () {
      $("#slider").responsiveSlides({
        auto: true,
        speed: 500,
        namespace: "callbacks",
        pager: true,
      });
    });
  </script>
</code>```

答:
You can add any scripts in application.html.erb, but i think will be better to require application.js in application.html.erb with javascript_include_tag:

```<code><%= javascript_include_tag "application" %>
</code>```

and include any scripts from javascript folder in application.js

```<code>//= require library_name
</code>```

Body:
You can add any scripts in application.html.erb, but i think will be better to require application.js in application.html.erb with javascript_include_tag:

<%= javascript_include_tag "application" %>

and include any scripts from javascript folder in application.js

//= require library_name


问:
How do you convert char to XElement in WPF C#?
How do you convert char to XElement.value from a XML file in WPF ? I've printed the tree elements, but not their values; I get the cannot convert from 'char' to 'System.Xml.Linq.XElement' argument.
Perphaps i'm iterating the wrong type ?

Thank you

```<code>    public partial class MainWindow : Window
   {
    string file1 = System.IO.File.ReadAllText(@"H:\MpxWpfComponents.strings.xsd");
    string file2 = System.IO.File.ReadAllText(@"H:\MpxWpfComponents.bg.strings.xml");
    string file3 = System.IO.File.ReadAllText(@"H:\MpxWpfComponents.fr.strings.xml");

    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnOpenFile_Click1(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
        openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        if (openFileDialog.ShowDialog() == true)
        {
            foreach (string filename in openFileDialog.FileNames)
                listXML.Items.Add(Path.GetFileName(filename));
        }
        var xmlDoc = XDocument.Parse(file2);
        BuildTree(treeView.Items, xmlDoc.Elements().First());
    }

    private void BuildTree(ItemCollection itemCollection, XElement xElement)
    {
        var item = new TreeViewItem() { Header = xElement.Name.LocalName };
        itemCollection.Add(item);
        foreach (var xElem in xElement.Elements())
        {
            BuildTree(item.Items, xElem);
        }

        item = new TreeViewItem() { Header = xElement.Value };
        itemCollection.Add(item);

        foreach (var xElem in xElement.Value)
        {
            BuildTree(item.Items, xElem);
        }
    }
</code>```

CS code

XAML code

答:
The Value property returns the text contents of the element. You want to iterate through the element's child elements:

```<code>private void BuildTree(ItemCollection itemCollection, XElement xElement)
{
    var item = new TreeViewItem() { Header = xElement.Name.LocalName };
    itemCollection.Add(item);
    foreach (var xElem in xElement.Elements())
    {
        BuildTree(item.Items, xElem);
    }

    item = new TreeViewItem() { Header = xElement.Value };
    itemCollection.Add(item);

    foreach (var xElem in xElement.Elements()) //<---
    {
        BuildTree(item.Items, xElem);
    }
}
</code>```

Body:
How do you convert char to XElement.value from a XML file in WPF ? I've printed the tree elements, but not their values; I get the cannot convert from 'char' to 'System.Xml.Linq.XElement' argument.
Perphaps i'm iterating the wrong type ?

Thank you

    public partial class MainWindow : Window
   {
    string file1 = System.IO.File.ReadAllText(@"H:\MpxWpfComponents.strings.xsd");
    string file2 = System.IO.File.ReadAllText(@"H:\MpxWpfComponents.bg.strings.xml");
    string file3 = System.IO.File.ReadAllText(@"H:\MpxWpfComponents.fr.strings.xml");

    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnOpenFile_Click1(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
        openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        if (openFileDialog.ShowDialog() == true)
        {
            foreach (string filename in openFileDialog.FileNames)
                listXML.Items.Add(Path.GetFileName(filename));
        }
        var xmlDoc = XDocument.Parse(file2);
        BuildTree(treeView.Items, xmlDoc.Elements().First());
    }

    private void BuildTree(ItemCollection itemCollection, XElement xElement)
    {
        var item = new TreeViewItem() { Header = xElement.Name.LocalName };
        itemCollection.Add(item);
        foreach (var xElem in xElement.Elements())
        {
            BuildTree(item.Items, xElem);
        }

        item = new TreeViewItem() { Header = xElement.Value };
        itemCollection.Add(item);

        foreach (var xElem in xElement.Value)
        {
            BuildTree(item.Items, xElem);
        }
    }

CS code

XAML code

Body:
The Value property returns the text contents of the element. You want to iterate through the element's child elements:

private void BuildTree(ItemCollection itemCollection, XElement xElement)
{
    var item = new TreeViewItem() { Header = xElement.Name.LocalName };
    itemCollection.Add(item);
    foreach (var xElem in xElement.Elements())
    {
        BuildTree(item.Items, xElem);
    }

    item = new TreeViewItem() { Header = xElement.Value };
    itemCollection.Add(item);

    foreach (var xElem in xElement.Elements()) //<---
    {
        BuildTree(item.Items, xElem);
    }
}


问:
Insert, Update, Delete for Oracle are not working in .NET C#?
It has been a while that i'm dealing with oracle and .net and they don't seem to be a perfect match together. That's this strange thing, i'm not finding any reason why it happens or how to fix it.

I do simple insert, update and delete and they are not working. It fails on the

```<code>cmd.ExecuteNonQuery();
</code>```

Here's the piece of code:

```<code>sqlCommand = string.Format(@" INSERT INTO TABLE_1
                              (ID, NAME, DESCRIPTION)
                              VALUES ((SELECT MAX(ID)+1 FROM TABLE_1),'{0}','{1}')", name, description);

using (OracleConnection conn = new OracleConnection(connectionString))
{
 OracleCommand cmd = new OracleCommand(sqlCommand, conn);
 cmd.CommandType = commandType;

 try
 {
  conn.Open();
  result = cmd.ExecuteNonQuery();
 }
 catch (Exception ex) { throw;}
 finally
 {
  conn.Close();
 }
</code>```

a simple insert, right?! when i debug, i get the cmd.Text value (that would be the sqlCommand), and i do execute it in the oracle db, it goes just fine. As i go the point of executing it in .Net it gives up.

Is this a known situation? Is there any solution, any explanation for it?

Thnx in advance

答: I had the same problem. I didn't have a clue how to solve it. When I run program wihout sqldeveloper running it went just fine. My answer to this question: close any other programas that uses connection to oracle from your computer. It went just fine for me.</p>

Body:
It has been a while that i'm dealing with oracle and .net and they don't seem to be a perfect match together. That's this strange thing, i'm not finding any reason why it happens or how to fix it.

I do simple insert, update and delete and they are not working. It fails on the

cmd.ExecuteNonQuery();

Here's the piece of code:

sqlCommand = string.Format(@" INSERT INTO TABLE_1
                              (ID, NAME, DESCRIPTION)
                              VALUES ((SELECT MAX(ID)+1 FROM TABLE_1),'{0}','{1}')", name, description);

using (OracleConnection conn = new OracleConnection(connectionString))
{
 OracleCommand cmd = new OracleCommand(sqlCommand, conn);
 cmd.CommandType = commandType;

 try
 {
  conn.Open();
  result = cmd.ExecuteNonQuery();
 }
 catch (Exception ex) { throw;}
 finally
 {
  conn.Close();
 }

a simple insert, right?! when i debug, i get the cmd.Text value (that would be the sqlCommand), and i do execute it in the oracle db, it goes just fine. As i go the point of executing it in .Net it gives up.

Is this a known situation? Is there any solution, any explanation for it?

Thnx in advance


问:
Procedure for creating a database locally using mongodb
I've connected to mLab using MongoClient.connect, but now I want to create a local database rather than use mLab. I've tried changing the URL to "mongodb://localhost:27017/mydb" to create a database locally as suggested, but I'm getting a failed to connect to server error. Is there anything I should install? Or am I just missing something?

答:
First, install your mongoDB server:
  https://docs.mongodb.com/manual/installation/

After that, you should be able to start your local mongodb server:

```<code>sudo service mongod start //in case of linux
</code>```

Here the docs to start the mongodb server

Then, you will type mongo and the client command line will start.
  And when typing use yourDatabase, mongo will create the database if
  it does not exist.

Then, your server will be up, and the database created. Anyway, check the docs if you need the guides for windows or other systems.

Body:
First, install your mongoDB server:
  https://docs.mongodb.com/manual/installation/

After that, you should be able to start your local mongodb server:

sudo service mongod start //in case of linux

Here the docs to start the mongodb server

Then, you will type mongo and the client command line will start.
  And when typing use yourDatabase, mongo will create the database if
  it does not exist.

Then, your server will be up, and the database created. Anyway, check the docs if you need the guides for windows or other systems.


问:
"Insufficient memory or insufficient privileges to attach " when capture the tomcat dump
I tried to capture the tomcat process dump with jmap , however I got the error " Insufficient memory or insufficient privileges to attach" , obviously there is enough memory, and the currently login user is in the role local administrator group. If I run the cmd command as administrator, it still failed.</p>

```<code>C:\Program Files\Java\jdk1.7.0_71\bin>jmap.exe -dump:format=b,file=d:\temp\HeapD
ump.hprof 30452
30452: Insufficient memory or insufficient privileges to attach
The -F option can be used when the target process is not responding
</code>```

答:
I ran into a similar scenario where we were running a jetty server wrapped as a windows service and I wanted to take a memory dump of it. I think most of the answers elsewhere on SO deals with situations where the process you want to take a dump of is not running as a windows service. This link helped.

Download PsExec and run jmap like this:

<path to psexec>PsExec.exe -s "C:\Program Files\Java\jd
k1.8.0_131\bin\jmap.exe" -dump:file=<filename> <processid>

Body:
I tried to capture the tomcat process dump with jmap , however I got the error " Insufficient memory or insufficient privileges to attach" , obviously there is enough memory, and the currently login user is in the role local administrator group. If I run the cmd command as administrator, it still failed.

C:\Program Files\Java\jdk1.7.0_71\bin>jmap.exe -dump:format=b,file=d:\temp\HeapD
ump.hprof 30452
30452: Insufficient memory or insufficient privileges to attach
The -F option can be used when the target process is not responding


问:
auto enter vr mode in aframe without clicking vr button
HI I'm developing VR cordova app based on aframe framework.

In My app user must click on enter vr button every time he wished to enter in vr mode. but actually it should start vr mode witout any enter vr button click.I have tried in online for solution but nothing helped me to complete my requirement. i even tried jquery for auto click for but it's not working because its loading to slow or anything else i didn't know exact reason. I'm looking for simple solution that user can enter vr mode by default. I mean without clicking any button.

Hope i will get better answer here and example.

Thanks for your help in advance.

答:
Have you tried</p>

```<code>document.querySelector('a-scene').enterVR()
</code>```

Body:
Have you tried

document.querySelector('a-scene').enterVR()


问:
Indexing across multiple intervals
I am trying to extract the n-th element from a set of multiple intervals. I am currently dealing with genome sequences. Assume we have a gene with a gap in the middle. The position of this gene within the whole DNA is:

```<code>gene = [100,110], [130,140]
# representing the lists [100,101,...,109] and [130, 131,...,139]
# the gene spans over these entries of the DNA, so it looks like -gene-gap-gene-
</code>```

Now, for a position within the gene (e.g. 10th position), I want to find the corresponding position on the whole DNA (which would be 109 in this example).
The function should do the following:

```<code>function(gene, 9)
> 109
function(gene, 10)
> 130
</code>```

My approach is to explicitly generate the two sequences, concatenate them and take the n-th element of this list. However, for large lists (as they happen to occur), this is very inefficient.

Can anyone think of a simple way?

Thanks in advance!

答:
A generic solution, should work for as many gaps in the gene as you want:</p>

```<code>gene = [[100,110], [130,140]]

def function(gene, n):
    for span in gene:
        span_len = span[1] - span[0]
        if n <= span_len:
            return n + span[0] - 1
        else:
            n -= span_len

print(function(gene,10))
print(function(gene,11))
</code>```

Title: Indexing across multiple intervals

Body:
I am trying to extract the n-th element from a set of multiple intervals. I am currently dealing with genome sequences. Assume we have a gene with a gap in the middle. The position of this gene within the whole DNA is:

gene = [100,110], [130,140]
# representing the lists [100,101,...,109] and [130, 131,...,139]
# the gene spans over these entries of the DNA, so it looks like -gene-gap-gene-

Now, for a position within the gene (e.g. 10th position), I want to find the corresponding position on the whole DNA (which would be 109 in this example).
The function should do the following:

function(gene, 9)
> 109
function(gene, 10)
> 130

My approach is to explicitly generate the two sequences, concatenate them and take the n-th element of this list. However, for large lists (as they happen to occur), this is very inefficient.

Can anyone think of a simple way?

Thanks in advance!

Body:
A generic solution, should work for as many gaps in the gene as you want:

gene = [[100,110], [130,140]]

def function(gene, n):
    for span in gene:
        span_len = span[1] - span[0]
        if n <= span_len:
            return n + span[0] - 1
        else:
            n -= span_len

print(function(gene,10))
print(function(gene,11))


问:
NSAttributedString to HTML in iOS Swift 3
I have searched a lot but can only find HTML to plain text, not the other way around, I have email implementation in my app, thus need to send the content of email as HTML to the backend.

Edit 1: I have rich text that includes bold, italic, ordered/unordered list, underlined words.

答:
If you are looking to convert NSAttributedString to String, here is the extension method you are looking for. Simply call yourAttributtedString.htmlString() and print it out.

```<code>extension NSAttributedString {
    func htmlString() -> String? {
        let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
        do {
            let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
            if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) {
                return htmlString
            }
        }
        catch {}
        return nil
    }
}
</code>```

Body:
If you are looking to convert NSAttributedString to String, here is the extension method you are looking for. Simply call yourAttributtedString.htmlString() and print it out.

extension NSAttributedString {
    func htmlString() -> String? {
        let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
        do {
            let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
            if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) {
                return htmlString
            }
        }
        catch {}
        return nil
    }
}