text:
Q: Does anyone know any API for OCRing 7-Segment Display for Windows Phone? I'm trying to develop a Windows Phone 8.1 App but I need to recognize some numbers from different Displays.

I was following this example:
http://bsubramanyamraju.blogspot.com/2014/08/windowsphone-81-optical-character.html
That is using the Microsoft OCR Runtime Library:
https://www.nuget.org/packages/Microsoft.Windows.Ocr/
However, it doesn't work when I'm trying to recognize those kinds of pics. Even I found this site:
https://www.unix-ag.uni-kl.de/~auerswal/ssocr/
Does anyone have a recommendation? Or Does anyone know any code related to it?
Thank for your worthy knowledge.

A: I wish the answer to your question would be "Sure, here it is" with link to a black-box process-anything OCR tool, but there are several aspects involved, which are best considered separately.
First, there is some work on image pre-processing BEFORE you even consider any OCR.  Your image samples are very drastically different, and include full range of issues.
SAMPLE 1 has low contrast, so when it is binarized to black and white layer, which most OCR will perform internally at some stage, there are no characters to process.  It looks like this after binarization:

See this OCR Blog post for additional details on image pre-processing: http://www.ocr-it.com/guide-to-better-mobile-images-from-cell-phone-camera-for-higher-quality-ocr.
Secondly, the image has no dpi information in the header, which some OCR technologies use to determine appropriate scaling of the image.  Without header information, some OCR programs may set some default dpi, which may or may not match your image, thus affecting the OCR result.  This is NOT critical, but preferred if this can be implemented at the time of picture creation.
SAMPLE 2 has sufficient contrast and adaptive notarization returns a clear image.  It is also missing dpi resolution value in the header.

SAMPLE 3 has very clear contrast, but it also has no resolution dpi in the header.
Once you have images that are optimized for OCR processing, the next step is to look at OCR technologies.
I did NOT test the once you mentioned, assuming you had correct implementation and yet no success with them.  I tested other OCR tools I have used in the past.
In general, there is no 7-segment OCR known to me. However, I was able to adapt to other generic OCR for this specialized task.  Every OCR I tried'out-of-box' or with default settings is unable to handle this recognition. And it is logical and expected. Why? Because most generic OCR are written to recognize inseparable pixel patterns for each character. This is related to the "character separability" principle used to separate words into separate characters. In other words, inner OCR algorithms look for connected strokes which make up each character. More powerful commercial OCR allows some breaks in pixel patterns, but they are expected to be minimal to none, like defects in print or scan, which may result in missing character pieces.
7-segment display by nature will have multiple breaks in each character, conflicting with the character separability principle.
More powerful OCR technologies have a) more tolerance to breaks in pixel patterns and/or b) have special settings to handle these cases.
I will perform further testing with OCR-IT web-based OCR API platform, which is well known to me.  I worked as a developer on its OCR capabilities.  I also use it extensively in my own iOS and Android apps.  OCR-IT API is based on a strong commercial OCR engine, so it is having good tolerance to character imperfections as well as some controls to help in this case.
SAMPLE 3.  This is the easiest sample to process, so I tested it first. Using OCR-IT API, and making a request with default settings, requesting the output to TXT format, I get the following:

It appears that OCR is a) segmenting characters into two separate lines, and b) tries to read resulting patters as close as possible to valid characters.

Based on this quick analysis, making one adjustments to OCR settings results in the following recognition:

The setting that made substantial difference in OCR result is switching from default print type to using "DotMatrix", which is in the middle of this entire OCR-IT API settings XML:

<Job>
 <InputURL>http://i.stack.imgur.com/wOtFx.jpg</InputURL>
  <CleanupSettings>
      <Deskew>false</Deskew>
      <RemoveGarbage>false</RemoveGarbage>
      <RemoveTexture>false</RemoveTexture>
      <RotationType>NoRotation</RotationType>
  </CleanupSettings>
  <OCRSettings>
      <PrintType>DotMatrix</PrintType>
      <OCRLanguage>English</OCRLanguage>
      <SpeedOCR>false</SpeedOCR>
      <AnalysisMode>MixedDocument</AnalysisMode>
      <LookForBarcodes>false</LookForBarcodes>
  </OCRSettings>
  <OutputSettings>
      <ExportFormat>Text</ExportFormat>
  </OutputSettings>
</Job>

The use of DotMatrix print type turned on necessary algorithms to increase tolerance for breaks in character structure, which commonly occurs by nature of dot-matrix printers in dot-matrix prints.  Alternatively, a "Typewriter" print type could be used, since character breaks are also expected in typewritten fonts, thus being automatically handled by OCR.
There could be one more change to the API setting to run OCR using "Digits" character set (language), effectively eliminating any possibility of misreading 1 as I, etc.
SAMPLE 2. In this sample, the gaps in each character's structure are much wider.  Even standard algorithms for handling DotMatrix or Typerwriter print types cannot accommodate these wide gaps. The use of all possible setting variations returned something like this:

Character segmentation seems to be the issue.  One technical solution goes back to image pre-processing. A simple algorithm can be implemented to fill in gaps between each segment of the 7-segment character. It does not have to be very precise, something like this:

But that is enough to produce a perfect OCR result.

Since it may be unknown in advance which 7-segment LCD display will require filled in gaps, and which does not, I recommend applying this algorithm to all LCD 7-segment images, with small or large gaps. I would limit the size of the gap to no wider than the width of a segment. Given these screens come in various background and segment colors, this pre-procession algorithm can be substantially simplified if it is performed on binarized (black & white) image.
Overall, this task is possible with OCR and near out-of-box functionality, assuming that some image pre-processing is performed.  In general, I believe that image pre-processing is required for any OCR-related project anyway, specific to that project.
If you have any further questions about OCR or image pre-processing, pm me.

A: Despite it has been a while since Ilya's answer and thanks to his advice and other ones, especially this one:
Seven Segment Optical Character Recognition
I was able to create my own class in C#:
https://github.com/FANMixco/7-segment-ocr-reader/blob/master/OCR/SevenSegmentOCR.cs
Feel free to use it and improve it.


text:
Q: мобильное приложение на nodejs Ребят, подскажите пожалуйста, имеется ли возможность написать гибридное приложение на cordova с применением nom пакетов для этого приложения? Может не совсем корректно вопрос звучит, я опишу суть своей проблемы. пишу гибридное приложение для смартов на apache cordova и пришла нужда использовать модуль камеры смартфона со своим интерфейсом камеры. соответственно пришла мысль взять пакет npm для веб-камеры. однако, всем известен тот фак, что nodejs - это бекэнд - меня сильно смущает. просто упаковав приложение для мобильника (тот же андроид - apk файл) и запустив его на своем нтс будет ли работать это приложение?

A: Не будет. Совет - кроме стандартного кордовского плагина есть же еще js-библиотеки для работы с камерой
http://bridgeit.github.io/demo-vanilla/menu.html
https://stackoverflow.com/questions/35073984/launch-android-phone-front-camera-by-html5-or-javascript

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to restore div which is hidden using empty() function

html code:
<button id="add"></button>

        Total:
        <input type="text" class="txtbox search" placeholder="Search" id="search">

Jquery code:
$("#add").click(function(){
       $("#count_search").empty();
})

I want to show count_search div once again on clicking on any other button execpt to add button
In above code add is button on which empty() is implimented. On clicking on add button count_search is got hide. Then after I want to restore that div content

A: .empty() deletes the elements in your container (count_search).
Instead, you can use .hide()/.show() or better approach, you can use .toggle() that show or hide your element.

$("#add2").click(function() {
    $("#count_search").toggle();
});
$("#add").click(function() {

    if ($("#count_search").is(":visible")) {
        $("#count_search").hide();
    } else {
        $("#count_search").show();
    }
});

<button id="add">Show/Hide</button>
<button id="add2">Toggle</button>

   Total:
   <input type="text" class="txtbox search" placeholder="Search" id="search">

A: By empty() you are deleting an item in DOM.
 Instead of empty, you can use toggle(), which hides the element and If you click once again, the item will show.
$("#add").click(function(){
       $("#count_search").hide();
})


text:
Q: JWT token authentication fails with message "PII is hidden" in my .net core 2.2 microservice, I try to extract claims from a JWT token to do some authorization. authentication is done on another part of the system so I don't need to do it at this point.
I am using this code in the Startup.cs:
  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                var signingKey = Encoding.UTF8.GetBytes("SECRET_KEY");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    IssuerSigningKey = new SymmetricSecurityKey(signingKey)
                };
            });

On the controller I have this code:
    [Authorize]
    [HttpPost]
    public async Task<ActionResult<CreateResponse>> Create()
    {
        var userIdClaim = HttpContext.User.Claims.Where(x => x.Type == "empId").SingleOrDefault();
        return Ok($"Your User ID is {userIdClaim.Value} and you can create invoices!");
    }

I always get this error message and "Unauthorized" response:

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10503: Signature validation failed. Keys tried: '[PII is hidden]'.
  Exceptions caught:
   '[PII is hidden]'.
  token: '[PII is hidden]'.

A: You can see the hidden details in development by adding the following to Configure() in the Startup class:
if (env.IsDevelopment())
{
     IdentityModelEventSource.ShowPII = true;
}

Once you have the full message check the key being used is correct for the token.


text:
Q: Android bitmap crop 5 or more corners I'm working crop operations on bitmaps.
Giving starting point, height, width,  easy clipping.Like this
lastImage = Bitmap.createBitmap(firstImage,x,y,width, height);

In this way, an area can be cut rectangle. But i dont want this for somae cases. It can be 5 or more sides(ex:pentagon). It sometimes goes out to the edge crop areas. I'm trying to tell this;

How i can crop image with this area. I am using OpenCV for image processing. Can I use it for this process.


text:
Q: Show image of product by browsing select2 options I have the latest version of select2 collection of products, and i want to show the image of the product on a single img tag dynamically according to my select2 cursor while I'm browsing for the product so I can make sure that the product i'm about to choose is the right product since some product have a similiar name.
My select2 options is based on the chosen customer ny onchange using ajax
so far I tried to use 'on' and select2:selecting listener, and it's not working.
here's my progress:
the html:
<select type="text" class="js-example-basic-single"
    style="width: 100%" id="search" onchange="toCart()">
</select>

the JQuery:
$('#search').on('select2:selecting', function () {
    console.log($(this).val());
});

If you find my question is vague, please kindly leave a comment so I can improve my question. thank you.

A: It sounds for me like you are looking for a way to get the highlighted option text and value from the select2 dropdown menu.
The selecting event is not made for this. It is fired just before you select something, in the moment you click on it or press enter.
select2 doesn't provide a "highlight/hover"-event and getting the highlighted field requires you to use the capture-event-phase or a mutation observer if you don't want to modify it.
Here is an example with the capture events:

$('#example').select2()
  .on("select2:opening", () => ($(img).show(), onHighlight()))
  .on("select2:closing", () => ($(img).hide(), onHighlight()));

function onHighlight(event) {
  /*
     both events are stopped at the element to prevent the
     page from scrolling when using arrow keys from within
     the search field

     this means, the capture phase is required and since the
     dropdown is not build when the event triggers, you have
     to wait for a short moment with setTimeout or
     requestAnimationFrame
   */
  setTimeout(() => {
    // only for the "#example" select2
    const el = document.querySelector(`[id^="select2-example-"].select2-results__option--highlighted`);
    if (el) {
      // depending on the id of the original select, the value to slice differs
      const value = el.id.split("-").slice(4).join("-"),
        text = el.innerText;
      // set the image matching the text and value
      img.src = `https://dummyimage.com/300x100/000/ffffff?text=value:${value}+text:${text}`;
      console.log(value, text);
    }
  });
}
document.body.addEventListener("mouseenter", onHighlight, true);
document.body.addEventListener("keydown", onHighlight, true);
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>

<select id="example" multiple="multiple" style="width: 100%;">
    <option value=0>January</option>
    <option value=1>February</option>
    <option value=2>March</option>
    <option value=3>April</option>
    <option value=4>May</option>
    <option value="Än Êxámplè">Foobar</option>
</select>

A: The select2 events do not appear to cater for your scenario.
The select2:selecting event is a "pre-select" - ie the user has selected an element and the event allows your code to cancel that selection.
With the templateResult templating built-in to select2, you can create any DOM in the drop down and thus apply events to those DOM elements.

Unfortunately, as noted in the comments, each select2 li has some padding/border that means using an event on the inner (templated) element will not trigger on the whole of the li, even with some mitigation such as setting 100% width.
Instead, you can listen on .select2-results__option

Then you just need to add enough information to the inner templated html so that you can create your preview.  Here's an example using the original <option> value=:

$('.select2').select2({
  templateResult: template
});

function template(state) {
  if (!state.id) {
    return state.text;
  }
  var $state = $(`<span class='mySelect2Option' data-value='${state.element.value}'>` +
    state.element.text +
    "");
  return $state;
}

$(document).on("mouseenter", ".select2-results__options>.select2-results__option", function() {
  var option = $(this).find(".mySelect2Option");
  $("#preview").text(option.data("value"))
});
#preview {
  float: right;
  margin-right: 5em; /* so not hidden by [result] */
  width: 2em;
  border: 1px solid #ccc;
  padding: 1em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />

<select class="select2">
  <option value="AL">Alabama (longer entry)</option>
  <option value="AK">Alaska</option>
  <option value="AZ">Arizona</option>
</select>


text:
Q: Error deleting Target Group: ResourceInUse when changing target ports in AWS through Terraform I am currently working through the beta book "Terraform Up & Running, 2nd Edition". In chapter 2, I created an auto scaling group and a load balancer in AWS.
Now I made my backend server HTTP ports configurable. By default they listen on port 8080.
variable "server_port" {
    …
    default = 8080
}

resource "aws_launch_configuration" "example" {
    …
    user_data = <<-EOF
                #!/bin/bash
                echo "Hello, World" > index.html
                nohup busybox httpd -f -p ${var.server_port} &
                EOF
    …
}

resource "aws_security_group" "instance" {
    …
    ingress {
        from_port = var.server_port
        to_port = var.server_port
        …
    }
}

The same port also needs to be configured in the application load balancer's target group.
resource "aws_lb_target_group" "asg" {
    …
    port = var.server_port
    …
}

When my infrastructure is already deployed, for example with the configuration for the port set to 8080, and then I change the variable to 80 by running terraform apply --var server_port=80, the following error is reported:
> Error: Error deleting Target Group: ResourceInUse: Target group
> 'arn:aws:elasticloadbalancing:eu-central-1:…:targetgroup/terraform-asg-example/…'
> is currently in use by a listener or a rule   status code: 400,

How can I refine my Terraform infrastructure definition to make this change possible? I suppose it might be related to a lifecycle option somewhere, but I didn't manage to figure it out yet.

For your reference I attach my whole infrastructure definition below:
provider "aws" {
    region = "eu-central-1"
}

output "alb_location" {
    value = "http://${aws_lb.example.dns_name}"
    description = "The location of the load balancer"
}

variable "server_port" {
    description = "The port the server will use for HTTP requests"
    type = number
    default = 8080
}

resource "aws_lb_listener_rule" "asg" {
    listener_arn = aws_lb_listener.http.arn
    priority = 100

    condition {
        field = "path-pattern"
        values = ["*"]
    }

    action {
        type = "forward"
        target_group_arn = aws_lb_target_group.asg.arn
    }
}

resource "aws_lb_target_group" "asg" {
    name = "terraform-asg-example"
    port = var.server_port
    protocol = "HTTP"
    vpc_id = data.aws_vpc.default.id

    health_check {
        path = "/"
        protocol = "HTTP"
        matcher = "200"
        interval = 15
        timeout = 3
        healthy_threshold = 2
        unhealthy_threshold = 2
    }
}

resource "aws_lb_listener" "http" {
    load_balancer_arn = aws_lb.example.arn
    port = 80
    protocol = "HTTP"

    default_action {
        type = "fixed-response"

        fixed_response {
            content_type = "text/plain"
            message_body = "404: page not found"
            status_code = 404
        }
    }
}

resource "aws_lb" "example" {
    name = "terraform-asg-example"
    load_balancer_type = "application"
    subnets = data.aws_subnet_ids.default.ids
    security_groups = [aws_security_group.alb.id]
}

resource "aws_security_group" "alb" {
    name = "terraform-example-alb"

    ingress {
        from_port = 80
        to_port = 80
        protocol = "tcp"
        cidr_blocks = ["0.0.0.0/0"]
    }

    egress {
        from_port = 0
        to_port = 0
        protocol = "-1"
        cidr_blocks = ["0.0.0.0/0"]
    }
}

resource "aws_autoscaling_group" "example" {
    launch_configuration = aws_launch_configuration.example.name
    vpc_zone_identifier = data.aws_subnet_ids.default.ids

    target_group_arns = [aws_lb_target_group.asg.arn]
    health_check_type = "ELB"

    min_size = 2
    max_size = 10

    tag {
        key = "Name"
        value = "terraform-asg-example"
        propagate_at_launch = true
    }
}

resource "aws_launch_configuration" "example" {
    image_id = "ami-0085d4f8878cddc81"
    instance_type = "t2.micro"
    security_groups = [aws_security_group.instance.id]

    user_data = <<-EOF
                #!/bin/bash
                echo "Hello, World" > index.html
                nohup busybox httpd -f -p ${var.server_port} &
                EOF
    lifecycle {
        create_before_destroy = true
    }
}

resource "aws_security_group" "instance" {
    name = "terraform-example-instance"

    ingress {
        from_port = var.server_port
        to_port = var.server_port
        protocol = "tcp"
        cidr_blocks = ["0.0.0.0/0"]
    }
}

data "aws_subnet_ids" "default" {
    vpc_id = data.aws_vpc.default.id
}

data "aws_vpc" "default" {
    default = true
}

A: From the issue link in the comment on Cannot rename ALB Target Group if Listener present:
Add a lifecycle rule to your target group so it becomes:
resource "aws_lb_target_group" "asg" {
    name     = "terraform-asg-example"
    port     = var.server_port
    protocol = "HTTP"
    vpc_id   = data.aws_vpc.default.id

    health_check {
      path                = "/"
      protocol            = "HTTP"
      matcher             = "200"
      interval            = 15
      timeout             = 3
      healthy_threshold   = 2
      unhealthy_threshold = 2
    }

    lifecycle {
      create_before_destroy = true
    }
}

However you will need to choose a method for changing the name of your target group as well. There is further discussion and suggestions on how to do this.
But one possible solution is to simply use a guid but ignore changes to the name:
resource "aws_lb_target_group" "asg" {
    name     = "terraform-asg-example-${substr(uuid(), 0, 3)}"
    port     = var.server_port
    protocol = "HTTP"
    vpc_id   = data.aws_vpc.default.id

    health_check {
      path                = "/"
      protocol            = "HTTP"
      matcher             = "200"
      interval            = 15
      timeout             = 3
      healthy_threshold   = 2
      unhealthy_threshold = 2
    }

    lifecycle {
      create_before_destroy = true
      ignore_changes        = [name]
    }
}

A: Slightly simpler than @FGreg's solution, add a lifecycle policy and switch from name to name_prefix which will prevent naming collisions.
resource "aws_lb_target_group" "asg" {
    name_prefix = "terraform-asg-example"
    port = var.server_port
    protocol = "HTTP"
    vpc_id = data.aws_vpc.default.id
    lifecycle {
        create_before_destroy = true
    }

    health_check {
        path = "/"
        protocol = "HTTP"
        matcher = "200"
        interval = 15
        timeout = 3
        healthy_threshold = 2
        unhealthy_threshold = 2
    }
}

No need for uuid or ignore_changes settings.

A: change name = "terraform-asg-example"
to
name_prefix = "asg-"


text:
Q: Can create and delete files on mounted file system yet not create links or change ownership I have a Xubuntu install running in a VM (VirtualBox) on a Windows 10 host. There is a directory on the Windows file system which I have mounted in the guest as a vboxsf. I think it's a Linux problem but that's the background in case it's relevant.
I have write access to this directory and all files within it (everything is -rwxrwxrwx). I can create, modify and delete files and directories in it. But trying to create a soft link (ln -s) or chown a file or directory to a different owner produces the following message:
ln: failed to create symbolic link 'myLink': Read-only file system

Have tried everything I can think of including unmounting and re-mounting. I don't understand how I am able to write, modify and delete files, yet a symbolic link produces "read only". Chown completes without an error or warning, but still hasn't changed ownership when done.

A: So eventually I found the answer to this. It's a bug / design decision in VirtualBox itself. See here:
https://www.virtualbox.org/ticket/10085
They used to support it and then realised it enabled a very hard to fix security vulnerability and so deliberately disabled linking in their shared folders. There's no great work around. You can edit your
to add the following:
<ExtraDataItem name="VBoxInternal2/SharedFoldersEnableSymlinksCreate/SHARE_NAME" value="1"/>

That comes with security risks so you must trust your guest. You can also (and this is what I might do) create an NFS mount point and connect to it in more old school ways.


text:
Q: Update an array in a sub-document - mongoose mongodb Suppose I have a model created like this:
const attendance = mongoose.Schema({
    studentName: {type: String, required: true},
    status: {type: Number, required: true}
});

const session = mongoose.Schema({
    sessionName: {type: String, required: true},
    attendances: {type: [attendance]}
});

const subjectSchema = mongoose.Schema({
    name: {type: String, required: true},
    faculty_ID: {type: String, required: true},
    students: {type: [String]},
    sessions: {type:[session]}
});

module.exports = mongoose.model('Subject', subjectSchema);

And a sample document from that looks like this:
{
    students: [
        "Student1",
        "Student2",
        "Student3"
    ],
    _id: "5bd5a6f49097cd505cf6317a",
    name: "subjectName",
    faculty_ID: "5bd57383bbe10f4f6439ae43",
    sessions: [
        {
            attendances: [ ],
            _id: "5bd6c4de95ffe03480ee8796",
            sessionName: "Session1"
        },
        {
            attendances: [ ],
            _id: "5bd7a9d2604b760004947833",
            sessionName: "Session2"
        },
        {
            attendances: [ ],
            _id: "5bd7a9e4604b760004947834",
            sessionName: "Session3"
        }
    ]
}

What would be the best way to push a new element in one of the attendances array inside sessions?
Like I want to push this:
{
    studentName: "Student1",
    status: "Present"
}

into the attendances array in the object with sessionName: "Session1" so that the document would then look like this:
{
    students: [
        "Student1",
        "Student2",
        "Student3"
    ],
    _id: "5bd5a6f49097cd505cf6317a",
    name: "subjectName",
    faculty_ID: "5bd57383bbe10f4f6439ae43",
    sessions: [
        {
            attendances: [
               {
                   studentName: "Student1",
                   status: "Present"
               }
            ],
            _id: "5bd6c4de95ffe03480ee8796",
            sessionName: "Session1"
        },
        {
            attendances: [ ],
            _id: "5bd7a9d2604b760004947833",
            sessionName: "Session2"
        },
        {
            attendances: [ ],
            _id: "5bd7a9e4604b760004947834",
            sessionName: "Session3"
        }
    ]
}

Also, if I'm already successful in pushing new elements on that array, how would I remove a specific element on that array?

A: You can use the $ positional operator to indicate which session should be modified. Try:
Model.updateOne({ _id: "5bd5a6f49097cd505cf6317a", "sessions._id": "5bd6c4de95ffe03480ee8796" },
    { $push: { "sessions.$.attendances": {  studentName: "Student1", status: "Present" } } })

To remove the value you need the same operator and $pull which takes condition as a parameter, for instance:
Model.updateOne({ _id: "5bd5a6f49097cd505cf6317a", "sessions._id": "5bd6c4de95ffe03480ee8796" },
    { $pull: { "sessions.$.attendances": {  studentName: "Student1" } } })


text:
Q: Swift navigation controller - Hide view I have a problem with the navigation controller and the view. However, I have created a view with a constraint: "Top Space to: Top Layout Guide : 0". I get this result with the simulator:

How to get the view correctly?
Thank you!
EDIT :
The problem is the top of the view is hidden by the navigation controller. On my screenshot, you can see that the segmented control is cut ! The top of the view is not show, even in the storyboard file.

A: Use edgesForExtendedLayout property to report which edges of your view controller extend underneath navigation bars or other system-provided views.
self.edgesForExtendedLayout = []

A: Select your view controller from stoaryboard,then unselect the
Adjust Scrollview Insets


text: Q: Error 6013 when adding view (PostgreSql) warning 6013: The table/view 'view_name' does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it.


text:
Q: Does itext support JPEG 2000? I would like to package a jpeg 2000 file as a PDF. Does itext support this?
I looked at the repo on github ( https://github.com/itext/itextpdf ) but it is hard to tell if there is support. Googling didn't turn up anything useful.
Thanks!

A: Since you mention Googling: when I Google for itext+jpeg2000,the first hit points to the API documentation: http://api.itextpdf.com/itext/com/itextpdf/text/Jpeg2000.html
Since you mention our GitHub repository: searching for jpeg2000 in that repository, points to the class with the Jpeg2000 implementation: https://github.com/itext/itextpdf/blob/develop/src/main/java/com/itextpdf/text/Jpeg2000.java
So the answer to your question is: yes.


text:
Q: Let $A=\{0,1\}$. How many strings of length $5$ are in $A^*$ where at least two $1$ are next to each other? Let $A=\{0,1\}$. How many strings of length $5$ where at least two $1$ next to each other are there in $A^*$?

A: Hint: it's easier to count the opposite (the number of strings of length five that do not contain "11") and subtract that number from the total number of strings of length five.

A: You could count the total number of possible strings, and then subtract the number of strings that do not contain any appearance of $11$.
Lets consider a more general case, where the strings you are interested in have length $n$ (in your case $n=5$).
We want to count the number $T(n)$ of strings that do not have $11$ in them.
Any such sequence (like any binary string), will start with either $0$ or $1$.

*

*If it starts with $0$, then the next entry (second bit) can be either $0$ or $1$; there is no restriction. Therefore, the remaining $n-1$ entries can be any binary string of length $n-1$ not containing consecutive ones. How many such sequences are there? Based on our definition, $T(n-1)$.

*If it starts with $1$, then we know that the next entry cannot be $1$ because then there would be a $11$ in the sequence. The second entry has to be $0$, and we only have the freedom to choose the value of the remaining $n-2$ entries. Of course, once again, we have to do that in a way that the substring of length $n-2$ also does not contain $11$. Hence, the number of such strings is $T(n-2)$.

The above cover all possible cases. We conclude that
$$
T(n) = T(n-1)+T(n-2).
$$
You are interested in $T(n)$ for $n=5$. But you should be able to determine $T(n)$ for smaller values of $n$ (e.g. $n=2$ and $3$) and build up from there..
Then, the total number of valid strings is
$$
 \#\lbrace\text{All possible strings}\rbrace - T(5).
$$
By the way, I find that this recursive way of building things comes handy in many cases when you want to count things. So keep it in mind!

A: Here's an ugly/inconvenient direct count, by breaking them up into instances by the maximum consecutive instances of $1$'s.
Strings where only $11$ appears:
1) A single $11$, no other $1's$: Obviously $11000$ is such a string. We can permute this in ${4 \choose 1}=4$ ways to obtain all strings with exactly one $11$ in it. (+4)
2) A single $11$, with single $1$'s: $11010,11001,01101$ and their mirror images. (+6)
3) Two disjoint $11$'s: The only possible one is $11011$. (+1)
Strings where only $111$ appears:
4) We count the number of reconfigurations of $11100$ with no extra $1$'s, ${3\choose 1}=3$. (+3)
5) With single $1$'s: $11101,10111$. (+2)
Strings where only $1111$ appears:
6) We count the number of reconfigurations of $11110$, ${2\choose 1}=2$. (+2)
Strings where only $11111$ appears:
7) Obviously, 1. (+1)
So there are, $4+6+1+3+2+2+1=19$ strings.


text:
Q: Security error in cross domain iframe I have a click tracker for a client. The tracker is nothing but a javascript snippet which writes an iframe(a different domain) into the page.
If I have a normal iframe I am able to track clicks more accuratley(I compare the data from another tracking solution) than when the iframe is secure(the site is accessed over ssl).
While trying to debug the issue, I came across a scenario, where the iframe had a security error. It said something to the extent that the Secure Certificate was not Valid.
The problem now is, I could see this error only once, after which I could not reproduce it. Is there any way I can replicate the error? Is there any way I can figure out why I am tracking less clicks if the iframe is secured?
Technology Stack:
dotNet framework 3.5
OS: Win 2003 server
Web server: IIS 6.0
SSL Certificate Issuer: Go Daddy.

A: iframes should be sharing the same domain for example foo.com and subdomain.foo.com is not the same SSL wise.

A: The range of permissible access for a page can be expanded when a script assigns the document.domain property to a suffix of the site name space, up to the second-level domain. For example, a page on www.microsoft.com can assign the document.domain property—initially www.microsoft.com—as microsoft.com to broaden access to include pages in home.microsoft.com or any other site, as long as the other pages also set the document.domain property to the identical value.
About Cross-Frame Scripting and Security : MSDN


text:
Q: Return field from first and last document in Elasticsearch aggregation I have a sorted elasticsearch histogram aggregation that works fine as is.
I need to return a field from the first and last document of each aggregation bucket.
Current query (ruby-style syntax):
{
  query: {
    filtered: {
      filter: {
        bool: {
          must: [
            { term: { some_id: 'something' } },
            { range: {
                completed_at: {
                  gte: start,
                  lte: end
                }
              }
            }
          ]
        }
      },
      _cache: true,
      _cache_key: "special-query"
    }
  },
  aggs: {
    intervals: {
      histogram: {
        field: 'completed_at',
        interval: 24.hours.to_i,
        min_doc_count: 0,
        order: { _key: 'asc' }
      },
      aggs: {
        start_at: { min: { field: 'completed_at' } },
        end_at: { max: { field: 'completed_at' } },
        price_stats: { extended_stats: { field: 'rate' } },
      }
    }
  }
}

I have searched through the documentation and googled extensively but can't find any solutions. Currently I have to send a second query to the database to explicitly fetch all the values for this field but I would like to roll that functionality in to my elasticsearch query.

A: You want to return a result per aggregation right?
That's called Field Collapsing and unfortunately isn't yet available in Elasticsearch, see: https://github.com/elasticsearch/elasticsearch/issues/256
Update sept 2014
As per @bpierce in comments below: Now that Elasticsearch 1.3.x is out, field collapsing is available via the top_hits aggregation. I'm currently using it in a query similar to this one.


text:
Q: Does Salesforce have a desktop Lightning Experience push API we can use to create custom push notifications? We are developing a LEX application and one of the requirements is that if another user has changed a specific value on the same record you are viewing, an instant notification is presented and the record state must change as a result.
It appears there are Push Notifications for the Service Console app, but is there a way we can create our own custom Push Notification for any object?
If Salesforce doesn't support custom desktop Push Notifications out of the box, can this be done with a 3rd party library?

A: With Winter 19, lightning:empApi can listen to platform events from such a DML. You would likely fire the platform event from a trigger or process builder on change event of your key fields and include the SObject recordID, current User ID, in its message payload.
Then, your listener component on the record page (of another viewing user) can check to see if the currently viewed recordID matches the payload recordID AND the current User IDs are different, then send an SLDS toast, SLDS prompt (seems appropriate here, as this is designed to stop workflow and you can refresh your data when they confirm it) or a more custom one.
You use to have to do this with a fragile cometD implementation, but it's now wrapped with a (hopefully more robust) version maintained by Salesforce themselves.


text:
Q: android studio setContenView So im trying to create a login page for my app and i'm implementing it on Android Studio but it receives an error saying cant not resolve symbol in setContentView. I have been cracking my head up for several hours but i still cant figure what wrong with it.
            setContentView(R.layout.activity_main);
right here at this line, it says activity_main cant not resolve as a variable even though i name my xml file is exactly the same with it.
here is my code,
package com.example.tieulyphidep.treasurehunters;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.R;

public class login extends ActionBarActivity implements View.OnClickListener{

    Button bLoggin,buttonSignup;
    EditText EditTextUserName, EditTextPassword;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bLoggin = (Button) findViewById(R.id.buttonLogin);
        buttonSignup = (Button) findViewById(R.id.buttonSignup);
        EditTextUserName =(EditText) findViewById(R.id.EditTextUserName);
        EditTextPassword =(EditText) findViewById(R.id.EditTextPassword);

        buttonLogin.setOnClickListener(this);
        buttonSignup.setOnClickListener(this);

    }
    @Override
    public void onClick(View v) {
    switch(v.getId()){
        case R.id.buttonLogin:
            break;
        case R.id.buttonSignup:
            startActivity(new Intent(this, register.class));
            break;
    }
    }

}

A: You imported R as import android.R;, but you want to import com.example.tieulyphidep.R
Just erase the line of import android.R; and Android Studio will suggest you to import the good one.
Note also that a class should start by an upcase letter and end by the mother class, like LoginActivity.

A: Do you have a layout file in your layout.xml titled activity_main? This piece of code:
setContentView(R.layout.activity_main);

is basically saying, "Hey, i'm a java class. I want to look like this file in my layout directory: activity_main"
Now, if you don't have an activity_main, you will definitely get an error.
If you already have the activity_main file in your layout, there are a few steps I suggest you take:

*

*Clean your project: Build->Clean Project

*Rebuild your project Build->Rebuild project

*Restart android studio

I also noted this:
import android.R;

You shouldn't be importing that.
Here's what your code should look like:
package com.USERNAME.loginregister;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Login extends ActionBarActivity implements View.OnClickListener {
    Button bLogin;
    TextView registerLink;
    EditText etUsername, etPassword;

    UserLocalStore userLocalStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        bLogin = (Button) findViewById(R.id.bLogin);
        etUsername = (EditText) findViewById(R.id.etUsername);
        etPassword = (EditText) findViewById(R.id.etPassword);
        registerLink = (TextView) findViewById(R.id.tvRegisterLink);

        bLogin.setOnClickListener(this);
        registerLink.setOnClickListener(this);

        userLocalStore = new UserLocalStore(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bLogin:
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();

                User user = new User(username, password);

                authenticate(user);
                break;
            case R.id.tvRegisterLink:
                Intent registerIntent = new Intent(Login.this, Register.class);
                startActivity(registerIntent);
                break;
        }
    }

According to the link you gave me, here is the full project code:
https://github.com/tonikami/LoginRegister
Best of luck,
{Ruchir}


text:
Q: Bug: useParams() hook initiates an error: TypeError: useContext(...) is undefined I'm trying to use the useParams() react hook to retrieve a parameter, but I'm getting this error:
TypeError: useContext(...) is undefined
This error is actually thrown by the hooks file, specifically this line (line 40):

/modules/hooks.js:40

 39 |
> 40 |   const match = useContext(Context).match;
 41 |   return match ? match.params : {};
 42 | }

My App.js file that contains the routing logic looks like this:

import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { ThemeProvider } from "@material-ui/core";
import theme from "./views/config/theme";
import { routes } from "./views/config/routes";
import Header from "./views/components/common/Header";
import Footer from "./views/components/common/Footer";

function App() {
return (

    <ThemeProvider theme={theme}>
      <Router>

        <Switch>
          {routes.map((route) => (
            <Route exact path={route.path}>
              {route.component()}
            </Route>
          ))}
        </Switch>

      </Router>
    </ThemeProvider>

);
}

export default App;

The routes.js file that contains all the routes looks like this:

import Dashboard from "../pages/Dashboard";
import UserDetails from "../pages/UserDetails";

export const routes: [
{
  name: "Dashboard",
  path: "/dashboard",
  component: Dashboard,
  access: "public",
},
{
  name: "User details",
  path: "/user/:id",
  component: UserDetails,
  access: "private",
},
];

and this is the UsersDetails component file where I'm trying to use the useParams() hook, it looks like this:

import { useParams } from "react-router-dom";

const UserDetails = () => {
const { id } = useParams();

return (

{id}

);
};

export default UserDetails;

I'm using:
NodeJS - 14.17.0
and:
"react": "^17.0.2"
"react-dom": "^17.0.2"
"react-router": "^5.2.0"
"react-router-dom": "^5.2.0"
"react-scripts": "4.0.3"

A: 1. Setting Routes
Firstly, in routes => component must be wrapped in open-close angle brackets. For example, my routes will look like this:

const routes = [
    {
        name: "Dashboard",
        path: "/dashboard",
        component: <Dashboard />,
        access: "public",
    },
    {
        name: "User details",
        path: "/user/:id",
        component: <UserDetails />,
        access: "private",
    },
];

2. Creating Two Components For Testing
Next, I created two components like this:

const Dashboard = () => {
  return
Dashboard
;
}

const UserDetails = () => {
  let { id } = useParams();
  return

    User Detail {id}

;
}

3. Wrapping The App Component
In App Component, we don't need to call component function (route.component() ), For example, look like this:

const App = () => {
  return (
    <Router>

        <Switch>
          {routes?.map((route) => <Route path={route.path}>
            {route.component}
          </Route>)}
        </Switch>

    </Router>
  );
}


text:
Q: Glassfish Server not in list of IntelliJ IDEA Ultimate 2017.3.4 I want to switch from Tomcat to Glassfish for the deployment of my web application.
Unfortunately, the application server Glassfish is not listed in the dialog of my IntelliJ IDE.

The IntelliJ documentation lists Glassfish.
How am I able to add/use it?

*

*IntelliJ IDEA Ultimate 2017.3.4

*MacOS 10.13.3

UPDATE
I tried previous version of the IDE and with 2017.2.7 Glassfish appears in the list of application servers:

Does anybody know why IntelliJ IDEs with versions 2017.3.x are missing Glassfish?

A: GlassFish Integration bundled plugin must be enabled in Settings (Preferences on Mac) | Plugins.


text:
Q: How to increment printf format php variable On my WordPress blog I'm trying to give specific id's to sidebar widgets. I'd like to just give them a simple incrementing ID for example id="sidebar-box-" . $i where i is the incrementing variable.
I have code that I got from this page, which can give it a specific id but I'd like more control over the id for style purposes and to keep my css following the same pattern. The code I have currently looks like this:
function custom_sidebar() {
    register_sidebar( array(
        'name'          => 'Blog Sidebar',
        'id'            => 'blog_sidebar',
        'before_widget' => '
',
        'after_widget'  => '
',
        'before_title'  => '
',
        'after_title'   => '
',
    ) );
}

But this code gives me an id like this: decent_comments_widget-2. My understanding is that the %1 is saying use the first parameter of the printf function like a string based on what I've read. I can't understand what the $s part is and I'm not even sure where it's getting the first parameter from since the register sidebar function is only being passed an array as its first parameter. What is the correct way to just make a simple id with an incrementing variable at the end? Any help in understanding variables in this format is also welcome. Thanks!
EDIT: I changed the id value from "sb-box-%1$s" to "sb-box-%d" but now I only get "sb-box-0" printed over and over again for each 'sidebar-box' class div in the sidebar. I can't figure out the right place to set the variable.

A: Normally you'd use %s (or something else) to indicate you want to have a string to be placed there when you are using sprintf().
But when you have multiple (different) conversion specifications (%_) you need to have the arguments that you pass into sprintf() in the same order as they are in your format string or you can specify the order they need to be in. Else the string might not look like you had expected.
That can be done very easily by using n$ (as @AlexBlex said) where n is the nth argument.
Example:
I have the string I am buying %d %s. (which can be I am buying 2 tomatoes.) but I want my sprintf() function to be like this sprintf($format, $item, $amount);.
That won't be possible with my current string. By adding 1$ between % and s I can specify that that placeholder will be the first argument and $2 for %d to specify that that will be the second argument.
What I get is this:
$item = "tomatoes";
$amount = 314;
$format = "I am buying %2$d %1$s.";
echo sprintf($format, $item, $amount);

// I am buying 314 tomatoes.

The documentation on sprintf() has some more information about argument swapping.

id="sidebar-box-" . $i
You want to increment a part of the id of the div, I'd suggest you change the value of your before_widget array key to
 this way you can easily increment the integer and then pass this through sprintf().


text:
Q: Calculate Network usage using nettop in terminal I want to calculate the network usage like some apps do(which displays up and down which changes it's values by the usage of user)
Using nettop:
nettop -t wifi -t wired -P -l 1

But then I saw this repo in Github.
The command used there is
nettop -x -k state -k interface -k rx_dupe -k rx_ooo -k re-tx -k rtt_avg -k rcvsize -k tx_win -k tc_class -k tc_mgt -k cc_algo -k P -k C -k R -k W -l 1 -t wifi -t wired

Now I'm getting different values in bytes_in and bytes_out for both the commands.
For the first command:
Google Chrome.284     153 KiB         150 KiB

For the second command: Taken from github
Google Chrome.284     156895          152847

Q). I ran second command first and first command second. So obviously the first command data should be equal or greater than second command. But it's wrong when I converted(150*1024 = 153600) Why is that? Which command should I use?


text:
Q: Hidden Markov Parameters I am making a Hidden Markov Model for a maternity dataset in R. Lets say I want to observe the patterns in 1st, 2nd and 3rd pregnancy. In every pregnancy, I have two variables i.e Son and Daughter. But my model is taking Son and daughter as states while I want Preg 1,2 and 3 as three different states. Data looks like this;
P1   P2   P3
S    D     S
D    D     S
S    S     D
S    S     S

How can tailor my model in this way?


text:
Q: How C++ organize(manage) third-party lib? (I've just edited the question to be more specific)
I know that this question might be too general to answer, but I'm just can not find good tutorial on this, so trying to seek for help here.
I'm new to C++, previously my main programing language is Java and Python. The way that C++ manage third-party lib is somehow confusing for me......While Python can easily install things with pip, Java can import the JAR, how C++ organize those things?
I would like to split my question into few parts:
Here is some understanding and question of mine:

*

*As long as the compiler, or IDE,  know the path of the lib, then everything is fine. So when saying install, we just add the path of the lib to some system path. And for IDE, we just config the setting so that it can resolve the lib in given path. Correct me if anything is wrong.

*Some C++ lib are all source code, and some contains sth. like .so or .dll, what is that? And what's the difference? I saw some lib saying that it can be used with simply include a few headers, but some require static linking, what does it mean?

*What's is a general good approach to manage all those lib? (For example, in python, pip will simply install to some global scope, or we use vitrual env to manage that. Then anything similar to pip in C++?

*More specifically, I'm using CLion, and Clion use CMake, so maybe all I suppose to do is config the CMakeList.text correctly and then the IDE will resolve all lib and compile correctly?
Again sorry for such general and somehow opaque question, but I'm totally lost as a newb for C++, which is much more complicated than Python and Java I used before.....
Any good tutorials might be of great help, thanks!

A: C++ doesn't. C++ is a language not a specific compiler or implementation.
With that said, for most compilers, building a C++ application is done in multiple steps:

*

*Edit

*Compile to object file

*Link to executable.

The C++ compiler is technically only involved in step 2 (and really only part of step 2).
Most compilers and linkers since long ago allow you to put header- and library-file anywhere, and then there are flags passed to the compiler and linker on the command-line that tell the compiler and linker where to find the files.
For header files the (common) command-line option -I (upper-case i) is used to add a path to be searched for header files. For libraries the option -L similarly adds a path to be searched by the linker for libraries. There are of course default paths built into the compiler and linker, and the -I and -L options adds to those defaults.
Then to link with an actual library, the linker-option -l (lower-case L) is the common option to use. Each -l options list a single library that needs to be linked into the executable.

In regards to CMake and CLion, the CLion IDE doesn't really link anything at all. Instead it uses CMake to create a set of makefiles which contains the information used to build the targets.

Lastly there are some C and C++ alternatives to PIP or other languages package managers, but generally you use the standard way to install programs and libraries on your system.
Like on Windows you find an installer, and then modify your project settings (using CMake CMakeLists.txt, raw Makefile, or IDE settings) to add the directories needed.
For Linux systems you use the standard package manager (like apt on Debian-based systems, or yum on Fedora-based systems, etc.) to find and install libraries. Then the libraries and their header files will be installed in the default locations. You still need to set up the build-environment to actually link to the libraries.

A: The common way is, that you include the thirdparty stuff as a .dll or you can include it direct as code (as example boost ... you have to load it and to make it work you only have to include the parts you want, and for some parts from boost you have to build it with your compiler settings and include the .dlls)
The thing with the manager like you want I only now from VisualStudio with NuGet. I have no idea if is there such a thing for CLion.
As example you can look to the example from opencv:
https://docs.opencv.org/master/d3/d52/tutorial_windows_install.html
For your questions:

*

*Correct. But in case the lib have to match also the settings (32/64 bit, release/debug)

*If you only have to include some headers, then the code is direct included to your project and compiled with your code. If you have to link it as a binary (.dll windows, .so Unix (i think please correct me if wrong)) than the code is compiled and you link the compiled functions to your code.
Here a answer to .so:
What are .a and .so files?
And here for static and dynamic libs:
When to use dynamic vs. static libraries


text:
Q: Jquery load text into div - multiple values/divs I have a text file with multiple lines that I need loaded into different divs.   Text file looks like:
Jon
Doe
25

Jane
Doe
37

Foo
Bar
18

How can I load this file and populate the following divs?
<input id="firstname" type="text"></input>
<input id="lastname" type="text"></input>
<input id="age" type="text"></input>

<input id="firstname1" type="text"></input>
<input id="lastname1" type="text"></input>
<input id="age1" type="text"></input>

<input id="firstname2" type="text"></input>
<input id="lastname2" type="text"></input>
<input id="age2" type="text"></input>

Loading the div with
   $(".myDiv").load("myFile.txt");

Using json or csv is not out of the question either...

A: var strings = fileTextBlob.split('\n');
$(".myDiv").children("input").each(function(index, inputEl){
    var tmpStr = strings.shift();
    //Catch empty lines. Could add more logic to catch strings of all spaces, etc.
    while(!tmpStr && typeof(tmpStr) !== "undefined"){
        tmpStr = strings.shift();
    }
    $(inputEl).text(tmpStr);
})

A: Arrange the data as json array of objects
var data = [
  {
    "firstname": "Jon",
    "lastname": "Doe",
    "age": 25
    },  {
      "firstname": "Jone",
      "lastname": "Doee",
      "age": 21
    }
  ]

Then with JQuery you could build the divs
var body = $('body');
$.each(data, function(index, value){
  body.append($('<input type="text" id="firstname' + index + '" >').text(value.firstname));
  body.append($('<input type="text" id="lastname' + index + '" >').text(value.lastname));
  body.append($('<input type="text" id="age' + index + '" >').text(value.age));
}

Edit -
You can use getJSON to load the json file
$.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "
" + val + "
" );
  });

  $( "
", {
    "class": "my-new-list",
    html: items.join( "" )
  }).appendTo( "body" );
});


text:
Q: How to add Modal dialog form to show on Spree commerce homepage I need to present customers arriving to the homepage of a Spree commerce with a modal dialog form asking them to enter email address to subscribe.
I have identified fancybox jquery plugin as possible way to accomplish this but don't know where in the spree code to add this to take effect.
I see different occurrences of spree files in the bundle/ruby/1.9.1/ and in /apps in the project directory and not sure where to add the javascript.
I will very much appreciate some pointers to solving this and to clarify my confusion as i am quite new to Rails.
Thanks.

A: In versions of Spree prior to 2.2.x you would place the javascript under app/assets/javascripts/store/spree_frontend.js
In versions of Spree 2.2.x+ you would place under vendor/assets/javascripts/spree/frontend/


text:
Q: Is this a correct understanding of how Scala provides multiple inheritance without causing the Diamond issue Below code:
trait t1 {
    def printt1 = println("In t1")
}

trait t2 {
    def printt1 = println("In t2")
}

class cclass extends t1 with t2

Cause this compile-time error:
class cclass inherits conflicting members: method printt1 in trait t1 of type => Unit and method printt1 in trait t2
 of type => Unit (Note: this can be resolved by declaring an override in class cclass.)

So this is providing compile time checking which does not allow multiple inheritance but does allow mixins while also preventing the Diamond problem : "multiple inheritance has been a touchy issue for many years[citation needed], with opponents pointing to its increased complexity and ambiguity in situations such as the "diamond problem", where it may be ambiguous as to which parent class a particular feature is inherited from if more than one parent class implements said feature." source: http://en.wikipedia.org/wiki/Multiple_inheritance
In order to fix compile time error above I just override t1 :
class cclass extends t1 with t2 {

    override def printt1 = println("In cclass")

}

Is this the primary shortcoming (Diamond problem) Scala is overcoming with respect to Java and multiple inheritance ?

A: No, there is no diamond problem in your code. To quote Wikipedia:

The "diamond problem" ...  is an ambiguity that arises when two
  classes B and C inherit from A, and class D inherits from both B and
  C.

Here is an example that demonstrates Scala's handling of the diamond problem:
trait A {
  def x = 1
}

trait B extends A {
  override def x = 2
}

trait C extends A
class D extends B with C

(new D).x // == 2

Scala "linearizes" the lookup of methods from traits. For D, it starts with D itself, and then looks at every class or trait it inherits from, starting from the right. This is a depth-first search, so the order is D -> C -> A -> B -> A, however duplicates (which indicate a diamond problem) are eliminated leaving the last in the list, so it becomes D -> C -> B -> A.
However, this code:
trait A[A] {
  val x: A
}

trait B extends A[Int]
trait C extends A[String]
trait D extends B with C

produces this error:
trait D inherits different type instances of trait A:
  A[String] and A[Int]

Showing that Scala still has a diamond problem in certain circumstances.


text:
Q: HTML-Fileupload using Firefox Android I'm a webdeveloper from Germany and I've got a problem with Firefox Android (different versions, current version I use is 23.0).
I developed a web application which has become very huge and complex.
It works fine but there's one PHP site which produces one or more bugs.
This site contains four HTML standard file controls. Here's the HTML code:
<input type="file" id="input_fileupload_01" name="input_fileupload_01"  accept="image/*; capture=camera">

<input type="file" id="input_fileupload_02" name="input_fileupload_02" accept="image/*; capture=camera">

<input type="file" id="input_fileupload_03" name="input_fileupload_03" accept="image/*; capture=camera">

<input type="file" id="input_fileupload_04" name="input_fileupload_04" accept="image/*; capture=camera">

When I click one control Firefox opens the dialog for selecting a device.
That's OK.
When I select the smart phone camera (and that's one of the most important features of my application) and shot a photo then sometimes there happen very extremely things:

*

*FF closes itself with a fatal system error.

*FF closes my web application's browser tab and opens a new browser tab starting my application's index site.
What's wrong? Please watch my HTML code - is there something wrong?
It is so simple. Why do those errors happen?
I hope you've seen that I cut all the upload logic - I did that for testing.
What's the reason FF "kills itself" after I shot a photo or selected an existing photo file from one of the local devices?
What is the error source: HTML, Firefox, the smart phone camera or something else? Please help me.
Thomas


text:
Q: Select from table where=$variable i'm trying to learn PHP/MySql and create a simple "website".
I have a problem while i try to print a row from a Select. I created a Database with the table "Utenti" and i want to select an username from it.
$username='Prova';
// In my database there is a record with username "Prova"

require 'connessione_db.php';
// I connect Php to the Database in another file

mysqli_select_db ($conn, $dbname);

$checkusername= "SELECT username FROM utenti WHERE username= '$username' ";
// when i write "Where username='Prova' " there aren't problem.

$username_result=mysqli_query($conn,$checkusername);

if (mysqli_num_rows($username_result) > 0) {
        while($rows=mysqli_fetch_array($username_result)) {
                echo $rows['username'];
        }
} else {
    echo "no";
}

With actual code the result is "no", but if i write:
... where username='Prova'";

the result is "Prova".
I tried to change the code reading user's solutions without success. I tried:
" ... Where username='" .$username. "'";

or
mysqli_real_escape_string($conn,$username);

and other useless advice.

A: When you're adressing to your sql server you're using string so you jsut need to merge two strings so username='" .$username. "'" should work just fine. What might work is something like "...username='{$username}". You should debug this string by using error.log($checkusername) what's wrong with your string. Also what version of php you currently using? Best stable version are 5.6 or 7.3.4 although 7+ versions isn't popular.


text:
Q: Java class functions and members I am trying to improve my scripts by altering some code. What I want is to make use of JS members. I know I can do this with AbstractScriptObject by overriding getMember.
Now comes the problem, I also have methods in this class that I want to call, but apparently I cannot call them anymore because it acts like a JS object now and it won't recgonize my methods anymore.
Is there any way so I can have members and java methods that I can call within a script? (Maybe something that converts my java methods to js functions?)
I want to do something like this in scripts:
if (dog.name == "")
and
dog.doSomething(args)
Thanks in advance,
Kevin

A: You've to expose your "methods" as script "functions". i.e., getMember should return further JSObject implementations that are "callable" (isFunction returns true and you override "call").


text:
Q: Home network switch and cable category I have few questions about home network. The architecture is as follows:

*

*fiber cable to home door

*from home door in box into the wall, separate cables are going to each room

The questions are:

*

*the box in the wall (where the IPS cable and room cables are going to be connected) is pretty small with no access to air (as it is closed); as there will be a switch, are there any heat concerns?

*as the room cables will be laid on the floor, which is later concreted what types of cable to use:

High class Cat6 cable seems OK, as it is standardize, uses RJ45. As I have read, Cat7 is not
recommended. The question is there any purpose for home network (in the future years) to support 40 Gbps (Cat8)?

*I guess that there is no point of switch like this as it support to 1Gbps, and need to get someone like this even currently the IPS is not delivering such speed; I am worrying about heat issues and noise as both seems to big (at least bigger and more complex than my current 6 ports one). Should I be worried?

A: I've built houses, I've done installs, and I've been in InfoSec for decades.
It is a bad idea to pour concrete over cables. I assume this is what you mean by "concreted." What you need to do is place runs of conduit (pipes) that are designed to be placed in concrete and run your cables through the conduit. This does several things.

*

*Makes it so that if a cable is damaged, it can be pulled and run again.

*When it is time to upgrade the cable, you can pull it and run new cable.

*You don't run the risk of damaging Ethernet with concrete.

You want to know what category of Ethernet cable to place? The answer is in the switch you'll be using. Does it have RJ-45 ports? If yes, then Cat6 or Cat8 is your answer.
You then ask if you need to worry about Cat8. I don't think anyone can tell you when 40Gbps will be a requirement between devices in the home. How quickly will VR develop? How many Internet connected devices will you own? Are you going to set up your own security system that's IP based? You are the only person that can determine this.
Do keep in mind that Thunderbolt 3 has a theoretical maximum speed of 40 Gbps. This allows transfer of data from a host to storage/video.

A: There is a fair of opinion to this question, but I would offer two specific points:

*

*I have not seen much consumer / general commercial switch gear that that can permanently survive zero ventilation. Remember you will need to service this gear. You can keep it is a ventilated cabinet if visible in a residence.

*While CAT 6e spec is good into the future for any home, make sure is it is enclosed in conduit in the concrete which is certified for burial in concrete.
Using properly installed conduit allows you to change cable category if you need it. I have been 25 years on CAT5 e / CAT 6 e with no degradation.

switch ....I am worrying about heat issues and noise as both seems to
big (at least bigger and more complex than my current 6 ports one).
Should I be worried?

Any switch, router, modem and like needs to be ventilated. Yes, you need to be concerned about heat.


text:
Q: Como implementar uma lista dentro de outra? (Estrutura de dados 1 em C) Eu tenho uma estrutura estática que defini como variável global: class_alimentacao Tipos_alimentacao[3]; E não consigo fazer com que a posição Tipos_alimentacao[i], receba o endereço da lista de animais. Estou perdido, sugestões? Eu nem consigo acessar os métodos inserir, porque eu programo em c++ e fico confuso com C. (Professor pediu em C...)
Veja o código:
Tipos de classificação de seres vivos que alimentam.
    typedef struct{
        char nome[50];
        struct Lista *animais;
        //struct NO *animais;
    } class_alimentacao; //Herbívoro, Onívoros e Carnívoro.
void consultarDataBase(class_alimentacao p){ printf("Tipo: %s\n",p.nome); }

NO_lista.
typedef struct NO{
    int id;
    char name;
    struct NO *proximo;
} NO;

typedef struct{
    NO *inicio;
    void(*ptr_metodo);
}Lista;

Métodos:
void insert(Lista *LISTA,int ID,char NAME){
    NO *ptr= (NO*)malloc(sizeof(NO));
    ptr->id= ID;
    ptr->name= NAME;

    ptr->proximo= LISTA->inicio;
    LISTA->inicio= ptr; }

void exibir(Lista *LISTA){
    NO *inicio= LISTA->inicio;
    if(inicio!=NULL){
        while(inicio!=NULL){
            printf("%d\t",inicio->id);
            printf("%c",inicio->name);
            inicio= inicio->proximo;
        }
    } else{
        printf("Nenhum animal cadastrado!");
    } }

Main:
int main(){
    Lista *list; list->inicio= NULL; int i= 0;
    for(i= 0;i<3;i++){
        scanf("%s",Tipos_alimentacao[i].nome); int op= 1;
        printf("(1) - Cadastrar nome animal.\n(2) - Sair.\n"); scanf("%d",&op);
        while(op>0 && op<2){
            list= &Tipos_alimentacao[i].animais;
            insert(list,10,'m');
            //insert(Tipos_alimentacao[i].animais,10,'m');
            if(op==2)break;
        } }

Como eu faria? Vejo que eu consigo acessar as variáveis do NO,com este argumento: Tipos_alimentacao[i].animais->, mais logo não acessaria os métodos: insert exibir. Por isso criei um void (*ptr_metodo) na estrutura da lista.
E ao fazerlist= &Tipos_alimentacao[i].animais;, dá erro de incompatibilidade. E mesmo que desce certo, já iria ocorrer outro problema, pois eu criei um objeto list, sendo que quero uma nova lista, toda vez que criar um Tipo_alimentacao. Ao fazer a consulta, eu estaria exibindo a mesmo conteúdo do objeto Lista *list. Me compreende? Por isso fiz assim: list= &Tipos_alimentacao[i].animais; e passando como parâmetro no inserir.

A: Em C provavelmente não precisaria dos ponteiros para as funções dentro da lista num problema tão simples, mas poderia ter. Aqui seria sempre a mesma função. Não há especialização e então seria só uma frescura a mais. Vou deixar no exemplo.
Se escrever uma implementação genérica de Lista nos moldes de list em C++ não terá dificuldade em ter uma lista de listas ou uma lista de listas de listas e tal. E seria bem útil já que escreveria uma vez só. Apenas use a mágica de void*, o type erasure de C ;)
Um exemplo mais simples em C
Considere que uma lista não é de animais ou de listas ou de int. É de nós.
Seja um nó:
typedef struct st_NO
{
    Animal*       animal;
    struct st_NO* ant;
    struct st_NO* prox;
}   NO;  // um no da lista

Devia ser void* mas vamos ficar com isso menos genérico. E considere que ter ponteiros para os dois lados é muito mais simples e não o contrário: navegar numa lista que só tem ponteiros para um lado é um porre.
O animal:
typedef struct
{
    int         id;
    const char* name;

}   Animal;  // um animal

Note que é muito mais simples encapsular o animal e usar apenas o endereço. Assim pode mudar o animal sem mudar as assinaturas das funções.
E a Listaafinal

typedef struct st_Lista
{
    NO*    inicio;
    NO*    fim;
    size_t size;
    // provavelmente nao precisa disso
    int (*insert)(struct st_Lista*, Animal*);
    int (*show)(struct st_Lista*, const char*);
    struct st_Lista* (*create)();  // construtor
    struct st_Lista* (*delete)(struct st_Lista*);  // destructor

}   Lista;  // uma lista afinal

Não acho que precise dos ponteiros para os métodos aqui, mas essa seria uma maneira de escrever, provavelmente o mais simples. Note que DENTRO da lista está o tamanho o início e o fim, o que minha avó chamava de "mão na roda".
Um mínimo de funções

// insere um animal numa lista, o simples
int insert(Animal* a, Lista* l);

// mostra uma lista na tela, com uma mensagem
// opcional
int show(Lista*, const char*);

// cria e destroi uma lista
Lista* create_l();
Lista* delete_l(Lista*);

Bem no estilo RAII de C++ ter a função que apaga a lista retornando um endereço de lista permite invalidar o ponteiro na mesma linha. E retornar apenas o ponteiro na hora de criar e nunca usar listas estáticas facilita o uso.
o header coisas.h
#define HERBIVORO_ 0
#define ONIVORO_ 1
#define CARNIVORO_ 2
#include <stdio.h>

typedef struct
{
    int         id;
    const char* name;

}   Animal;  // um animal

typedef struct st_NO
{
    Animal*       animal;
    struct st_NO* ant;
    struct st_NO* prox;
}   NO;  // um no da lista

typedef struct st_Lista
{
    NO*    inicio;
    NO*    fim;
    size_t size;
    // provavelmente nao precisa disso
    int (*insert)(struct st_Lista*, Animal*);
    int (*show)(struct st_Lista*, const char*);
    struct st_Lista* (*create)();  // construtor
    struct st_Lista* (*delete)(struct st_Lista*);  // destructor

}   Lista;  // uma lista afinal

typedef struct
{
    size_t  size;
    Lista** an;

}   Animais;  // um vetor de listas

// insere um animal numa lista, o simples
int insert(Animal* a, Lista* l);

// mostra uma lista na tela, com uma mensagem
// opcional
int show(Lista*, const char*);

// cria e destroi uma lista
Lista* create_l();
Lista* delete_l(Lista*);

Uma implementação vazia coisas.c
#include <stdio.h>
#include "v1.h"

int insert(Animal* a, Lista* l) { return 0; }
int show(Lista* l, const char* msg) { return 0; }
Lista* create_l() { return NULL; }
Lista* delete_l(Lista* l) { return NULL; }

main.c para um teste
Apenas como exemplo de como acessar as coisas
#include <stdio.h>
#include <stdlib.h>
#include "v1.h"

int main(void)
{
    Animal tigre    = {0, "tigre"};
    Animal coelho   = {1, "coelho"};
    Animal cascavel = {2, "cascavel"};

    Lista* l_herb = create_l();
    Lista* l_carn = create_l();
    Lista* l_oniv = create_l();

    insert(&tigre, l_carn);
    insert(&coelho, l_herb);
    insert(&cascavel, l_oniv);

    show(l_carn, "carnivoros ate aqui");
    show(l_herb, "herbivoros ate aqui");
    show(l_oniv, "onivoros ate aqui");

    Animais animais = {.size = 0, .an = NULL};

    animais.an = (Lista**)malloc(3 * sizeof(Lista*));
    animais.an[HERBIVORO_] = l_herb;
    ++animais.size;
    animais.an[CARNIVORO_] = l_carn;
    ++animais.size;
    animais.an[ONIVORO_] = l_oniv;
    ++animais.size;

    // apaga as listas
    l_herb = delete_l(l_herb);
    l_carn = delete_l(l_carn);
    l_oniv = delete_l(l_oniv);

    // esvazia a lista de animais
    free(animais.an);
    animais.an   = NULL;
    animais.size = 0;

    return 0;
}

HIH


text:
Q: Remove Commas from my textfield I have a problem when inserting elements from my XML to a textfield.
When I trace my code I get all my elements without any commas, but when I insert it into a textfield i'm getting alot of commas.
I've tried to split up the text to remove the commas, but there aren't any commas in the XML so how do I do this?
Here's my code
var B:Array = [];
var textLength:int = imgData.Vehicle.EquipmentList.children().length();
var list:XMLList = imgData.Vehicle.EquipmentList.children();
var equipmentList:XMLList = list.text();
for(var t = 0; t < textLength; t++)
{

    var equipText:String = list[t];
    equipText.split(",");
    B.push(equipText);
    trace(equipText);
    //B = B.split(", ").join();
}

errorMessage.text = B.toString();

A: Commas are added by toString() method.
See http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#toString().
You should use join() method instead.
errorMessage.text = B.join("");


text:
Q: ImageMagick: resize image and reduce file size Using ImageMagick, I'm trying to resize a JPEG's dimensions and reduce the file size.
The issue is that I don't want to worsen the image quality.
I've tried the following commands:
convert -resize 170x80 -resample 100x100 image1.jpg image2.jpg

=> A resized picture but with bad quality.
convert -resize 170x80 -quality JPEG image1.jpg image2.jpg

=> A resized image and with good quality, but the same file size.
convert -density 600 -resize 170x80 image1.jpg image2.jpg

=> A resized image but very bad quality.
I don't know what option I should use.

A: I've managed to solve this issue using convert and mogrify :
convert -flatten -colorspace RGB myImage.jpg myImage.jpg
&&
mogrify -quality JPEG -geometry 170x80 myImage.jpg

A: quality parameter has a numeric value. From -quality doc :

For the JPEG and MPEG image formats, quality is 1 (lowest image quality and highest compression) to 100 (best quality but least effective compression). The default is to use the estimated quality of your input image if it can be determined, otherwise 92.

You may use quality lower than the default 92 to reduce the size, e.g. 72 as:
convert -resize 170x80 -quality 72 image1.jpg image2.jpg


text:
Q: Cannot upgrade ubuntu 19.04 for a time After I login ubuntu, as usual, I check upgradable packages by running: sudo apt update. Then the result is:

36 packages can be upgraded. Run 'apt list --upgradable' to see them.

I continue with the command:sudo apt upgrade but I got error:

E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
  E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?

I waited for a few moments and then I rerun the previous command and it told me:

2 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
  Is it an apt error or there's an update process running on the background?

A: You are duplicating the work being done by Unattended Upgrades, so encountering interference is expected behavior.
Take a look at the Software & Updates control panel, the 'Updates' tab:

Look at the line: When there are security updates
Those security updates are downloaded-and-installed-automatically using apt...just like updates that you initiate. Security updates can occur at any time, but often occur just after startup.
Since only one apt session can run at a time, one of you gets locked out with an error message until the current apt session completes. That lockout is the classic error message you encountered. Another process was indeed using apt at the time.
If you want to verify, look at /var/log/apt/history.log. You will likely see two sessions, one that installed the security updates, and another (yours) that installed the rest.
Interfering with Unattended Upgrades causes no damage. The same packages get installed regardless of who initiates the upgrade or when.

A: It is the most common error and question while installing an application in ubuntu :) You can use the below references. I hope these are useful to you.

*

*https://itsfoss.com/could-not-get-lock-error/

*https://www.linuxuprising.com/2018/07/how-to-fix-could-not-get-lock.html


text:
Q: How do I change the command prompt using a bash script? My Ubuntu version is Ubuntu 21.04. I am trying to change my command prompt with a script I made, called recording.sh. Here is the code:
#!/bin/bash

echo -n "are you recording? yes(1)/no(0)"
read VAR

if [ $VAR -eq 1 ]; then
       PS1="\[\033[38;5;2m\]Hazardous-potato@\h\[$(tput sgr0)\]:\[$(tput sgr0)\]\[\033[38;5;4m\]\w\[$(tput sgr0)\]: \[$(tput sgr0)\]"
else
       PS1="\[\033[38;5;2m\]\u@\h\[$(tput sgr0)\]:\[$(tput sgr0)\]\[\033[38;5;4m\]\w\[$(tput sgr0)\]: \[$(tput sgr0)\]"
fi

I expect my command prompt to change from:
sterling@The-beast~:

to
Hazardous-potato@The-beast~:

when I run the above script, but, instead, it just stays the same.

A: I sourced the file and lead bash into the file to execute it when the terminal opens. I sourced it at the end of the .bashrc file:
. /home/sterling/recording.sh


text:
Q: protobuf-net extensions : "already contains a definition" I have the following (simplified !) .proto. It's from another software, I can't modify it.
package test;

message Base
{
    optional string name            = 2;
    extensions 1000 to max;
}

message Extension1 {
  extend Base {
    optional Extension1 type = 1000;
  }
  optional double     blabla      = 2;
}

message Extension2
{
  extend Base {
    optional Extension2 type = 1001;
  }
  optional double     blabla      = 2;
}

Compiling if with protogen generates the following C# for the Base message (extract) :
private test.Extension1 _type = null;
[global::ProtoBuf.ProtoMember(1000, IsRequired = false, Name=@"type", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public test.Extension1 type
{
  get { return _type; }
  set { _type = value; }
}

private test.Extension2 _type = null;
[global::ProtoBuf.ProtoMember(1001, IsRequired = false, Name=@"type", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public test.Extension2 type
{
  get { return _type; }
  set { _type = value; }
}

As you can see, the extensions are both called "type", but should be called "Extension1::type" and "Extension2::type" (if my understanding of extensions is correct).
Clearly, this doesn't compile. Also, Name=@"type" seems wrong to me (not sure, might be ok).
What can I do to be able to read files serialized with this .proto ?
Possible workarounds I've thought of:

*

*Modifying the .proto and renaming "type" to "type1". This will surely break everything.

*Going through a binary .pb with protoc. Reduces the number of errors, but many remain.

*Patching protogen so that it generates field names like "Extension1_type"

*Hand-patching the .cs with field names like "Extension1_type"

*Using something else than protobuf-net

A: Options:

*

*try protobuf-csharp-port, which is much closer to the google code-base, and might handle this scenario better

*edit the generated C# file to rename one of the members: names are never used in the binary format, so as long as the numbers are the same, the names don't matter

*edit the .proto file: for the same reasons above, nothing bad will happen if you simply copy the file, edit the names in the copy, and generate code from the copy


text:
Q: SQL Query to Count Duplicate Values in String I've searched for an answer to this here on the boards and elsewhere - I'm guessing this issue has already been resolved, but for some reason, I'm not finding what I need... so, I'll ask and hope this isn't a duplicated question.
What I have is a list of students and employees in a MSSQL database. One of the columns contains a string with the current term (semester) with an identifier for each class that the student is registered for, delimited by ';' for each entry.
What I'm trying to figure out is how to return a value of students who are signed up for more than 4 classes for the current semester. To get a count of all students registered for the current semester, the query is simple:
SELECT COUNT(*) AS Current_Students
FROM UserData
WHERE StuTermClassString LIKE '%2163%'

This works fine to return the total number of students, but I need a way to return a value of the full-time students (those that have more than 11 class hours per semester, which is typically 4+ classes). So I need a way to determine when the count of classes with '%2163%' for a record is > 4. If I haven't explained this well enough, please let me know and I'll expand on it more. Thanks!

A: Direct answer to your question:
WHERE StuTermClassString LIKE "%2163%;%;%;%;%"<-- assuming the semester indicator is before the class names, and each class name has a semicolon after it.
But, might I suggest a more reasonable DB structure? Instead of having a column in your Student table with a string of ;-delimited class names, you could have a second table of Registrations, where each row has a Student ID (referring to a row in your Student table), a Semester Number, and a single class name. This way you could query for students with more than a certain number of classes by doing:
SELECT student_id FROM Registrations WHERE semester_number = "2163" GROUP BY student_id HAVING COUNT(student_id) > 3

A: Unfortunately handling pseudo-arrays packed into a string in SQL happens.
You will need to create a string splitting function to parse out the individual items in the list string and present them as a table variable.
See: http://sqlperformance.com/2012/07/t-sql-queries/split-strings
There are many ways to do this, but you should end up with a table variable that can use the standard built-in set oriented SQL functions to find what you need.


text:
Q: angularjs http request to php file response back is the php file itself I spend some time on this error and I'm not really solving it. Everything works fine but when I get my response back, I get my php file back in plain text.
my http request:
.factory('getDataFactory', function ($http) {
    function myCheckList() {
        $http({
            url: 'connect.php',
            method: "GET",
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function (response) {
            var result = response;
            console.log(result);
        });
    }
    return myCheckList;
})

console log contains:
<?php
$con = mysqli_connect("localhost", "root", "", "username");

$res = mysqli_query($con, "SELECT * FROM `wereldsteden`");

$result = array();

while ($row = mysqli_fetch_assoc($res)) {

    $result[] = $row;
}

echo json_encode($result);
?>


text:
Q: Scale and Rotation Issue with Model Import 3DS Max to Unity I have just designed simple 3d model in 3ds Max and try to import within Unity. But notice one thing that is irrelevant for me, I was getting -90 rotation in X degree and scale of model is also not proper.
I don't know what is the reason behind this though I am beginner with 3ds max software.

As per above image, I hope you understand my point so what kind of settings, I require to do in 3ds max software so that it get imported with 0 rotation in X degree and with (1,1,1) scale.
Give me some suggestions into this.

A: I have used this plugin for Blender and it works great for me:
Unity Rotation Fix for Blender
If you can't find a plugin for 3DS Max you can try to write similar plugin yourself or export your model to Blender and then use the plugin.
Here is the original Python code in case the link gets deprecated:
import bpy

bl_info = {
 "name": "Unity Tools",
 "author": "Karol \"Mirgar\" Głażewski",
 "version": (1, 0, 2),
 "blender": (2, 6, 5),
 "location": "3D View > Tool Shelf > Unity Tools",
 "description": "Tools to ease workflow with Unity Engine",
 "warning": "",
 "wiki_url": "",
 "tracker_url": "",
 "category": "Object"}

# fixes rotation on X axis, +X is -X in Unity compared to Blender
class UnityRotationFixerX(bpy.types.Operator):

    bl_description = "Fixes rotation of object so it will not \"lay on its face\" in Unity, +X axis is -X compared to Unity"
    bl_label = "Simple rotation fix"
    bl_idname = "object.unity_rotation_fix_x"
    bl_options = {'REGISTER', 'UNDO'}

    def FixRotationForUnity3D(self):
        bpy.ops.object.transform_apply(rotation = True)
        bpy.ops.transform.rotate(value = -1.5708, axis = (1, 0, 0), constraint_axis = (True, False, False), constraint_orientation = 'GLOBAL')

        bpy.ops.object.transform_apply(rotation = True)
        bpy.ops.transform.rotate(value = 1.5708, axis = (1, 0, 0), constraint_axis = (True, False, False), constraint_orientation = 'GLOBAL')

    @classmethod
    def poll(cls, context):
        return context.mode == 'OBJECT' and context.area.type == 'VIEW_3D'

    def execute(self, context):
        self.FixRotationForUnity3D()
        return {'FINISHED'}

# fixes rotation on X and Z axis, front is now +Y
class UnityRotationFixerXZ(bpy.types.Operator):

    bl_description = "Fixes rotation of object, +Y is now front"
    bl_label = "Full rotation fix"
    bl_idname = "object.unity_rotation_fix_xz"
    bl_options = {'REGISTER', 'UNDO'}

    def FixRotationForUnity3D(self):
        bpy.ops.object.transform_apply(rotation = True)

        bpy.ops.transform.rotate(value = -1.5708, axis = (1, 0, 0), constraint_axis = (True, False, False), constraint_orientation = 'GLOBAL')
        bpy.ops.transform.rotate(value = -3.1416, axis = (0, 1, 0), constraint_axis = (False, True, False), constraint_orientation = 'GLOBAL')

        bpy.ops.object.transform_apply(rotation = True)

        bpy.ops.transform.rotate(value = 1.5708, axis = (1, 0, 0), constraint_axis = (True, False, False), constraint_orientation = 'GLOBAL')
        bpy.ops.transform.rotate(value = 3.1416, axis = (0, 0, 1), constraint_axis = (False, False, True), constraint_orientation = 'GLOBAL')
    @classmethod
    def poll(cls, context):
        return context.mode == 'OBJECT' and context.area.type == 'VIEW_3D'

    def execute(self, context):
        self.FixRotationForUnity3D()
        return {'FINISHED'}

class UnityPanel(bpy.types.Panel):

    bl_idname = "OBJECT_PT_unity_tools"
    bl_label = "Unity Tools"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_context = "objectmode"
    bl_options = {'DEFAULT_CLOSED'}

    def draw(self, context):

        layout = self.layout

        col = layout.column(align=True)
        col.label(text="Rotation:")
        col.operator("object.unity_rotation_fix_x")
        col.operator("object.unity_rotation_fix_xz")

#registers

def register():
    bpy.utils.register_class(UnityRotationFixerX)
    bpy.utils.register_class(UnityRotationFixerXZ)
    bpy.utils.register_class(UnityPanel)

def unregister():
    bpy.utils.unregister_class(UnityRotationFixerX)
    bpy.utils.unregister_class(UnityRotationFixerXZ)
    bpy.utils.unregister_class(UnityPanel)

if __name__ == "__main__":
    register()

And the installation guide:

To install this addon unpack it to your Blender addon folder, e.g.
  "C:\Program Files\Blender Foundation\Blender\2.67\scripts\addons" or
  use install from file button in user preferences under addons tab.
After installing, addon is in Object category and after enabling it,
  can be accessed from Tool Shelf under "Unity Tools" panel.
Note that complete rotation fix on X and Z axis will swap object so it
  will face +Y axis instead -Y, if you export through fbx remember to
  set Forward Z and Up Y as export axis when you use full rotation fix.

A: Unity have different axis that 3D Max (and Blender etc.) and to fix that Unity is rotating models by default. Just Unity thing. If it's bordering you, you can always set your model as a child of an empty object.

A: load the ball in 3d max, rotate it -90 degrees on the x axis, reset transform and re-export. as for the scale,
https://docs.unity3d.com/Manual/FBXImporter-Model.html
select the model in the inspector and check out its properties, specifically the import props.... do a little math and adjust the import scale.


text:
Q: Rendering Power BI Dashboard in Angular Do anyone have a working sample where a Power BI dashboard is rendered to an Angular (>= 2) application?

A: You can embed the PowerBI report in your Angular App with an embed link.
<iframe width="1140" height="541.25" src="https://app.powerbi.com/reportEmbed?reportId=e91770ca-3d4c-49c9-a389-84f8656779c1&autoAuth=true&ctid=8f102725-4bbc-4a0f-ba03-1a0e913cd18e&config=eyJjbHVzdGVyVXJsIjoiaHz0cHM6Ly93YWJpLXVzLWV9c3QyLXJlZGlyZWN0LmFuYWx5c2lzLndpbmRvd3MubmV0LyJ9" frameborder="0" allowFullScreen="true"></iframe>

See more here


text:
Q: Database Runtime Exception while inserting a row in a column that doesn't appear in source code While running my app, logcat is showing an exception:
09-28 16:37:33.364     853-2228/? E/SQLiteDatabase? Error inserting
    android.database.sqlite.SQLiteConstraintException: column context_id is not unique (code 19)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
    at com.google.android.contextmanager.q.al.a(SourceFile:408)
    at com.google.android.contextmanager.q.al.b(SourceFile:383)
    at com.google.android.contextmanager.q.al.a(SourceFile:349)
    at com.google.android.contextmanager.q.al.b(SourceFile:376)
    at com.google.android.contextmanager.g.a.j.a(SourceFile:58)
    at com.google.android.contextmanager.g.a.a.run(SourceFile:52)
    at com.google.android.contextmanager.g.i.handleMessage(SourceFile:215)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.os.HandlerThread.run(HandlerThread.java:61)

My problem is, context_id column doesn't appear when I do a full search in whole project. The exception info point to classes from android libs, not my code.
Any clues, how to track this exception?

A: This is something that has started appearing in android devices after one of the recent updates. It most likely has nothing to do with your app.
Unless you're doing communication with other apps/services and need to see what they're logging you should probably filter your logs on the first of the numbers in 1234-4321/ABCD as that is the process-id of the process that produced the log-message. Find a message that you know to come from your app and use that as reference.
If you're using Android Studio it should also be possible to select your application from a dropdown-list, and select "Show only selected application", which will have the same effect as what I described above.


text:
Q: How to get date difference between 24 hour format time? I want to get the time difference between 2 times. It's basically between 9 PM and 5 AM.
SELECT DATEDIFF(HOUR, '21:00', '05:00')

Here is the query I am trying to execute but it's returning 16 hours although it should be returning 8 hours.
Can anyone help ?

A: Your problem is the wrapping of the time to the next date.  I would recommend:
select (case when @start <= @end
             then datediff(hour, @start, @end)
             else 24 - datediff(hour, @end, @start)
        end) as diff_hours

You could also express this as:
select (24 + datediff(hour, @start, @end)) % 24

A: One method is with a CASE expression:
SELECT CASE WHEN DATEDIFF(HOUR, '21:00', '05:00') >= 0 THEN DATEDIFF(HOUR, '21:00', '05:00') ELSE 24 + DATEDIFF(HOUR, '21:00', '05:00') END;


text:
Q: "Merging" two books in Calibre's index I've bought some digital books, and I was supplied with both the PDF and the mobi format.
Adding them to Calibre, they are treated as different books, and strangely they also have different metadata (the PDF versions miss publisher and author information).

Is there a standard way to tell Calibre that they are the same book? Sure I could use it to manually convert one into the other one, but I would rather keep the original one in both formats.

A: My current version has a "Merge book records" menu entry. Just select all entries belonging to the same book, then right-click and find "Merge book records" under "Edit metadata".
The first clicked book will be the main one, whose metadata will be picked in case of conflicts.

The manual way would be:

*

*Delete all but one of the duplicate entries (NOT the files!)

*Open the metadata editor for the remaining entry (right-click, Edit metadata individually)

*Click the red book with the plus sign in the top right to add the other format's files

*Click OK when you're done.

A: My Solution
Select both book records in clibre books list
Right Click on the selection > Edit Metadata > Merge book records
You will see 3 options

*

*Merge into first selected book - delete Others

*Merge into first selected book - keep Others

*Merge only formats into first selected book - delete Others

Select the one that fits your need.


text:
Q: SendPingAsync Reply return 11050 i'm trying make a simple ping application using SendPingAsync. But, pingReply.Status.ToString() return weird number "11050" when connection disconnected. It will return unsuccessful message like "TimedOut" or "DestinationHostUnreachable", but after some seconds. What does it means?
Here is my code :
async Task ngeping(String host, CancellationToken ct)
{
    Ping ping = new Ping();
    IPAddress ipaddress;
    PingReply pingReply = null;
    long tripTime;
    while (true)
    {
        if (ct.IsCancellationRequested) break;
        tripTime = -1;
        try
        {
            pingReply = await ping.SendPingAsync(host, 3000);
            ipaddress = pingReply.Address;
            if (pingReply.Status == IPStatus.Success)
            {
                tripTime = pingReply.RoundtripTime;
                if(tripTime<300)
                    gaweRTF.insertLine(GaweRTF.HIGHLIGHT_GREEN, ipaddress.ToString() + " - " + tripTime + " ms");
                else if (tripTime < 500)
                    gaweRTF.insertLine(GaweRTF.HIGHLIGHT_YELLOW, ipaddress.ToString() + " - " + tripTime + " ms");
                else
                    gaweRTF.insertLine(GaweRTF.HIGHLIGHT_RED, ipaddress.ToString() + " - " + tripTime + " ms");
            }
            else
                gaweRTF.insertLine(GaweRTF.HIGHLIGHT_RED, "not success: "+pingReply.Status.ToString());
        }
        catch
        {
            gaweRTF.insertLine(GaweRTF.HIGHLIGHT_RED, ERROR_MESSAGE);
        }
        rtb.Rtf = gaweRTF.finishRTF();
        if (tripTime>=0 && tripTime<1000) await Task.Delay(1000 - (int) tripTime);
        if (pingReply.Status != IPStatus.Success) await Task.Delay(1000);
    }
}

Edit : Here my application screenshots :
Right after disconnect
After 10-15 "11050" message

A: buddy
this code : 11050 means General Failure
Request failed for an unknown reason.
For more information, see Knowledge Base article 325487, "How to troubleshoot network connectivity problems" (http://go.microsoft.com/fwlink/?linkid=3052&kbid=325487).