text:
Q: Finding the First Few Terms of the Sum of Two Infinite Series Consider $$f(x)=\sum_{n=0}^{\infty}\sum_{j=0}^{n}\sum_{k=0}^{j}d_{k}c_{j-k}a_{n-j}x^{n-11}+\sum_{n=0}^{\infty}\sum_{k=0}^{n}e_{k}b_{n-k}x^{n-8}.$$
Given that I know the first few values of $d,c,a,e,b$, I am able to compute the first few terms for each of the series. However, I simply cannot add the terms (with same powers of $x$) from the two series and conclude that this sum represents the first few terms of the entire sum, namely, $f(x)$.
Is the following correct in terms of adding the two series?
Let $\alpha_{0}=\alpha_{1}=\alpha_{2}=0$ and $\alpha_{k}=1$, $k=3,4,\ldots$. Then,
$$f(x)=\sum_{n=0}^{\infty}\sum_{j=0}^{n}\sum_{k=0}^{j}d_{k}c_{j-k}a_{n-j}x^{n-11}+\sum_{n=0}^{\infty}\sum_{k=0}^{n}\alpha_{k}e_{k}b_{n-k}x^{n-11}$$
$$\Rightarrow\quad f(x)=\sum_{n=0}^{\infty}\left(\sum_{j=0}^{n}\sum_{k=0}^{j}d_{k}c_{j-k}a_{n-j}+\sum_{k=0}^{n}\alpha_{k}e_{k}b_{n-k}\right)x^{n-11}$$

Included Later

The formula for $\displaystyle\sum_{n=0}^{\infty}\sum_{k=0}^{n}e_{k}b_{n-k}x^{n-8}$ while reducing $x^{n-8}$ to $x^{n-11}$ with the introduction of $\alpha_{k}$ is incorrect.
The correct form is $\displaystyle\sum_{n=3}^{\infty}\sum_{k=0}^{n-3}e_{k}b_{n-3-k}x^{n-11}$, where the inside sum is $0$ whenever $n-3<k$. (I hope this is correct). But I think it still does not provide a way of writing $f(x)$ as a single sum.

Question
Suppose I want to write down the first 10 terms of $f(x)$. I can then write down the first 10 terms of the first sum and the first 7 terms of the second sum. Adding these two together will give me the first 10 terms of $f(x)$. Will this be correct?

Thanks, Radz.


text:
Q: Bootstrap 4 Dropdown menus not functioning - But works on other file with same CDNs I was trying to make the navbar-brand logo a dropdown toggle for my navbar. When I first implemented it, it worked fine! However, after editing my home page file and logged into access the main.php page, it suddenly stopped working.
I dont usually show all of my code but for this case, I will so please forgive me for that.
I tried copying and pasting a generic navbar into the echo"" portion, and the dropdown did not work. That gave me the idea that it had something to do with the cdns I was using. So I copied and pasted to another file and it worked. Which confused me. When I went back to the main.php file I thought it could have been a bad cache. I emptied it and it still did not work. Understand that this was working 100% fine until I edited my home page and logged back in.
Also, I ruled out my css file because I commented it out and tried it without that. So here is a list of things it was not:
1.Bad Cache
2.CSS file
3.CDN's not matching with the bootstrap4 version I am using.
4.Haunted computer
<?php
   require "login.php";
?>
<!DOCTYPE html>

    <meta charset='UTF-8'>
    <title>Main</title>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>
    <link rel ='stylesheet' href='register.css'>

    <?php
      if(!isset($_SESSION['username'])){
        echo"
You have not logged in.
";
      }
      else{
        $username = $_SESSION['username'];
        echo"

            $username

              Logout
              Account

        <button class='navbar-toggler' type='button' data-toggle='collapse' data-target='#navbarSupportedContent' aria-controls='navbarSupportedContent' aria-expanded='false' aria-label='Toggle navigation'>

        </button>

              Coming Soon (current)

          <form class='mx-2 my-auto mx-auto search-bar d-inline w-50'>

                <input class=' form-control mr-sm-2' type='text' placeholder='Search Contacts' aria-label='Search'>

                <button class='btn btn-outline-success' type='submit'>GO</button>

          </form>

      ";
      }
    ?>

I expect my dropdowns to work.
Also another interesting bit,  the hamburger menu works sort of... it does not de-toggle though.
This issue is confusing.

A: Not Sure what happen but try this

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

            Coming Soon (current)

        <form class='mx-2 my-auto mx-auto search-bar d-inline w-50'>

            <input class=' form-control mr-sm-2' type='text' placeholder='Search Contacts' aria-label='Search'>

                <button class='btn btn-outline-success' type='submit'>GO</button>

        </form>

        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    $username
  </button>

          Logout
          Account

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

A: I removed the CDN's at the bottom. That seemed to have worked.
Turns out login.php was being imported with the CDNs in PHP. At least that is my theory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Printing multiple instances of a number or a character by using format specifiers Is it possible to for example print more than 1 number using format specifiers?
printf("%05d",5);

This will print 00005
Is there a way to make it print ----5 for example using these format specifiers?

A: If you can use alloca then a not so elegant solution would be:
printf("%s%d", (char*)memset(memset(alloca(4), '\0', 4), '-', 3),5);

If you can allow c++, then you can try this which looks little more elegant:
printf("%s%d",std::string(3,'-').c_str(),5);

Both these cases will give out ---5

A: You can't do exactly what you want. I think the closest is something like this:
#include <stdio.h>
#include <math.h>

// FILLER_DASH needs to be long enough for all use cases
const char *FILLER_DASH = "---------------------------------------------------";

int main(void) {

    const int field_width = 10;

    for (int number = 1 ; number < 1100000; number += (number + 90)) {
        // zero or negative numbers not supported by this simple formula
        int digits = log10(number) + 1;
        printf("%.*s%d\n", field_width - digits, FILLER_DASH, number);
    }
    return 0;
}

It uses the * in format specifier to take field width from arguments, and then uses a string to provide characters to be printed.
It uses base 10 logarithm to get number of base-10 digits in a number, which involves implicit conversions from int to double for logarithm function and then back to int for printf format. This logarithm is only defined for positive numbers (so in this case integers 1 and greater), if you want 0 or negative number support then they need to be handled as special cases (basically 3 branch if-elseif-else ladder).


text:
Q: list created str in range other list i have a list like below:
[3,2,4,5]

and i want a list like below:
[['1','2','3'],['1','2'],['1','2','3','4'],['1','2','3','4','5']]

i mean i want to have a list that is created by the count of another list.
I want to iterate each with string.
how can i write it in python
i tried this code:
    for i,val in enumerate(list_mf_input):
        self.eachMembership.append([])
        for value in range(1, val+1):
            self.eachMembership.append([value])

A: You can use range with list, and list comprehension:
>>> a = [3, 2, 4, 5]
>>> [list(range(1, x+1)) for x in a]
[[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5]

And to make all strings, add map with str:
>>>[list(map(str, range(1, x+1))) for x in a]
[['1', '2', '3'], ['1', '2'], ['1', '2', '3', '4'], ['1', '2', '3', '4', '5']]

A: try this code. I tried to make as easy as possible
lol=[3,2,4,5]
ans=[]
temp=[]
for i in lol:
    for j in range(1,i+1):
        temp.append(j)
    ans.append(temp)
    temp=[]
print(ans)

Hope it helps


text:
Q: How to find text in file located in remote-server folder? I need to create an easy PowerShell script to find the text in to the files.
I used this script code:
Select-String -Pattern "TextToFind" -Path \\ServerName\C$\Folder_I\Folder_II\*.txt

But It not work well, this code work only if the folder is located in my machine.  On the remote machine, I got this error:
is missing the terminator CategoryInfo : ParserError: (:String) [], ParseException FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

Is this the right syntax to link the remote folder?
Thanks

A: How about running it on the remote server. PowerShell remoting will need to have been setup.
Invoke-Command -ComputerName 'ServerName' -Command Select-String -Pattern "TextToFind" -Path C:\Folder_I\Folder_II\*.txt

@ulisses added this. Yes, it works, but it requires the file to be sent over the network. Using Invoke-Command runs the command on the remote machine. That is generally faster than reading the file across the network.
Work fine too this command line:
Select-String -Pattern 'TextToFind' -Path \\ServerName\C$\folder_I\Folder_II\*.txt


text:
Q: How can I print a matching line and the next three lines in Perl? I need to search for a pattern and write that line as well as the next 3 lines into a file (FILE). Is this a correct way to do it? Thanks.
print FILE if /^abc/;
$n=3 if /^abc/;
print FILE if ($n-- > 0);

A: I like .. operator:
perl -ne 'print if (/abc/ and $n=3) .. not $n--'

but you doesn't have described what should happen if abc pattern is repeated in following three lines. If you want restart counter, your approach is correct if fix a little bug with double print.
perl -ne'$n=4 if/abc/;print if$n-->0'

A: You could simplify it to using a flag variable to know if you should print a line:
while( <$input> ) {
    $n=4 if /^abc/;
    print FILE if ($n-- > 0);
    }

Besides simplification, it also fixes a problem: in your version the abc string will be printed twice.

A: This is a feature of the command-line grep(1). No programming needed:
grep abc --after-context=3

You do get '--' lines between groups of context, but those are easy enough to strip. It's also easy enough to do the whole thing in Perl. :)
The trick is what you want to do when one of the following three lines also contains the pattern you're looking for. grep(1) will reset the counter and keep printing lines.

A: There is no need to slurp the file in or try to write your code on a single line:
#!/usr/bin/perl
use strict;
use warnings;

while ( my $line = <DATA> ) {
    if ( $line =~ /^abc/ ) {
        print $line;
        print scalar <DATA> for 1 .. 3;
    }
}
__DATA__
x
y
z
abc
1
2
3
4
5
6

A: Another possible solution...
#!/usr/bin/perl

use strict;

my $count = 0;
while (<DATA>) {
    $count = 1 if /abc/;
    if ($count >= 1 and $count <= 3) {
        next if /abc/;
        print;
        $count++;
    }
}

__DATA__
test
alpha
abc
1
234123
new_Data
test

A: I'd rather take a few extra lines of code and make everything more clear. Something like this should work:
my $count = 0;
while ( my $line = pop @file ) {
   if ( /^abc/ ) {
      $count = 4;
   }

   if ( $count > 0 ) {
       print FILE $line;
       $count--;
   }
}

Edit to respond to comments:

*

*missing the regex was a bug, fixed now.

*printing the newlines or not is certainly optional, as is slurping the file in. Different people have different styles, that's one of the things that people like about Perl!


text:
Q: the value of pointer to data member in C++ Meet a very weird problem, anyone know what is the reason of this? the code is tested under Visual Studio 2012.
#include <iostream>
struct A {
  int a;
};
struct B {
  int b;
};
struct C : public A, public B {
  int c;
};

int main() {
  int C::*p = &C::b;
  std::printf("%p\n", &C::b); //00000000
  std::printf("%p\n", p);     //00000004
  return 0;
}

A: Pointers to members are not just plain C-pointers, so passing them to printf is actually undefined behavior, because printf will believe in the "%p" and C-cast the pointer-to-member  to void*.
The only conversions of pointers to members allowed by the standard are listed in paragraph 4.11:

*

*Null-pointer constants can be converted to null member pointer values

*B::*T can be converted to D::*T if B is an accessible, nonambiguos and nonvirtual baseclass of D.

Pointers to members can actually have different sizes depending on the classes they point into.
See here for more info on pointer-to-member implementations in MSVC: http://blogs.msdn.com/b/oldnewthing/archive/2004/02/09/70002.aspx

A: Note the possibly unexpected result of:
printf("typeid(&C::b) = %s\n",typeid(&C::b).name());
printf("typeid(&B::b) = %s\n",typeid(&B::b).name());

Which on VS2010 yields:
typeid(&C::b) = int B::*
typeid(&B::b) = int B::*

This indicates that the resulting type for &C::b is a member pointer on type B.  Since C is derived from B the pointer is freely convertible to a member pointer on type C.  This explains the difference between the two values you see.  &C::b is a member function pointer on type B, int C::*p is a member function pointer on type C.
int B::*p_b = &B::b;
int C::*p_c = p_b;
printf("p_b = %p\n", p_b);
printf("p_c = %p\n", p_c);


text:
Q: Aurelia - which view port is the view-model being rendered in? I have a two-column layout setup, the two columns have very similar functionality, so the very same view-model is being reused. Hovewer, the rendering might slightly differ depending on which side is it being rendered, so wondering how is it possible to access view port information?
Consider this setup:
app.js
export class App {
    configureRouter(config: RouterConfig, router: Router): void {
        config.map([ {
            route: '',
            name: 'home',
            viewPorts: {
                left: { moduleId: 'module1' },
                right: { moduleId: 'module1' },
            }
        }]);
    }
}

app.html
<template>
    <router-view name="left"></router-view>
    <router-view name="right"></router-view>
</template>

module1.js
export class Module1 {
    activate(params: Object, routeConfig: Object, instruction: NavigationInstruction): void {
        //which view port am I being rendered in?
    }
}

A: My solution was to lookup the navigation instruction's viewport instruction object and compare if it is the very same object instance. I've created a convinient method for doing so.
navigation-instruction-extension.js
import {NavigationInstruction} from 'aurelia-router';

NavigationInstruction.prototype.viewPortFor = function(viewModelInstance: Object): string {
    for (let key in this.viewPortInstructions) {
        let vpi = this.viewPortInstructions[key];
        if (vpi.component.viewModel === viewModelInstance)
            return key;
    }
    return undefined;
}

module1.js
import 'navigation-instruction-extension.js';

export class Module1 {
    activate(params: Object, routeConfig: Object, instruction: NavigationInstruction): void {
        instruction.viewPortFor(this); //returns either 'left' or 'right'
    }
}

A: I've added a new Pull Request, when new version is released, the viewport's name will be accessible through regular lifecycle parameters:
activate(params: Object, routeConfig: Object, instruction: NavigationInstruction): void {
    routeConfig.currentViewPort //the name of current viewport
}


text:
Q: Gwt RPC in development mode I am wondering if I can test my RPC in Developement mode.Does service will be invoked from the client if I run my GWT project in development mode ?
EDIT :
Is it possible to test GWT RPC mechanism in GWT development mode as we do in production/web mode ?

A: Of course you can implement RPC in development mode.
Here is the link form Google's GWT tutorial :http://code.google.com/webtoolkit/doc/latest/tutorial/RPC.html

The sample application in the tutorial successfully implements GWT RPC. You don't need to run the application in production mode just for implementing/testing RPC.
If you are confused due to the fact that without setting any server(externally), How come you be able to do client-server programming(RPC),then don't be. GWT has its own internal server called Jetty Server to take care of this situation.
Hope this helps.


text:
Q: StoreFront Wordpress theme: How can i create a new Home page with Custom design same as template I am getting too frustrated while creating new home page using template in Storefront theme. https://wordpress.org/themes/storefront/.
With the help of this https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/
i tried bt not getting success.. anyone can tell me how can i do this without plug-in..
I want to change home page , and want to show my custom template home page. –
Updated:
I did not tried Child theme. But i think i have find out the issue.. My template name is not listing in Word press admin menu .. I tried with Twenty twelve bt same issue , template name not is in List during add page. –
Template Script
<?php
/**
 * Template name: Homepage My Custom
 *
 * @package storefront
 */

get_header(); ?>

    <div id="primary" class="content-area">
        <main id="main" class="site-main" role="main">
            **My Custom Home Template**
        </main><!-- #main -->
    </div><!-- #primary -->
<?php get_footer(); ?>


text:
Q: NSCache, image release, async queue This is supposed to display a placeholder in my any given table row unless an image for that indexpath exists. When I scroll down, the images from the previous indexPath loads over the default instead of releasing. I know someone helped me with the same problem before, but this was before I realized the importance of caching the images.  In my customCell method I have UIImage property set to strong, and I release the images for viewDidUnload.
NSString *imagename = [_imageCache objectForKey:indexPath];
UIImage *preview = [_imageCache objectForKey:imagename];

if (preview)
{
    [[cell myImageView] setImage:preview];
}
else
{
    [[cell myImageView] setImage:[UIImage imageNamed:@"CellLogo.png"]];

            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
            dispatch_async(queue, ^{

             //   __block UIImage *preview = nil;
               UIImage *preview = [UIImage imageWithData:object.iG];
              //             }
         if (preview)
         {
                dispatch_async(dispatch_get_main_queue(), ^{

                 //   if (cell)
                    [[cell myImageView] setImage:preview];

                });
             [_imageCache setObject:preview forKey:imagename];
         }
            });
}

A: As the error message states, you haven't declared imageFilename: anywhere in your code. There are no such methods by default and if you wish you can define a method in that name in current class as:
- (NSString *)imageFilename:(NSIndexpath *)indexpath {
  //code here
}

If you have already used it somewhere else, you need to import that particular class and call this method as NSString *imagename = [myobject imageFilename:indexPath]; where myobject is the object of that class.

A: Look up "cell reuse".  You need to implement -prepareForReuse in your UITableViewCell subclass.  It should reset the image to a placeholder or blank image.


text:
Q: cURL - 404 error when trying to POST a file Forgive my Linux n00bishness, I'm only just starting out! I'm trying to POST a file to a Windows web listener using cURL but am receiving an error that I haven't been able to find an explanation for online. I've never used cURL before (and am very new to Linux in general) so I don't know where to look for the issue. Here's what I've done so far:

*

*Navigated to the file directory /home/user/Documents

*Used the command curl --form "fileupload=@mesh.pcap" http://XXX.XXX.XXX.XXX (the file is obviously a pcap file, and the listener is being accessed by IP, simply trying to push the file to any location on the target)

And I receive the following message in the terminal:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Not Found

HTTP Error 404. The requested resource is not found.

Now I'm doing this all based on the cURL manpage, but have no idea if I'm doing it right at all, so if this doesn't even make sense please explain why and I'll do my best to clarify or try whatever suggestions you may have. I think I'm on the right track but the 404 error is confusing me and there is no file actually being transferred. What am I missing?
Edit: Some context... Basically I have a pcap file on the Linux box that I want to send to the web listener to be parsed. I don't necessarily need the file itself, as long as the data comes across one way or another. I'm trying to simulate something that a contractor is developing for us, my part is being able to parse the data from the pcap. He said he's sending it through cURL, so I thought I'd set up a little mock environment for testing purposes so we don't have to have a fully-running system before I can do my end of the task.


text:
Q: SQL Server error 3415 When i  attaching mdf file to SQL Server i am getting error database cannot be upgraded because it is read only or it has read only file. Make sure Database or files are writeable.

A: The database you attach is an previous SQL build. It has to be upgraded and it cannot be upgraded because the file is read only.

A: before you detach the database in the previous version.  Change any read-only file groups to read-write.  Microsoft also recommends that you turn on auto-grow if its disabled.
After you've attached the database in the new version, can then change the filegroup back to read-only and disable auto-grow.

A: I had this issue when attempting to attach a sql server 2000 database to a sql server 2008 r2 server. Checked that nothing had been marked read only. Ran management studio as administrator, problem solved.
The moral of my story is "Try running management studio as administrator while you do it".

A: In addition to checking any read-write flag on the file, make sure that the security ACLs on the file and the folder that you put it in will allow the login that the SQL Server service is using to  access the file. If you are unsure what the acl should look like, find the master.mdf file for your instance, look at the ACL/permissions for that file and then make the permissions for your particular mdf file match.
Also, you don't mention the ldf. If you are expecting the server to automatically create the ldf file, figure out where it will be creating and make sure that sql server can write files at that location. It would be better to create the database by attaching both the mdf and ldf files and NOT rely on SQL Server to create a missing LDF. There may be updates in the LDF that did not make it to your MDF file.

A: Thanks,Telarian
I had this issue when attempting to attach a sql server 2000 database to a sql server 2008 r2 server. Checked that nothing had been marked read only. Ran management studio as administrator, problem solved.
The moral of my story is "Try running management studio as administrator while you do it".
=> Running SSMS as an Administrator & giving db owner permission to the user by which you are trying to attach the database resolved my problem.


text:
Q: Chrome CORS troubles My node backend is set on Heroku, React frontend on Netlify. On firefox everything works good but on chrome I can login (post request) and then I can't move on my page cuz cors policy blocks my get requests to the server.

Access to XMLHttpRequest at 'https://xxx.herokuapp.com/api/fetchPurchasedPrizes' from origin 'https://xxx.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My backend cors setup
    app.use(
  cors({
    credentials: true,
    origin: 'xxx.netlify.app',
  }),
);

On localhost both browsers worked good.

A: Simple solution, I just had to add
cookie: {
  sameSite: 'none',
  secure: 'true',
},

to my session config.


text:
Q: Configure provisioning script for multiple instance VM vSphere deployment I can't quite work out how to add a provisioning "remote-exec" section to my module, where I would like it to copy configuration scripts from the project directory and execute them. But when I add this module I can't seem to have it target the VM instance and as it has multiple network cards, I would just like to target the primary card.
I have used this to deploy a Linux VM via Terraform on a on-premise vSphere instance.
provider "vsphere" {
  user           = var.vsphere_user
  password       = var.vsphere_password
  vsphere_server = var.vsphere_server
  # If you have a self-signed cert
  allow_unverified_ssl = true
}

This is the sample Linux deployment script outlining the network part, which allows configuring of multiple network card to a VM
resource "vsphere_virtual_machine" "Linux" {
  count      = var.is_windows_image ? 0 : var.instances
  depends_on = [var.vm_depends_on]
  name       = "%{if var.vmnameliteral != ""}${var.vmnameliteral}%{else}${var.vmname}${count.index + 1}${var.vmnamesuffix}%{endif}"
........
  dynamic "network_interface" {
    for_each = keys(var.network) #data.vsphere_network.network[*].id #other option
    content {
      network_id   = data.vsphere_network.network[network_interface.key].id
      adapter_type = var.network_type != null ? var.network_type[network_interface.key] : data.vsphere_virtual_machine.template.network_interface_types[0]
    }
  }
........
    //Copy the file to execute
    provisioner "file" {
      source      = var.provisioner_file_source // eg ./scripts/*
      destination = var.provisioner_file_destination // eg /tmp/filename
      connection {
          type     = "ssh" // for Linux its SSH
          user     = var.provisioner_ssh_username
          password = var.provisioner_ssh_password
          host     = self.vsphere_virtual_machine.Linux.*.guest_ip_address
        }
      }
    //Run the script
    provisioner "remote-exec" {
      inline = [
        "chmod +x ${var.provisioner_file_destination}",
        "${var.provisioner_file_destination} args",
      ]

      connection {
        type     = "ssh" // for Linux its SSH
        user     = var.provisioner_ssh_username
        password = var.provisioner_ssh_password
        host     = self.vsphere_virtual_machine.Linux.*.guest_ip_address
      }
    }
 }
} // end of resource "vsphere_virtual_machine" "Linux"

So I have tried self. reference but thus far self.vsphere_virtual_machine.Linux.*.guest_ip_address this just shows the entire array of guest IPs?
Anyone able to point me in the right direction or even a good guide on terraform modules?

A: The first issue I notice is that the vsphere_virtual_machine resource doesn't have a property guest_ip_address, it is guest_ip_addresses. This does indeed return a list, so you would need to figure out how to select the IP you want from the list. I'm not sure if the ordering is predictable in vSphere. If I recall, it isn't.
The simplest approach, without knowing what you're trying to accomplish, would probably be to use the default_ip_address as this returns a single address and selects the ip for the "most likely" scenario.
It looks like you're also setting up the host to be multi-homed. This adds additional complexity. If default_ip_address doesn't give you what you want, you'll need to resort to using some more complex expression to find your IP. Perhaps you could use the sort function so the ordering is more predictable. You may also be able to "find" the IP using a for loop.
Regarding building modules, if the above code is in a module, the first thing I would recommend is avoiding the use of count. Reasoning for this is explained in the following texts. Hashicorp has a lot of good documentation directly on their site. Also, the folks over at gruntwork also have a blog series that they developed into a book called Terraform Up and Running. I recommend checking this out.


text:
Q: Python3 won't recognize a variable in code All my code is below.
Just started learning to program this week. I'm attempting to make a Monty Hall simulator (text only) where the player chooses a door by selecting 1, 2 or 3. For some reason, though, Python doesn't seem to be recognizing the input!
Here are links to the game for the uninitiated:
Monty Hall wikipedia page
Monty Hall simulation
What my program attempts to do is as follows. First the player chooses a door, either 1, 2 or 3. Then the program checks to make sure that the player did indeed enter one of those three numbers. If not, then the person needs to choose again.
After this, the game randomly chooses a winning door. Then, per the rules of the game, the program needs to reveal a dummy prize (the goat). So the program randomly chooses one of the doors to be the "goat door." The program first makes sure that this door is not the winning door nor is it the chosen door.
Here's the error I get when running my code:
line 52, in <module>

     doors()

line 14, in doors

     while goatDoor == chosenDoor or goatDoor == winningDoor:

NameError: name 'chosenDoor' is not defined

My issue is that I can't tell why it keeps saying that chosenDoor is not defined!
Here's the code:
import random

def chooseDoor():   # choose a door
    chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')

def doors():    # the winning door and the dummy door are randomly selected
    winningDoor = random.randint(1,3)
    goatDoor = ''
    while goatDoor == chosenDoor or goatDoor == winningDoor:
        goatDoor = random.randint(1, 3)

def keepOrSwitch():
    switchDoor = 1
    if switchDoor == chosenDoor or switchDoor == winningDoor:
        switchDoor = 2
        if switchDoor == chosenDoor or switchDoor == winningDoor:
            switchDoor = 3
    print('Do you want to')
    print('KEEP your choice of door number ' + str(chosenDoor) + '?')
    print('...or...')
    print('Do you want to')
    print('SWITCH and choose door number ' + str(switchDoor) + '?')
    print()
    choice = ''
    while True:
        print('Type \'K\' for keep or type \'S\' for switch.')
        choice = input()
        if choice == 'K' or choice == 'k':
            break
        if choice == 'S' or choice == 's':
            chosenDoor = switchDoor
            break

def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')

# the rest of the code is the actual game
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':

    chooseDoor()

    doors()

    keepOrSwitch()

    checkWin()

    print('Do you want to play again? (yes or no)')
    playAgain = input()

A: In your function:
def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')

you try to compare chosenDoor to winningDoor, but they are not yet defined. The function checkWin() has no access to localy defined variables in other functions.
You have to refactor your code. Eventually you could assign some parameters to the function checkWin and return some values from the other functions.
Also:
# the rest of the code is the actual game

can be replaced by:
if __name__ == "__main__":
    # your actual game

This is the standard way to run a Python program. If you import anything from this module in another file, the code won't run by accident.
EDIT:
the error is actually caused by this line:
while goatDoor == chosenDoor or goatDoor == winningDoor:

In your function doors() you define goatDoor and winningDoor, but chosenDoor is not declared.
In the function keepOrSwitch() you have the same problem.
Nevertheless the function checkWin() will cause an error, too.
You have to refactor your function chooseDoor() too. It has a print statement after the return statement. It enters the while loop and will finish the function call never reaching the last line.
The simplest way to fix this would be to assign the return value of chooseDoor to a variable:
choosenDoorByTheUser = chooseDoor()

and later call the other functions with that variable as argument.

A: Your variables are out of scope, you need to store the variables you're making down in the while loop and return the values from the methods you've made, then pass the values to checkWin
keepOrSwitch should return chosen
chooseDoor should return chosenDoor
doors should return winningdoor/goatdoor
checkwin should take chosenDoor + winnindoor + goatdoor
you'll then be able to reference your variables correctly

A: You have posted a lot of code and it looks like a scope issue, the variables in your functions are not visible inside the other functions.
The quick and dirty way to fix this is to make that variable causing the error global like this:
def chooseDoor():   # choose a door
    global chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')

I think that will probably fix it but it's not good coding practice.

A: In a python program you've only defined chosenDoor in the chooseDoor() function and you haven't passed chosenDoor into the next function doors().  You can pass chosenDoor to doors() by doing doors(chosenDoor).


text:
Q: Opshub and user migration I am trying to migrate source control only from a TFS2013 system to VSTS and I have a question about how to manage user migration.
We have been using TFS since it was released and have a >250000 changeset history that we would like to preserve.
We have linked our Azure AD to the VSTS project and I have added in a relevant group that contains most of our current users, but these are not showing up in the user mapping screen presumably as they are not 'proper' users until they have logged on and applied their MSDN license. Is there an easy way of adding around 200 users to the system and applying a license?
Most of the other users that require mapping have long since left the company but it is useful to see which person made which changeset. This class of user will never have an active account on TFS but the current system would force me to remap these users to a current account losing that information. Is there any way of keeping this data?


text:
Q: dynamic_cast for multiple derived classes I have a base class and n derived class. I want to instantiate a derived class and send it to a function that receive as an argument a base class. Inside the function, I found which type of derived class it is by using dynamic_cast, but I don't want to use several if-else sentences. Instead, I would like to know if there is a way to find out which derived class is it in order to cast it.
  Here I leave my code as an example.
class animal{
   public:
          virtual ~animal() {}
          int eyes;

  };

class dog: public animal{
   public:
         int legs;
         int tail;
  };

class fish: public animal{
   public:
         int mostage;
  };

void functionTest(animal* a){
  if(dynamic_cast<fish*>(a) != NULL){
                             do_something();
                             }
  else if(dynamic_cast<dog*>(a) != NULL){
                              do_something();
                              }
 };

I would like to have a more general approach to this. Something like  dynamic_cast(a). Thank you!

A: It's great to do this for quick drafts if you need to demonstrate something in a few minutes, but usually you try to avoid using dynamic_cast this way - it can lead to extremely high maintenance costs if used in the wrong places. Various patterns are available, such as a simple method overload, the Visitor pattern, or a virtual "GetType" function (which could be implemented with the curiously recurring template pattern, if you like patterns).
I'll list all 3 approaches. The first one is by far the most straightforward, and easiest to use. The advantages of the other 2 is that each of them moves the decision of what to do to a different part of the code, which can be a huge benefit (or drawback).
Lets assume this is what you want to do:
void functionTest(animal* a)
{
    if(dynamic_cast<fish*>(a) != NULL)
        blub();
    else if(dynamic_cast<dog*>(a) != NULL)
        bark();
};

Simple virtual function approach:
class animal {
public:
    virtual ~animal() {}
    virtual void do_something() = 0;
    int eyes;
};

class dog : public animal {
public:
    virtual void do_something() { bark(); } // use override in C++11
    int legs;
    int tail;
};

class fish: public animal {
public:
    virtual void do_something() { blub(); } // use override in C++11
    int mostage;
};

void functionTest(animal* a)
{
   if (a) a->do_something();
};

Visitor approach:
class IVisitor {
public:
   ~IVisitor(){}
   virtual void visit(const fish&){}
   virtual void visit(const dog&){}
   virtual void visit(const animal&){}
};

class animal {
public:
    virtual ~animal() {}
    virtual void accept(IVisitor& visitor) = 0;
    int eyes;
};

class dog : public animal {
public:
    virtual void accept(IVisitor& visitor) { visitor.visit(*this); }  // use override in C++11
    int legs;
    int tail;
};

class fish : public animal {
public:
    virtual void accept(IVisitor& visitor) { visitor.visit(*this); }  // use override in C++11
    int mostage;
};

class MyVisitor : public IVisitor {
public:
   virtual void visit(const fish&) { blub(); } // use override in C++11
   virtual void visit(const dog&) { bark(); }  // use override in C++11
};

void functionTest(animal* a)
{
    if (a)
    {
        MyVisitor v;
        a->accept(v);
    }
};

GetType approach, with CRTP spice:
class animal {
public:
    virtual ~animal() {}
    virtual const type_info& getType() const = 0; // careful. typeinfo is tricky of shared libs or dlls are involved
    int eyes;
};

template <class T>
class BaseAnimal : public animal {
    // these are C++11 features. Alternatives exist to ensure T derives from BaseAnimal.
    static_assert(std::is_base_of<BaseAnimal,T>(,"Class not deriving from BaseAnimal");// C++11

    virtual const type_info& getType() const { return typeid(T); }
};

class dog : public BaseAnimal<dog> {
public:
    int legs;
    int tail;
};

class fish : public BaseAnimal<fish> {
public:
    int mostage;
};

void functionTest(animal* a)
{
   if (!a)
      return;
   if (a->getType() == typeid(fish))
        blub();
   else if (a->getType() == typeid(dog))
        bark();
};

Notice that you should consider the above examples to be pseudo-code. For best practices you will need to look up the patterns. Also, the curiously recurring template pattern can also be used in the second approach, or it can be easily removed from the third. It's just for convenience in these cases.

A: You may use virtual functions for that:
class animal{
public:
    virtual ~animal() {}
    virtual void do_thing() = 0;
};

class dog: public animal{
public:
    void do_thing() override { std::cout << "I'm a dog" << std::endl; }
};

class fish: public animal{
public:
    void do_thing() override { std::cout << "I'm a fish" << std::endl; }
};

And then
void functionTest(animal& a){
    a.do_thing();
}

As an alternative, if you want to avoid to have to many virtual functions, you may use visitor pattern

A: Let me strongly urge you to NOT do what you have here and to follow the very wise advice that everyone has given to use polymorphism (e.g. virtual functions). The approach you've outlined could be made to work, but it is working against the tools the language provides. What you are trying to do is exactly why the language has virtual functions.
With your method, if you add a new sub-class of animal then you also have to change  function_test(), and function_test() is doing what the compiler would do for virtual functions anyway, but in a much clumsier and inefficient way.
Using virtual functions, all you have to do is implement do_something() in the new sub-class and the compiler takes care of the rest.
Don't use dynamic_cast<>() for this. That's not what it is for.

A: Consider implementing this "switch" as virtual functions.
If you do not want that, you can either use dynamic_cast as in your example, or you use the typeid operator to compute a mapping for the result of typeid to a function that implements the do_something code.
However, I would not recommend that, as you just end up with a hand-coded vtable. It is better to use virtual functions and let the compiler generate the mapping.
For additional reading, I recommend Herb Sutter's article Type inference vs static/dynamic typing. He mentions Boost variant and Boost any, which might be possible alternatives for your problem.

A: The "classical" type-switch by Stroustrup may be suitable for your needs:
https://parasol.tamu.edu/mach7/
https://parasol.tamu.edu/~yuriys/pm/
Basically it will let you do a switch-case like based on obect type, using one of three different implementations


text:
Q: Understanding proof that continuous image of connected is connected I am trying to understand the proof: A continuous image of a connected space is always connected.
This is how it goes:

If $f:X\to Y$ is a surjective continuous map with $X$ connected, then we need to show $Y$ is also connected. Suppose $Y$ is disconnected. Then there exists a non-empty clopen subset $U\neq Y$ in $Y$. Since $f$ is surjective, $f^{-1}(U)\neq\varnothing,X$. Since $f$ is continuous, $f^{-1}(U)$ is clopen. This contradicts that $X$ is connected.$\blacksquare$

I understand everything in this proof EXCEPT why we supposed that $f$ is continuous and surjective. Our question is only about continuous maps so why did we assume that $f$ was continuous and surjective? What about if the map is continuous but not surjective, then this proof will not work?

A: Asserting that the image of $f$ is connected is asserting that $f(X)$ is connected. What happens in $Y\setminus f(X)$ does not matter. So, it is natural to assume from the start that $Y$ is just $f(X)$; in other words, that $f$ is surjective.


text:
Q: MacBook Pro Keyboard - How to Swap / Remap Keys? I know this may be asked before in a different manner, but I still haven't really seen a solid answer. I'm hoping that providing these 2 specific needs will make it more clear.
I specifically want 2 behaviors that will make my transition from a long time PC user to being able to use a MacBook Pro.
Background:

*

*I am a windows user that just got my first mac ever (in my life) this past weekend.

*I am dual booting the MBP with Snow Leopard and Windows 7 x64

What I want to do (in both Windows 7 and Snow Leopard):

*

*Swap the fn and control keys (not physically)

*Be able to tap the eject key for a forward delete, but keep the ability of holding down the eject key to actually eject the disc.

Are these possible, if so what is the best way (software?) of accomplishing this in both Windows 7 and Snow Leopard?

A: On the Snow Leopard side you can swap Control and Fn with Karabiner (formely KeyRemap4MacBook).
If you're dual-booting, a good idea is to swap Command and Control in OS X's preferences. You'll get physically same keyboard shortcuts on both.

A: Just as a sidenote you may also consider taking a look at the normal OS X system preferences under Keyboard there is a button on the lower-right named "Modifier keys" where you can define which actions should be taken by the modifier keys (caps-lock, ctrl, cmd,...). Could also be enough in some situation without installing 3rd-party software.

A: On OS X: DoubleCommand

On Windows: SharpKeys

For anything more extensive, you'll want AutoHotkey (Windows) or IronAHK (AutoHotkey rewrite that works with Mono for cross-platform compatibility - Linux, Mac, etc).

A: There is keyboard maestro that does this

A: As John T pointed out, AutoHotKey does everything on Windows, and that's it.
For Mac, IronAHK used to be good too, back when it existed.
So there's another option that, while I could never really use, seems to do what you need. Although it's very very technical, it's highly customizable. I'll just quote the website:

Ukelele is a Unicode
  Keyboard Layout Editor for Mac OS X
Ukelele aims to simplify keyboard
  layout editing by providing a
  graphical interface to .keylayout
  files, where the desired characters
  can simply be dragged onto keys as
  needed. (The Character Palette,
  available in the Input menu if it has
  been enabled in System Preferences, is
  a great place to find the characters.)
In addition to simple assignment of
  single character codes to keys,
  Ukelele can assign multiple-character
  strings and can create "dead keys",
  where a keystroke sets a new state
  that modifies the output of the
  following keystroke.

Hope it can help you where it couldn't for me back when I found it. ;)

A: You can use BetterTouchTool, it's a free tool with wich you can reprogram keys and multi-touch gestures. Make sure that in your settings you have set the F1, F2, etc-keys as default. Open BetterTouch and remap your keyboard. Don't forget to automatically let it run after logging in. It's also a very usefull tool for working with multi-touch gestures. I use it to swipe through my Spaces with four fingers. I don't like the default gestures in Snow Leopard.

A: On Windows, someone implemented a kernel-mode driver to do this magical feat for the wireless Apple keyboard. I am not sure if it works for a macbook. The FAQ says that an option is to install Windows "natively." Regardless, there is a good chance a small modification to the source code could get it working everywhere.
https://github.com/samartzidis/WinA1314


text:
Q: QSpatiaLite query syntax Using the QSpatiaLite plugin in QGIS I composed the following query
SELECT  'AddressPoint_2'.'buildingNu', 'AddressPoint_2'.'postCode' WHERE  'AddressPoint_2'.'postCode' = 'NR13 3AA'  FROM  'AddressPoint_2'
This returns an error:
"The SQL query seems to be invalid near "FROM":syntax error."
A previous query:
SELECT   'AddressPoint_2'.'buildingNu', 'AddressPoint_2'.'postCode' FROM 'AddressPoint_2'
runs OK. I cannot see why the slightly more complicated query is failing on the same use of FROM
Any pointers please?

A: Move your FROM clause before your WHERE clause: SELECT ... FROM ... WHERE ...


text:
Q: Smart-Table - AngularJs - Wrap within a directive I'm very new to AngularJs and trying to "wrap" the Smart-Table plugin inside a directive.
I can get the rows but the pagination is not showing
Currently this is what I did.
    app.directive('grid', [ function () {
    return {
        restrict: 'E',
        replace: true,
        template: function (element, attrs) {
            return '
'
                          + '
'
                          + '
'
                                  + 'Team	'
                                  + 'Team Freq	'
                                  + 'Team Sac	'
                                  + 'Priority	'
                              + '
'
                          + '
'
                          + '
'
                              + '
'
                                 + ' {{row.firstName}}	'
                                  + '{{row.lastName | uppercase}}	'
                                  + '{{row.age}}	'
                                  + '{{row.email}}	'
                              + '
'
                          + '
'
                          + '
'
                              + '
'
                                 + ''
                                  + '

'
                                  + '	'
                              + '
'
                          + '
'
                      + '
';

        },
        scope: {

        },
        controller: function ($scope) {

        },
        link: function (scope, elem, attrs) {
            var nameList = ['Pierre', 'Pol', 'Jacques', 'Robert', 'Elisa'], familyName = ['Dupont', 'Germain', 'Delcourt', 'bjip', 'Menez'];
            function createRandomItem() {
                var
                    firstName = nameList[Math.floor(Math.random() * 4)],
                    lastName = familyName[Math.floor(Math.random() * 4)],
                    age = Math.floor(Math.random() * 100),
                    email = firstName + lastName + '@@whatever.com',
                    balance = Math.random() * 3000;

                return {
                    firstName: firstName,
                    lastName: lastName,
                    age: age,
                    email: email,
                    balance: balance
                };
            }

            scope.rowCollection = [];
            for (var j = 0; j < 10; j++) {
                scope.rowCollection.push(createRandomItem());
            }
            scope.dataset = [].concat(scope.rowCollection);
        }
    };
}]);

My html contains this tag
  <grid st-table="dataset"></grid>

This code is just a test, the data will be passed using a service.. and the template will be dynamic.
I need some help :-)
Thanks

A: I couldn't get the pagination to show when I was using smart-table in a directive the other day. Turns out it had nothing to do with the directive and I just pulled/updated to the very latest version of smart-table from GitHub and it all worked. I started looking at the what had changed but got side tracked and moved onto something more productive, happy that it was now working.
Version I have that appears to be working fine is tagged 1.4.2.
With dynamic data from a service, however, I think you're going to need to look at the st-safe-src attribute too. Although I'm new to this whole Angular / smart-table business too.

A: I believe you have to match the st-table value and the st-pagination value to get the pagination to show.


text:
Q: Supporting docker based and non docker based deployments Currently for my python project I have a deploy.sh file which runs some apt-get's, pip installs, creates some dirs and copies some files.... so the process is git clone my private repo then run deploy.sh.
Now I'm playing with docker, and the basic question is, should the dockerfile RUN a git clone and then RUN deploy.sh or should the dockerfile have its own RUNs for each apt-get, pip, etc and ignore deploy.sh... which seems like duplicating work (typing) and has the possibility of going out of sync?

A: That work should be duplicated in the dockerfile. The reason for this is to take advantage of docker's layer and caching system. Take this example:
# this will only execute the first time you build the image, all future builds will use a cached layer
RUN apt-get update && apt-get install somepackage -y
# this will only run pip if your requirements file changes
ADD requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
ADD . /app/

Also, you should not do a git checkout of your code in the docker build. Just simply add the files from the local checkout to the images like in the above example.


text:
Q: gt Tables - applying formatting to multiple dataframes I have several tables that all need to be formatted similarly. I figured out how I want the tables formatted on one table, and have been trying to write a function that I can apply to all tables easily without having to copy and paste the code over and over
Here is my sample data frame
example <- data.frame(
  stringsAsFactors = FALSE,
               age = c("age 12 to 17", "age 18 to 25", "age 26 and up"),
           alc_est = c(14579.28558, 131872.35964, 660957.6512),
          bing_alc = c(0.0477, 0.3143, 0.224),
          marj_est = c(35913.3345, 137033.12968, 534667.52856),
            mj_use = c(0.1175, 0.3266, 0.1812),
        heroin_est = c(NA, 419.5748, 18294.36356),
        heroin_use = c(NA, 0.001, 0.0062),
          meth_est = c(550.16172, 2139.83148, 68161.25778),
          meth_use = c(0.0018, 0.0051, 0.0231)
)

Here is some of the formatting that will be applied to multiple tables
table_format <- example %>%
  gt(rowname_col = "age") %>%
  tab_stubhead(label = md("**Statewide**")) %>%
  tab_header(
  title = md("**table title here**"),
  subtitle = "more info here"
   ) %>%
  fmt_number(
      columns = c(2, 4, 6, 8),
      decimals = 0
      ) %>%
    tab_spanner_delim(
    delim = "_",
    columns = c(2:9)
)

Here is how I tried to write a function to apply to multiple tables. The function runs but doesn't actually format the table
format_use_est <- function(df_here) {
  result <-  df_here %>%
    gt(rowname_col = "age") %>%
  tab_stubhead(label = md("**Statewide**")) %>%
  tab_header(
    title = md("**table title here**"),
    subtitle = "more info here"
  ) %>%
    fmt_percent(
    columns = c(3, 5, 7, 9),
    decimals = 1
  ) %>%
    fmt_number(
      columns = c(2, 4, 6, 8),
      decimals = 0
      ) %>%
    tab_spanner_delim(
    delim = "_",
    columns = c(2:9)
      )
}

How can I write a function for formatting these tables and apply to multiple tables more effectively? Thank you!


text:
Q: What is complete purpose of a Frame ContentControl in UWP I'm quite new to UWP development and even less experienced with Xamarin Forms. I came across a pretty hard to debug situation, which made me think 'What does a Frame really handle under the covers other than only supporting navigation'
According to the MSDN documentation the Frame class has this purpose:

Displays Page instances, supports navigation to new pages, and maintains a navigation history to support forward and backward navigation.

In literally all examples I find, the default template in VS for a blank UWP app and the template for Xamarin Forms app I see this code:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;

    if (rootFrame == null)
    {
        rootFrame = new Frame();
        // some code removed for brevity...

        Window.Current.Content = rootFrame;
    }

    if (rootFrame.Content == null)
    {
        rootFrame.Navigate(typeof(MainPage), e.Arguments);
    }

    Window.Current.Activate();
}

And this seems fair, because an app will almost certainly need to navigate between multiple pages.
However, when one would use a MVVM framework, e.g. Caliburn Micro, navigation will be handled by this framework and the use of a Frame seems useless.
So in my App I chose to remove the template code and put a normal Page as rootelement. And this works as expected, it will just show this view.
But when I combined this with Xamarin Forms, together with a CommandBar in which I placed a default 'AppBarButton' without an icon set, the app throwed an exception.
When I changed the root element again with a Frame the exception went away. Placing a valid Icon in the AppBarButton did also made the exception to go away with a normal Page as rootelement.
So must the rootelement of the visual tree be a Frame in order to let everything work correctly, because apparently a Frame has influence on the correct functioning of an AppBarButton?
Edit:
I'm not really interested in solving the exception. But if it helps explaining what a Frame does under the covers, I created a repo here
Edit 2:
Maybe I'm missing something, but I don't see any stacktrace nor callstack and the description is not much of a help!


text:
Q: Возникает ошибка в ветвлении. Постоянно выводится "данного треугольника не существует". Visual studio 2019 #include iostream
#include cmath

void length(int x1, int x2, int x3, int y1, int y2, int y3)
{
    double AB, BC, AC;

    AB = sqrt(pow((x2 - x1), 2) - pow((y2 - y1), 2));
    BC = sqrt(pow((x3 - x2), 2) - pow((y3 - y2), 2));
    AC = sqrt(pow((x1 - x3), 2) - pow((y1 - y3), 2));

    if ((AB + BC > AC) && (BC + AC > AB) && (AC + AB > BC))
    {
        std::cout << "AB= " << AB << std::endl;
        std::cout << "BC= " << BC << std::endl;
        std::cout << "AC= " << AC << std::endl;
    }

    else
    {
     std::cout << "данного треугольника не существует" << std::endl;
    }
}

int main()
{
    setlocale(LC_ALL, "Russian");

    int x1, y1, x2, y2, x3, y3;

    std::cout << "Эта программа вычисляет параметры треугольника" <<
"(координаты точек - целые числа) " << std::endl;
    std::cout << "Введите координату x1 точки A: ";
    std::cin >> x1;
    std::cout << "\nВведите координату y1 точки A: ";
    std::cin >> y1;
    std::cout << "\nВведите координату x2 точки B: ";
    std::cin >> x2;
    std::cout << "\nВведите координату y2 точки B: ";
    std::cin >> y2;
    std::cout << "\nВведите координату x3 точки C: ";
    std::cin >> x3;
    std::cout << "\nВведите координату y3 точки C: ";
    std::cin >> y3;
    length(x1,x2,x3,y1,y2,y3);

    return 0;
}

A: AB = sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2));
                            ^ - Теорема Пифагора


text:
Q: Is there an option for "Mark All Emails as Read Across All Folders" in Outlook? I have lots of Outlook folders (30+) and they each get a trickle of over 200 emails a day.
Usually I scan through each folder to make sure nothing important is in there and right click on the folder and press E to 'Mark All as Read'.
This gets tedious and I want to eliminate the second step so I can just scan through my folders then press a button to mark all subfolders and folders as read at the end.
I would like to say this differs from this as I would like to know which emails are new and not have them automatically all be marked as read when they come in.

A: The Search Folder tip does the work. To do this go "Folder" tab > press "New Search Folder" > on the pop window select "Unread mail" > Press OK.
This will create a folder, like all your others, on the left menu (where you have Inbox, Sent Items so on), named Search Folder > Unread Mail and you can right click and "Mark all as read".

A: No there isn't a single button that does this, not in the Outlook client.
You could use a search query and then select all (Ctrl - A), right-click, and then mark all as read.

A: I found a way to do this:
Based on the other answer of doing a search, I created a new customized search folder and selected all of my folders that I wanted to do a mass "Mark as Read" action, with a criteria of "unread".  This made a new "Unread" search folder for just the targeted folders.  Now I can do a single right-click and "Mark All as Read".

A: follow below steps;
click on search box
type: isread:no
next to the search box is an option which you specify the search scope (current folder, All mailboxes,...) choose the one you need
once the search is done, press Ctrl+A, right click "mouse", and press read
ta-da. it's done :)


text:
Q: "and I'm the Queen of Sheba" According to Longman Dictionary the droll comeback...

and I'm the Queen of Sheba
  (humor) used as a reply when someone claims that they are famous or that they have done something impressive, but you do not believe them
'I'd like to reserve a table for tonight – this is Demi Moore.'
  'Oh yeah, and I'm the Queen of Sheba.'

A movie poster of The Queen of Sheba, an Italian drama/romance movie released in 1952
Amazingly, Phrase Finder has no information on this pithy rejoinder.

*

*I believe that the catchphrase is a snowclone of "I'm the Queen of England" or "I'm the King of Siam" but which came first? And why is it the Queen of Sheba and not some other ancient or mythological kingdom?

*I have a sinking feeling that it is terribly old-fashioned nowadays. What would be its modern-day counterpart?

A: The first use of the expression

I am the Queen of Sheba,

by somebody who was not actually the queen of Sheba herself, that I can find on Google books is in the 1877 book

The Queen of Sheba, by Thomas Bailey Aldritch,

where it is used repeatedly by somebody who does not actually seem to be the Queen of Sheba. It doesn't appear to be used in the sense the expression is used in today—if that's true, then I'm the queen of Sheba. From skimming the book, it appears that she is mentally ill (at least, she has been put in an insane asylum).
So this probably explains why we generally use Sheba as the country in this snow clone, unless the expression was around before this book was written and the book is playing off it. I can't find any instances of this snow clone (either with the Queen of Sheba or with other people) in Google books before 1877, but I easily could have missed them.

A: As a point of interest, the reverse case,

or I am the Queen of Sheba

wherein the contrary-to-fact claim serves to humorously assert the truth (rather than the falsehood) of the preceding statement, appears at least as early as 1833, in The Stolen Child, by Scottish novelist John Galt:

However, give yourself no uneasiness, you are my lord's brother or I am the Queen of Sheba.

The speaker, a Mrs Servit, is characterized by her use of Scottish idioms in conversation:

...her accent, however, betrayed her Scottish origin, and yet she did not exactly speak the language of the country, though with a few deviations she evinced a perfect mistressy of its most recondite and common idioms.

These circumstances, along with the nationality of the the author, although they do not establish the point, suggest that the contrary-to-fact claim "and/or I am the Queen of Sheba" may have been a Scottish idiom in the early 1800s.
The earliest similar use of "I am the Queen of England" uncovered by my research appears in the 1849 romance Trials of Love, by Mrs H.M. Lowndes née Hannah Maria Jones:

He's about as much of a footman as I am the Queen of England....

For "I am the King of Siam", my research turned up no uses in the 1800s or earlier.

A: At the turn of the previous century, the Queen of Sheba was a crowd-pulling spectacular traveling show, the most famous actress was a Russian "Queen of Sheba". Solomon and the Queen of Sheba was one of the many themes such as Cleopatra included in travelling shows. By the 1910s the Ringling Bros. Circus had more than 1,000 employees, 335 horses, 26 elephants, 16 camels and other assorted animals that travelled on 92 railcars. "The Greatest Shows on Earth" included pageantry and other performances in addition to the ring.

*

*
These and similar spectaculars would have been very well known to G. B. Shaw when he wrote his plays that retold historical events in modern settings.
One of Shaw's most successful plays, Pygmalion, written in 1912 was staged in Vienna the following year and in Berlin shortly afterwards. By 1914 the author of Pygmalion has become the most popular writer in England.
The story was later presented to the masses first as Pygmalion on the screen

*

*
and later became M(a)yFair Lady.

ELIZA [curiously] 'Ere, what's that you say?
HIGGINS. Yes, you squashed cabbage leaf. You disgrace to the noble
  architecture of these columns! You incarnate insult to the English
  language! I could pass you off as, er, the Queen of Sheba.
ELIZA [laughing] Ah-how-ow!

https://en.wikipedia.org/wiki/Pygmalion_(play)#Different_versions
Around the early 1930's there were several movie adaptations and in  movie magazines there were Woolworths Stores advertisements for Embassy Powder,

"A $1 quality face powder for 20c? If that's true, I'm the Queen of
  Sheba."


text:
Q: Fastest and most efficient way to insert and update a lot of rows in cassandra using cqlengine I have a csv file with 15000000 records that I'm trying to process into a cassandra table. Here's an example of the column headers and data:

To help make more sense of it, here is my model in python:
class DIDSummary(Model):
    __keyspace__ = 'processor_api'

    did = columns.Text(required=True, primary_key=True, partition_key=True)
    month = columns.DateTime(required=True, primary_key=True, partition_key=True)
    direction = columns.Text(required=True, primary_key=True)
    duration = columns.Counter(required=True)
    cost = columns.Counter(required=True)

Right now I'm trying to process the data in each row of the csv file and insert them in batches of 500, 1000, 10000, 250, etc. but with the same time results (about .33 seconds per 1000, which means it would take 90 minutes to get through all of them). I also tried taking a multiprocessing pool and apply_async()'ing each batch.execute() call, with no better results. Is there a way I could, in python, use an SSTableWriter, or do something else to insert them into cassandra better? For reference, here's my process_sheet_row() method:
def process_sheet_row(self, row, batch):
    report_datetime = '{0}{1:02d}'.format(self.report.report_year, self.report.report_month)
    duration = int(float(row[self.columns['DURATION']]) * 10)
    cost = int(float(row[self.columns['COST']]) * 100000)

    anisummary = DIDSummary.batch(batch).create(did='{}{}'.format(self.report.ani_country_code, row[self.columns['ANI']]),
                                                direction='from',
                                                month=datetime.datetime.strptime(report_datetime, '%Y%m'))
    anisummary.duration += duration
    anisummary.cost += cost
    anisummary.batch(batch).save()

    destsummary = DIDSummary.batch(batch).create(did='{}{}'.format(self.report.dest_country_code, row[self.columns['DEST']]),
                                                 direction='to',
                                                 month=datetime.datetime.strptime(report_datetime, '%Y%m'))
    destsummary.duration += duration
    destsummary.cost += cost
    destsummary.batch(batch).save()

Any help would be greatly appreciated. Thanks!
Edit: Here is my code for going through the file and processing it:
with open(self.path) as csvfile:
    reader = csv.DictReader(csvfile)
    if arr[0] == 'inventory':
            self.parse_inventory(reader)
    b = BatchQuery(batch_type=BatchType.Unlogged)
    i = 1
    for row in reader:
        self.parse_sheet_row(row, b)
        if not i % 1000:
            connection.check_connection() # This just makes sure we're still connected to cassandra. Check code below
            self.pool.apply_async(b.execute())
            b = BatchQuery(batch_type=BatchType.Unlogged)
        i += 1
print "Done processing: {}".format(self.path)
print "Time to Execute: {}".format(datetime.datetime.now() - start)
print "Batches: {}".format(i / 1000)
print "Records processed: {}".format(i - 1)

And just because this might be a bit of help, here's the connection.check_connection() method (and surrounding methods):
def setup_defaults():
    connection.setup(['127.0.0.1'], 'processor_api', lazy_connect=True)

def check_connection():
    from cdr.models import DIDSummary
    try:
        DIDSummary.objects.all().count()
    except CQLEngineException:
        setup_defaults()

A: Batches, in general, aren't the fastest method for performing insertions. Especially so in your unlogged batches containing various partitions. Some reading on batches here
If you can pull away from cqlengine for insertion, you should try async callback chaining which is implemented in the Python driver under: cassandra.execute_concurrent.
I've had major improvements in inserts/sec moving to this method after misusing batches of various sizes, but YMMV.


text:
Q: Is there a way to undo VGA adapter modesetting in Linux I'm looking for a way to reset the graphics adapter to textmode after it has been set to some sort of graphical mode by the kernel on bootup, and possibly used by an X server.
Is there any code to do this in the Kernel or the X Server?
I figure there must have been such code, because before the introduciton of KMS, the X server used to set the VGA adapter back to text mode when switching to a linux console (e.g. Ctrl+Alt+F1)
I also figure that this is highly adapter-specific. My graphics adapter is controlled by i915.
I've been looking at places in the X source code where I assumed the code would reside, but have been unable to find anything.
So the precise thing I am asking of you would be, in this priority,

*

*A kernel interface that allows returning to textmode

*An existing utility

*An ugly hack that might involve directly writing to the kernel memory or invoking the VGA bios to do the initialization

*Hints at where (version-wise, repository-wise and sourcefile-wise) in the pre-KMS X or kernel sources I might find such code

I have found a utility called restoretextmode, but all it did was crash my VGA adapter. It appears to come from ancient times, and not to be designed to handle these kinds of situations at all (but I might be in error).
For those of you who are curious why I require this functionality, it is related to running all kinds of low-level utilities such as memtest86 or a boot loader directly via kexec. These utilities require the graphics adapter to be in textmode.


text:
Q: ggplot Stacked barplot with uncertainty I would like to show the confidence interval for a stacked barplot. With whiskers the display is not quite correct (whiskers are always appended at the end, with 100% this makes no sense). While searching for alternative ways of plotting, I came across the following (see Image). Is something like this possible in ggplot2 f.e. with addins?
Thanks in advance.

A: Yes, it's possible, but requires a little bit of data manipulation, faking a discrete axis from a continuous one, and using geom_area instead of geom_bar
In the absence of a reproducible example, here's one using the iris data set:
library(tidyverse)

iris %>%
  group_by(Species) %>%
  mutate(width = factor(ifelse(Sepal.Width > 3, 'wide', 'narrow'))) %>%
  nest(data = - Species) %>%
  mutate(data = map(data, ~ prop.test(table(.x$width))),
         prop = unlist(map(data, ~ .x$estimate)),
         lower = unlist(map(data, ~ .x$conf.int[1])),
         upper = unlist(map(data, ~ .x$conf.int[2]))) %>%
  select(-data) %>%
  summarise(prop = c(prop, 1 - prop),
            lo = c(lower, 1-upper),
            hi = c(upper, 1 - lower),
            width = c('wide', 'narrow')) %>%
  group_by(Species, width) %>%
  summarize(x = as.numeric(Species),
            x = c(x - 0.25, x - 0.25, x - 0.083, x + 0.083, x + 0.25, x + 0.25),
            y = c(0, prop, ifelse(width == 'wide', lo, hi),
                  ifelse(width == 'wide', hi, lo), prop, 0)) %>%
  ggplot(aes(x, y, fill = width)) +
  geom_area(position = 'stack') +
  scale_x_continuous(breaks = 1:3, labels = levels(iris$Species),
                     name = 'Species') +
  ylab('Proportion of measurements') +
  coord_flip() +
  scale_fill_brewer(palette = 'Set1') +
  theme_minimal(base_size = 16)


text:
Q: Play/Pause multiple video with one function I can currently play and pause a video by clicking anywhere in the <video> tag.But unfortunately, when i have added a second video the function works only for the first video only.

 var video = document.getElementById('vid');
    video.addEventListener('click', function() {
                this.paused?this.play():this.pause();
            },
            false);

    video.addEventListener("pause", function() {
        document.getElementById("paused").style.display = "";
    });
    video.addEventListener("play", function() {
        document.getElementById("paused").style.display = "none";
    });

QUESTION HERE

      <video width="1000" height="480" id="vid">
        <source src="video.mp4" type="video/mp4">
          Your browser does not support the video tag.
      </video>

QUESTION HERE

      <video width="1000" height="480" id="vid">
        <source src="video2.mp4" type="video/mp4">
          Your browser does not support the video tag.
      </video>

Any issue with the js code. Kindly advice.

A: it will not work lake that because ,the interpreter will consider just the last id with the same element ,if you use just two videos then you can just add other video id and paused id

QUESTION HERE

  <video width="1000" height="480" id="vid2">
    <source src="video2.mp4" type="video/mp4">
      Your browser does not support the video tag.
  </video>

A: try to use classes instud of ids
for more detaill take a lok to this page
http://flash.flowplayer.org/demos/installation/multiple-players.html


text:
Q: [ISQL]ERROR: Could not SQLConnect: [IM004][unixODBC][Driver Manager]Driver's SQLAllocHandle on SQL_HANDLE_HENV failed I have defined the connection steps below but I get an error. Tried most of the available drivers in /usr/lib64/ but still same error.

/usr/local/etc/freetds.conf

#Server defined by Victor
[THESERVER]
   host = 172.xx.xxx.xx
   port = 1433
   tds version = 7.2

/etc/odbc.ini

# Defined by victor
[CRMCONNECT]
Description = "CRMConnect"
Driver = msSQL
Trace = Yes
Servername = THESERVER
hostname = 172.xx.xxx.xx
Database = "THE_DB"
UserName = "user"
Password = "password"
PROTOCOL = TCPIP

/etc/odbcinst.ini

[msSQL]
Description = msSQL Driver
Driver = /usr/lib64/libodbc.so.2.0.0
fileusage=1
dontdlclose=1

command
[root@darubini ~]# isql -v "CRMCONNECT" "user" "password"

Error message
[IM004][unixODBC][Driver Manager]Driver's SQLAllocHandle on SQL_HANDLE_HENV failed
[ISQL]ERROR: Could not SQLConnect

Below is a snapshot of the available libodbc and libtds drivers . Where would i be going wrong.


text:
Q: Automator service for encrypting or decrypting with openssl Can I create two Automator services that allow me to encrypt or decrypt files? So I would right click a file and click 'Encrypt', the .txt file would be encrypted to a .enc using openssl:
pass=$(osascript -e 'tell app (path to frontmost application as text)
text returned of (display dialog "Enter password:" default answer "")
end')
for f in "$@"; do
    printf %s "$pass" | openssl enc -aes-256-cbc -salt -in "$f" -out "${f%.*}.enc" -pass stdin
done

Can I create a decrypt version that will give me the original .txt file back? Or can I write one service that knows if I want to encrypt or decrypt and run in the way necessary?

A: Select the service template, change the input type to files, add a Run Shell Script action, select pass input as arguments, and paste this script:
pass() {
    osascript - "$1" <<END
    on run args
    tell app (path to frontmost application as text)
    text returned of (display dialog ("Enter password for " & item 1 of args) default answer "")
    end
    end
END
    [ $? != 0 ] && exit 0
}

for f in "$@"; do
    if [[ "$f" == *.enc ]]; then
        pass "$f" | openssl enc -d -aes-256-cbc -pass stdin -in "$f" -out "${f%.enc}"
    else
        pass "$f.enc" | openssl enc -aes-256-cbc -salt -pass stdin -in "$f" -out "$f.enc"
    fi
done
exit 0

It doesn't show specific error messages, you have to run the service again if you enter a wrong password, and there is no way to use the same password for multiple files. It would be easier to just do it from a shell.


text:
Q: Plain RMI console client I'm working on a client-server application implemented with RMI where the client is a simple console application with several methods that the server can remotely invoke. When the client is started, it registers itself with the server and then it should just "hang" there and wait for invocations from the server (each method also prints some information using System.out.println and sometimes needs input from the user). How do I make the client just "hang" and wait?

A: Any JVM that has exported remote objects will 'hang and wait' as long as those objects remain exported.


text:
Q: Shortest distance between two vertices In the graph, we have to find the shortest distance between Newark and Cape May. I have tried using the Dijkstra algorithm but I can't seem to figure out how it would work. According to my working, the distance is coming out to be 175 whereas it should be 85.

A: Djikstra's algorithm gives Newark-Woodbridge-Camden-Cape May with a distance of $165$.
I suspect that your error was to permanently box Atlantic City (on $130$) before you had boxed Camden (on $80$).

A: $85$ does not make sense: from Cape May you could only reach Camden and Atlantic City.


text:
Q: Push files from Azure to GitHub? I have worked on a project in the Azure Machine Learning Studio. I wish to push the files from my storage account linked with the Machine Learning Service account.
I am new to the Azure Portal. I am mostly using the Jupyter Lab instance on Azure Machine Learning service.
How exactly can I push files from the folder I am currently working to my GitHub repository.
I could not find any documentation that will help me in Pushing Files From Azure ML to GitHub.
The following previously asked questions couldn't solve my issue:
push-updates-from-azure-to-github and cant-push-to-github-repository-for-azure-project.


text:
Q: Good .rm/.rmvb to divx or xvid joiner/converter? I used 'Total Video Converter' to convert and join some .rm/.rmvb files and it didn't work properly. Tried another one from Allok and it wasn't very reliable.
Any really good Real Video converters which can also join files?

A: Two excellent video editors and joiners are VirtualDub and Format Factory.
If you don't have the required codec you can find them on free-codecs.com.

A: I like PavTube.

A: I tend to use free stuff. To do this in the past I used ffmpeg to convert the .rm files to AVI, then avidemux to handle the joining. Free Software both.


text:
Q: Eclipse autocomplete appears outside of screen It seems like I'm the only one having this issue, as I have not found any similar questions on the internet.
Eclipse autocomplete does work for me. The box pops up with the correct suggestions, however, it doesn't appear at the line of code, but far away, seemingly at random positions, e.g. at the bottom corner of the screen and 90% of it overextends to outside of the screen, so it's basically useless. What could cause this? I have no idea how to even begin tracing this issue.
Reinstalling doesn't work. Even complete reinstall of Ubuntu 20.04, then installing Eclipse latest (2021-09) didn't work. So I'm wondering how isn't anyone else having this issue?


text:
Q: textbox not accepting pop up window value I have one text-box ,when i click on it popup window gets open ,but value is not inserted in text-box when i select any radio option in popup,where is the problem?
this is textbox

 Work
                <input title="Enter Work You Want to search ." readonly="readonly" id="search_workind" name="search_workind" type="text" size="20"  onclick="javascript:opendrop()">

this calling function
function opendrop()
{
var popy= window.open('search_kind.php','popup_form','width=380 height=300 left=800 top=300');
}

this is search_kind.php
<?php ob_start() ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Search </title>

<form  id="popupform" name="popupform">

Audit and Assurance

<input name="kind" type="radio" id="kind" value="A" onclick="javascript:validepopupform()" />A

<input name="kind" type="radio" id="kind" value="B" onclick="validepopupform()" />B

</form>

<?php ob_flush() ?>

A: You can't set the text box data onclick; in search_kind.php
add a submit button,
 then
<input title="Enter Work You Want to search ." readonly="readonly" id="search_workind" name="search_workind" type="text" size="20"  onclick="javascript:opendrop()"> value=$_POST['kind']


text:
Q: RegEx for replacing alphanumeric chars in Notepad++ I want to upgrade a project from one version to another so, that in need to change thousands of lines with same pattern.
Example:
From this
 $this->returnData['status']

To this
$this->{returnData['status']}

By using following regex i found all the matches but  unable to replace with braces.
->[a-zA-z]{5,15}\['[a-zA-z]{5,15}'\]

I used following to replace
->\{[a-zA-z]{5,15}\['[a-zA-z]{5,15}'\]\}

A: Try using the following find and replace, in regex mode:
Find:    \$this->([A-Za-z]{5,15}\['[A-Za-z]{5,15}'\])
Replace: $this->{$1}

Demo
The regex matches says to:
\$this->             match "$this->"
(                    then match and capture
    [A-Za-z]{5,15}   5-15 letters
    \[               [
    '[A-Za-z]{5,15}' 5-15 letters in single quotes
    \]               ]
 )                   stop capture group

The replacement is just $this-> followed by the first capture group, but now wrapped in curly braces.
If you want to just match the arrow operator, regardless of what precedes it, then just use this pattern, and keep everything else the same:
->([A-Za-z]{5,15}\['[A-Za-z]{5,15}'\])

A: You could also use negated character classes and use \K to forget the match. In the replacement use $0 to insert the full match surrounded by { and }
Match:
->\K[^[\n]+\['[^\n']+']

That will match

*

*-> match ->

*\K Forget what was matched

*[^[\n]+ Match not [ or newline 1+ times or exactly [a-zA-Z]{5,15} instead of [^[\n]+

*\[ Match [

*'[^\n']+' Match from ', 1+ times not ' or newline and then ' or exactly [a-zA-Z]{5,15} instead of [^\n']+

*] Match literally

Regex demo
Replace with:
{$0}

Result:
$this->{returnData['status']}

The exacter version would look like:
->\K[a-zA-Z]{5,15}\['[a-zA-Z]{5,15}']

Regex demo
Note that [a-zA-z] matches more than [a-zA-Z]


text:
Q: How to delay embedding of javascript? I'm embedding a Google trends widget in the sidebar of my site which delays the loading of the whole page. And also, sometimes the script never stops loading which almost cause my browser to crash. The script looks like this:

It simply returns markup that I cannot change and as far as I understand I can't put this script in the footer of my site and then have an html element higher up on the site which is replaced after the script is loaded. How can I delay loding of this script?

A: In this example, I will assume that your script is currently somewhere in the middle of your page like this...

... and also that the script essentially dumps out content to wherever it happens to be placed, which precludes you from moving it to the end of your document.
You could add the script element later like this...

    ...

    ....

So the script that loads the widget script is right at the bottom of your page, so it will only run once your DOM is pretty much ready. It then creates the script tag and adds it to the element you want it in.
UPDATE - based on your feedback using this method, this alternative may help, although it is a bit "gnarly".
Here is an example on JSFiddle. Note that the page is visible even though the widget is actually still loading.
This works by loading a script into a hidden div at the very bottom of the page, and then when it loads, shifting the contents of the hidden div into the visible widget div that is further up in the page flow.

A: The only thing you need to do is to load the script asynchronously:


text:
Q: windows unable to enable .net framework 3.5 I am stuck in a situation where all the solution on internet and stack overflow is not helping me .
I want to enable .net framework 3.5 in my machine for this i followed these steps.

*

*Downloaded it

*installed it

*Control Panel

*Programs and features

*Turn Windows features on and off

*I enabled .net 3.5 from there
It shows a message "Windows need to restart your PC to finish installing the requested changes"

I restarted my system , but it is still not enabled the SQL server installation is still showing an error for .net  framework 3.5.


text:
Q: I have a Windows 11 PC. I also installed Ubuntu for Windows 11 with WSL on my PC. How do I find my /home/username directory in Windows explorer? I have a Windows 11 PC.  I also installed Ubuntu for Windows 11 with WSL on my PC.  How do I find
my /home/username directory in Windows explorer?  I looked in c:\users\user_id\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc, but I cannot find anything there.
And I did look in all the directories.
FYI, user_id is my user name on my PC. I also have set things up so I can view hidden files in Windows Explorer.


text:
Q: Separate names with single quote and commas in php I have a directory where it content are saved in my database both files and sub dir name, now i have tried to select all to sub directories name so i can use it in sql select query but my problem is the selected dir show like this cssjspageimages.
How can i separate each dir name with commas and quote and also not add comma in last name?
Example of how i want it to look like 'css','js','page','images'
<?php
$dirs = array_filter(glob('*'), 'is_dir');

if(!empty($dirs)){
$listdirs = '';
foreach ($dirs as $fileinfo){
        $result = end(explode('/', $fileinfo));
        $listdirs  .= $result;
echo $listdirs;
  }
}
?>

Bonus question
after i have get the sub file and dir like this 'css','js','page','images' i will also add the main root dir example 'root','css','js','page','images'
Here is my code
<?php
$cb = basename(dirname(__FILE__)); //the current base name
$root = "'".$cb."',"
echo $root . $listdirs;
?>

Now what if the root dir is empty? it will still add comma at the end of root and i will get error in sql select.
How can i fix this also

A: Maybe this:
<?php

$dirs = array_filter(glob('*'), 'is_dir');

if (!empty($dirs)) {
  $listdirs = '';

  foreach ($dirs as $fileinfo) {
      $result = end(explode('/', $fileinfo));
      $listdirs .= '\'' . $result . '\','; /* Enclose the $result in quotes (') and append a comma (,) */
  }

  $listdirs = rtrim($listdirs, ','); /* Strip the trailling comma */
  echo $listdirs;
}

EDIT (answering the question edit):
<?php

$cb = basename(dirname(__FILE__)); //the current base name
$root = "'".$cb."'" . ($listdirs ? "," . $listdirs : ""); /* Check if $listdirs contains anything... if so, append a comma (,) and $listdirs... otherwise append nothing. */
echo $root;

A: If the tasks in the original question and the follow-up 'bonus' question can be merged, I would recommend keeping the data returned by glob() as an array instead of converting it to a string right away.
Also note that:

*

*you can add GLOB_ONLYDIR to glob() so you don't need to filter the result
through is_dir().

*glob() already returns the path-free basename so I
don't think you need to go through foreach and explode the result
looking for the directory names.

If that all sounds workable, this seems to do what you want:
$listdirs = "";
$dirs = glob('*', GLOB_ONLYDIR );
$cb = basename(dirname(__FILE__));

if( $cb )
    array_unshift( $dirs, $cb );

if( count( $dirs ) )
    $listdirs = "'" . implode( $dirs, "','" ) . "'";

A: As John Conde said, you were really close :)
$listdirs .= "'". $result ."',";

Don't forget to remove the last characters of this string ( last comma), after the loop,  :
$listdirs = substr($listdirs,0,-1);

I think your "echo $listdirs;" should also be outside the loop.


text:
Q: Clipboard TTS Custom Keyboard Doesn't Work I want ubuntu to read aloud something I put on clipboard. I found a solution for that, which is this:
xsel --clipboard | festival --tts

When I try it on terminal, this code works. But when I try to put this command to a shortcut instead, it doesn't work. Nevertheles, if I change the command in shortcuts with 'gedit' for example, it opens gedit. So, the shortcut is also working. What can be the problem over here?

A: Keyboard shortcut commands do not get interpreted by a shell, so you can't normally use shell features like pipes in them directly.
Change your shortcut command to explicitly run in a Bash shell:
bash -c 'xsel --clipboard | festival --tts'


text:
Q: Two level deep copy in Java In Java, it's easy to deeply clone an object with Object.clone() and also to shallow-clone (let's call it level 1).
How do you go about doing a two-level deep copy, that is, copying all primitives, but also creating (shallow) copies of all Object members ?
Let's say you copy a phone book with a list of number entries . A shallow copy would just
clone = original.getLNumberlist();

a deeper copy would do a
clone = new ArrayList<>(original.getNumberlist());

there are many questions about deep and shallow cloning, but I could not find any Java question about this two-level cloning, let alone its implementation


text:
Q: $_SERVER['HTTP_USER_AGENT'] extract mail client Currently I'm trying to create a mailing system with statistics. I send a mail with an image which links to a file where I can read the $_SERVER['HTTP_USER_AGENT']. When I open the mail in thunderbird this is my user-agent:
Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20130328 Thunderbird/17.0.5
I'd like to get the name and the version of the mailclient.
I tried to use
stristr($_SERVER['HTTP_USER_AGENT'],'thunderbird') but there are alot of email clients and if I make an if else structure with all of the clients it will get very big and I will always miss some email clients. how can I extract it the easy way and get a result like THIS?

A: I think you are looking for http://php.net/get_browser. Note that it requires a 3rd party text file that holds information regarding browsers/clients which can be parsed by get_browser()
You can obtain the latest php_browscap.ini at http://tempdownloads.browserscap.com/
Edit: I checked to be sure, but the files contains Thunderbird too.


text:
Q: Are all lengths multiples of the Planck length? If the Planck length is the smallest unit of length that has any physical meaning then is it true to think that all the lengths are multiple of the Planck length?

A: Yes, all lengths are multiples of the Planck length. All lengths are also multiples of the meter and the mile and the parsec. The Planck length is just another unit length and all lengths may be expressed as some multiple of any unit length.
The Planck scale is expected to be the scale at which quantum gravity is expected to become important. That does not mean that the universe is expected to be formed of Planck length pixels.


text:
Q: Directory issue when connecting VS Code to remote server via ftp-simple I've set up ftp-simple to connect to my remote server. Files show up fine, however directories appear with [DIR] next to them which, when clicked, disappear with a red line through it, as per image below (template-parts was the directory which I had just clicked on).
As mentioned, files are fine - they load perfectly, but it's the directories which have the issue.
Nothing shows up in the output log when this happens and I can't seem to find anything about this issue elsewhere.

A: The only solution I have found is this.
In vscode, go File->Preferences->Settings.
Then at the search area type this -> ftp-simple.remote-workspace-load-all <- and set it to false.
What this does is, when you first load a directory (the default path that has been set in vsc config), vsc is going to load only the content of this specific directory.
Then, only if you click another directory ([DIR]), it will start to download the content of this directory.


text:
Q: Pandas find values present in at least two groups I have a multiindex dataframe like this:
                            Distance
Company Driver Document_id
Salt    Fred   1               592.0
               2               550.0
        John   3               961.0
               4               346.0
Bricks  James  10              244.0
               20              303.0
               30              811.0
        Fred   40              449.0
        James  501             265.0
Sand    Donald 15              378.0
               800             359.0

How can I slice that df to see only drivers, who worked for different companies? So the result should be like this:
                            Distance
Company Driver Document_id
Salt    Fred   1               592.0
               2               550.0
Bricks  Fred   40              449.0

UPD: My original dataframe is 400k long, so I can't just slice it by index. I'm trying to find general solution to solve problems like these.

A: To get the number of unique companies a person has worked for, use groupby and unique:
v = (df.index.get_level_values(0)
       .to_series()
       .groupby(df.index.get_level_values(1))
       .nunique())
# Alternative involving resetting the index, may not be as efficient.
# v = df.reset_index().groupby('Driver').Company.nunique()
v

Driver
Donald    1
Fred      2
James     1
John      1
Name: Company, dtype: int64

Now, you can run a query:
names = v[v.gt(1)].index.tolist()
df.query("Driver in @names")

                            Distance
Company Driver Document_id
Salt    Fred   1               592.0
               2               550.0
Bricks  Fred   40              449.0


text:
Q: Express stops listening when using Puppeteer I'm currently writing a simple API which is performing actions via Puppeteer, however when trying to execute my script so I can access the API; my Express app seems to stop listening once Puppeteer opens?
Here's my script:
const Apify = require('apify');
const puppeteer = require('puppeteer-extra');
const RecaptchaPlugin = require('puppeteer-extra-plugin-recaptcha');

const express = require('express');
const app = express();

let page;
let browser;
let device_imei;

puppeteer.use(
    RecaptchaPlugin({
        provider: {
            id: '2captcha',
            token: '2captcha-token'
        },
        visualFeedback: true
    })
);

const handle_response = async (response) => {
    const url = response.url();
    try {
        const req = response.request();
        const orig = req.url();
        let status;
        let text;
        if(response.status) {
            status = response.status();
        }
        if(
            status
            && !(status > 299 && status < 400)
            && !(status === 204)
            && (req.resourceType() === 'xhr')
            && (orig.startsWith('https://www.website.com/apis'))
        ) {
            text = await response.text();
            if(text.includes('Access Denied')) {
                console.log('Access Denied, we need a new IP');
                return;
            }
            const json = JSON.parse(text);
            if(json['orderFlowResponseDO']['validationErrors'] !== undefined) {
                console.log({orig, status, text: json});
            }
        }
    } catch (err) {
        console.error(`Failed getting data from: ${url}`);
        console.error(err);
    }
};

const launch_browser = async () => {
    Apify.main(async () => {
        browser = false;
        browser = await Apify.launchPuppeteer({
            args: [
                '--no-sandbox',
                '--proxy-server=' + await get_proxy()
            ],
            headless: true,
            stealth: true,
            stealthOptions: {
                hideWebDriver: true
            }
        });
        page = await browser.newPage();
        page.on('response', handle_response);
        browser.on( 'disconnected', launch_browser);
    });
};

const get_proxy = async () =>
{
    return '127.0.0.1:80'; //example
};

(async () => {
    await launch_browser();
})();

app.get('/submit/:imei', async function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({
        'test': 'testvalue'
    }));
});

app.listen(3000);

When I run node index.js I get the following output:
curtis@Curtiss-MacBook-Pro-2 untitled3 % node index.js
INFO  System info {"apifyVersion":"0.21.0","apifyClientVersion":"0.6.0","osType":"Darwin","nodeVersion":"v13.0.1"}
WARN  Neither APIFY_LOCAL_STORAGE_DIR nor APIFY_TOKEN environment variable is set, defaulting to APIFY_LOCAL_STORAGE_DIR="/Users/curtis/Downloads/untitled3/apify_storage"
INFO  Launching Puppeteer {"args":["--no-sandbox","--proxy-server=127.0.0.1:80","--no-sandbox","--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"],"headless":true,"stealth":true,"defaultViewport":{"width":1366,"height":768}}
curtis@Curtiss-MacBook-Pro-2 untitled3 %

A: Just remove the Apify.main() function. For details, see How to use Apify on Google Cloud Functions


text:
Q: PHP Like System / 'Most Liked' (Need for logic) I'am trying create a basic comment system, I was success but I have a problem right now.
I can't list "most liked" comments and I don't have an idea about how can I.
My votes database showing like that:
voteid  | value     | entryid   | userid
25      | like      | 257       | 17
24      | like      | 257       | 17
23      | unlike    | 257       | 18

I create a new like with this code:
    $vote = $connect->prepare("INSERT INTO votes (entryid, userid, value) VALUES (:entryid, :userid, :value)");
    $vote->bindParam(':entryid', $entryid);
    $vote->bindParam(':userid', $userid);
    $vote->bindParam(':value', $value);
    $vote->execute();

And my question.
What's my need SQL Query?
I've tried like this:
  $bestliked = $connect->prepare("SELECT * FROM votes");
  $best = $bestliked->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN, 2);

But I can't list the array which have most subarray. It only seems that;
[1] => Array
    (
        [0] => 8
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
        [5] => 6
        [6] => 7
        [7] => 9
        [8] => 10
        [9] => 11
        [10] => 12
        [11] => 13
        [12] => 14
        [13] => 15
    )

[2] => Array
    (
        [0] => 16
    )

[3] => Array
    (
        [0] => 17
    )

Thanks All!

A: You could try to sum the group count and sort it descending:
  Select *,count(*) as sum group by entryid where value='like' order by sum desc


text:
Q: Getting information about "What are you doing" activity from facebook api I am trying to get information from using facebook api about a status update like
"Narendra Rajput is watching American Hustle".
This was created by using "Say what are you doing" feature.
I tried getting information about it using graph api and FQL using stream table. It does give me postid and permalink and all other fields are empty or null.
I tried using graph api too but again all fields are empty except postid and permalink.
In FQL I tried this query to get the information about posts
SELECT post_id, actor_id, target_id, attribution, attachment, app_data, action_links,  impressions, description_tags ,description,tagged_ids, message,message_tags, attachment, type, permalink
FROM stream
WHERE source_id = me()
AND is_hidden != "true"
AND (type = 46 OR type = 60 OR type = 65 OR type = 80 OR type = 128 OR type = 247 OR type = 285 OR type = 373)
LIMIT 100

I tried all possible fields in stream table.
I want the text "Narendra Rajput is watching American Hustle" from this status update as it appears in the news feed.
How can I get this information. Is it possible with FB api.

A: Currently this information is not available via the FQL, it's only available via the Graph API.
You will need the user_actions.video and friends_actions.video permissions for accessing it.
Once you have the access to these endpoints you, can fetch it via-
https://graph.facebook.com/me/video.watches?access_token= # valid access token
Replace the me with your friends Facebook ID to fetch data for his/her video.watches.