text:
Q: Placing Rectangle with earliest startdate on first spot (Gantt Chart) In my program i have 4 "workPackages" with different start and enddates, this looks like this:
WorkPackage[] workpackages = new WorkPackage[4];

workpackages[0] = new WorkPackage("Package 1", new DateTime(2021, 1, 7), new DateTime(2021, 2, 2));
workpackages[1] = new WorkPackage("Package 2", new DateTime(2021, 1, 1), new DateTime(2021, 4, 1));
workpackages[2] = new WorkPackage("Package 3", new DateTime(2022, 1, 3), new DateTime(2022, 8, 1));
workpackages[3] = new WorkPackage("Package 4", new DateTime(2023, 1, 8), new DateTime(2024, 12, 1));

Then I created rectangles whose length depends on the time span between the date times from the packages. This looks like this:
for (int i = 0; i < workpackages.Length; i++)
        {
            timeSpan[i] = (workpackages[i].enddate - workpackages[i].startdate).TotalDays;

            Rectangle rectangle = new Rectangle
            {
                Fill = brush,
                StrokeThickness = strokethickness,
                Stroke = Brushes.Black,
                Width = timeSpan[i],
                Height = rectangleHeight / howmanyrect - distancebetweenrectangles
            };
            MyRectangle[i] = rectangle;

            Canvas.SetLeft(rectangle, rectangle.Width / 2.0 - rectangle.Width / 2.0);
            Canvas.SetTop(rectangle, i * (rectangleHeight / howmanyrect));

            myCanvas.Children.Add(rectangle);
            Content = myCanvas;
        }

And in my WPF window it looke like this:
.
If you know what a Gantt Chart is then it should be familiar to you what I'm trying to do. Now I want the rectangle with the earliest startDate to be on the first spot and then the others in order according to their start- and endDate. For finding the earliest date I did this for loop:
for (int i = 1; i < workpackages.Length; i++)
        {
            if (workpackages[i].startdate < earliestdate)
            {
                earliestdate = workpackages[i].startdate;
            }
        }

So how do I let the program know that the rectangle with the earliest date must be placed on the first spot?

A: First, you got to cut out your centering method and then you use this for finding earliest date:
DateTime earliestdate = workpackages[0].startdate;
        for (int i = 1; i < workpackages.Length; i++)
        {
            if (workpackages[i].startdate < earliestdate)
            {
                earliestdate = workpackages[i].startdate;
            }
        }
        return earliestdate;

and this for finding the latest date:
DateTime latestdate = workpackages[0].enddate;
        for (int i = 1; i < workpackages.Length; i++)
        {
            if (workpackages[i].enddate > latestdate)
            {
                latestdate = workpackages[i].enddate;
            }
        }
        return latestdate;

Then you just need to get the positioning and stuff, for that you use this:
double totalDaysDiff = (latestdate - earliestdate).TotalDays;
        double totalDistanceDiff = data.latestDatePosition - data.earliestDatePosition;

        double dayStep = totalDistanceDiff / totalDaysDiff;

        double[] width = new double[workpackages.Length];

        for (int i = 0; i < workpackages.Length; i++)
        {
            double daysFromStart = (workpackages[i].startdate - earliestdate).TotalDays;
            double rectStartPosition = data.earliestDatePosition + daysFromStart * dayStep;

            double daysFromEnd = (workpackages[i].enddate - earliestdate).TotalDays;
            double rectEndPosition = data.earliestDatePosition + daysFromEnd * dayStep;

            width[i] = rectEndPosition - rectStartPosition;

            double rectangleOffset = 14;
            Rectangle rectangle = new Rectangle
            {
                Fill = Brushes.Green,
                StrokeThickness = rectValues.strokethickness,
                Stroke = Brushes.Black,
                Width = width[i] + rectangleOffset,
                Height = rectValues.rectangleHeight / rectValues.heightDevider - rectValues.distancebetweenrectangles
            };

And that's how you can place your rectangles like it's a Gantt Chart.


text:
Q: How to change encryption for SSHD in Fedora Server 29? CRYPTO_POLICY field is empty and I do not know where to start.
I only read about LEGACY, DEFAULT and FUTURE options (what is not clear for me absolutely how it is relates to SSHD).
# Ciphers and keying
#RekeyLimit default none

# System-wide Crypto policy:
# This system is following system-wide crypto policy. The changes to
# Ciphers, MACs, KexAlgoritms and GSSAPIKexAlgorithsm will not have any
# effect here. They will be overridden by command-line options passed on
# the server start up.
# To opt out, uncomment a line with redefinition of  CRYPTO_POLICY=
# variable in  /etc/sysconfig/sshd  to overwrite the policy.
# For more information, see manual page for update-crypto-policies(8).

The main idea is to change default encryption to fast algorithm (or disable it). It is local machine for tests, so only performance is matter.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VPS exceedingly slow, /proc/meminfo looks suspicious A VPS I'm using has become unbearably slow.  Over ssh, things like changing directories or opening small files take 5+ seconds to complete.  The website hosted on it, however, performs with reasonable latency as long as it doesn't read too more than a couple KB from the DB.
Below is cat /proc/meminfo.  I'm not a sys admin, but this looks suspicious to me.  Especially Active/Inactive being 0.  Does this mean it's not buffering any disk reads?  So, does this (partially?) explain the performance problems?  Is there a straightforward way to fix this (I have root access, but no access to the hosting provider's control panel).
EDIT:  CPU utilization is about zero most of the time and doesn't seem to affect the issues I'm having.
thanks.
MemTotal:      4190208 kB
MemFree:       3970416 kB
Buffers:             0 kB
Cached:              0 kB
SwapCached:          0 kB
Active:              0 kB
Inactive:            0 kB
HighTotal:           0 kB
HighFree:            0 kB
LowTotal:      4190208 kB
LowFree:       3970416 kB
SwapTotal:           0 kB
SwapFree:            0 kB
Dirty:               0 kB
Writeback:           0 kB
AnonPages:           0 kB
Mapped:         219792 kB
Slab:                0 kB
PageTables:          0 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:         0 kB
Committed_AS:  1243020 kB
VmallocTotal:        0 kB
VmallocUsed:         0 kB
VmallocChunk:        0 kB
HugePages_Total:     0
HugePages_Free:      0
HugePages_Rsvd:      0
Hugepagesize:     2048 kB

A: Few checks to do when a server is slow:

*

*Memory
free -tom (will show available & used memory)
OR
do what you've done above :)

*CPU usage
top
This will show you some key information along the top. Look for these set of numbers along the top:
load average: 0.00, 0.00, 0.00
The following article has a good explanation of how to understand these numbers:
http://blog.scoutapp.com/articles/2009/07/31/understanding-load-averages

*Get a list of process and see whether there are multiple threads for a service (ex: httpd or the webserver)
ps awwwwfux | less -S
The above command is excellent to view all processes in a tree format

*Depending on the service which seems to be acting up, try to read through those logs for clues as to what may be happening. Remember, logs can usually be found under /var/log/


text:
Q: Elastic Beanstalk App in Private VPC without NAT Is it possible to deploy an EB app in a custom private VPC, without using a NAT Gateway? I want to use AWS API Gateway as the public entry point for the app while keeping the services private. After setting everything up, my environment keeps failing with:
The EC2 instances failed to communicate with AWS Elastic Beanstalk, either because of configuration problems with the VPC or a failed EC2 instance. Check your VPC configuration and try launching the environment again.

The VPC consists of:

*

*Two private subnets for the EC2 instances

*Two private subnets for the load balancer

The template I used is vpc-private.yaml from the EB samples repo.
The EB app is a multi-container docker application with a Nginx reverse proxy and a Flask app running with uWSGI (similar to this configuration). I'm using an internal Network Load Balancer and the instances are not assigned public IP addresses. The Docker images are hosted in AWS ECR.
A common answer in forums seems to be to have one public subnet with NAT to allow internet access. AWS documentation indicates that using a private/private configuration is possible though by using VPC Endpoints, as long as the app does not require an internet connection.
The endpoints I have configured are:
com.amazonaws.us-east-1.s3
com.amazonaws.us-east-1.elasticbeanstalk
com.amazonaws.us-east-1.ecs-telemetry
com.amazonaws.us-east-1.ecs-agent
com.amazonaws.us-east-1.ecs
com.amazonaws.us-east-1.ecr.dkr
com.amazonaws.us-east-1.ecr.api
com.amazonaws.us-east-1.elasticbeanstalk-health

It looks like VPC endpoints for Beanstalk are fairly new and I could not find any other resource explaining how to do this...
Thanks!
EDIT (solved)
A few setup details I forgot to mention:

*

*DNS resolution and DNS hostnames are enabled in the VPC

*Private DNS is enabled for every endpoint

*Made sure that the endpoint's security group allowed the instance's VPC as inbound traffic

Thanks to @Marcin suggestion, I was able to log into the instances via Session Manager (just add ssm, ec2messages and ssmmessages endpoints). After checking the logs, I noticed the following error:
2020-08-01 15:15:56,801 [WARNING] Timeout of 60 seconds breached
2020-08-01 15:15:56,801 [ERROR] Client-side timeout
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/cfnbootstrap/util.py", line 162, in _retry
    return f(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/cfnbootstrap/util.py", line 231, in _timeout
    raise TimeoutError("Execution did not succeed after %s seconds" % duration)
TimeoutError

I found other people had the same issue, and it was caused by cfn-signal failing to execute. I was able to solve this by adding the cloudformation endpoint. On the following deployment I now noticed a new sqs connection error which was solved by adding the sqs endpoint.
After adding the mentioned endpoints to the VPC, the deployment succeeded. Either way, I'm not sure why these endpoints were necessary, and why it was not mentioned in the AWS documentation in the first place.

A: The template you linked does not have NAT, even though the description says it has. AWS mistake.
The template creates two private subnets, fully cut off from the internet and any other services, such as EB or ECR.
The important thing to note, and the template fails to showcase it, is to enable private DNS for your endpoints.
For that to work you must ensure that EnableDnsHostnames and EnableDnsSupport are enabled for the VPC. The template from the docs does not enable them.
These could possibly explain why your VPC interface endpoints don't work.


text:
Q: How to use Netcat to check whether postgresql docker container is up I want to see if docker container with PostgreSQL is ready using Netcat utility.
My entrypoint.sh script seems to be unable to spot the DB up and running.
When I login into docker and run NC in verbose mode I get
DNS fwd/rev mismatch: db != telegram_messages_db_1.telegram_messages_default
What am I doing wrong?
My setup
entrypoint.sh
echo "Waiting for postgres..."

while ! nc -z db 5432; do
  sleep 0.1
done

echo "PostgreSQL started"

docker-compose.yaml
version: '3.7'

services:

  messages:
    build:
      context: .
      dockerfile: Dockerfile
    entrypoint: ['/usr/src/app/entrypoint.sh']  # new
    volumes:
      - .:/usr/src/app
    ports:
      - 5001:5000
    environment:
      .....
    depends_on:
      - db

  db:
    build:
      context: ./backend/db
      dockerfile: Dockerfile
    expose:
      - 5432
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres

docker-compose output
Attaching to telegram_messages_db_1, telegram_messages_messages_1
messages_1  | Waiting for postgres...
db_1        |
db_1        | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1        |
db_1        | 2020-03-29 23:55:22.103 UTC [1] LOG:  starting PostgreSQL 12.2 on x86_64-pc-linux-musl, compiled by gcc (Alpine 9.2.0) 9.2.0, 64-bit
db_1        | 2020-03-29 23:55:22.103 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1        | 2020-03-29 23:55:22.104 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1        | 2020-03-29 23:55:22.115 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1        | 2020-03-29 23:55:22.170 UTC [20] LOG:  database system was shut down at 2020-03-29 23:46:56 UTC
db_1        | 2020-03-29 23:55:22.190 UTC [1] LOG:  database system is ready to accept connections

Also...
If I run nc -z -v telegram_messages_db_1.telegram_messages_default 5432
I do get a nice response:
telegram_messages_db_1.telegram_messages_default [172.19.0.2] 5432 (postgresql) open

A: Removing all containers, rebooting and building from scratch solved the issue.
I will leave it here for posterity.


text:
Q: Internal Sever error when trying to update query in PHP Am actually building a login and register system but having these internal error in the email activation part, when am trying to change the active table to 1, if users email and email_code matches.
the activate.php code :
<?php

} else if (isset($_GET['email'], $_GET['activation']) === true) {

    $email      = trim($_GET['email']);
    $email_code = trim($_GET['activation']);

    if (email_exists($email) == false) {
        $errors[] = 'Ooops, We counldn\'t find that email address';

    } else if (activate($email, $email_code) == false) {
        $errors[] = 'Ooops, We had problem activating your account';

    }

    if (empty($errors) == false){
        echo output_errors($errors) . '

';
    } else {
        header('Location : activate.php?success');
        exit();
    }

} else {

    header('Location: index.php');
    exit();
}

?>

The activate($email, $email_code) function :
function activate($email, $email_code) {
    global $connection;

    $email      = $email;
    $email_code = $email_code;
    $active     = 0;
    $new_update_active = 1;

    $stmt       = $connection -> prepare('SELECT id FROM users WHERE email = ? AND email_code = ? AND active = ?');

    $stmt -> bind_param('ssi', $email, $email_code, $active);
    $stmt -> execute();
    $stmt -> store_result();
    $stmt -> fetch();

    if ($stmt -> num_rows() == 1) {

        $update_active = $connection -> prepare('UPDATE users SET active = ? WHERE email = ?');
        $update_active -> bind_param('is', $new_update_active, $email);
        return true;

    } else {
        return false;
    }

}

The error:
The error image!!
The code is seems correct and am only having these intenal serval when it comes to the part that the email and email_code matches and to change the active table to 1 in the database.

A: I later spot the error and i just change the
header('Location : activate.php?success');

to
header('Location: activate.php?success');


text:
Q: Change Character Value Into Negative Number Using R I have the following dataframe. All the columns are character columns, but except the 1st column, rest of the columns contain numeric values:
df <- data.frame(col1=c('', 'assets', 'loss', 'liability'),
                 col2=c("", "5,000", "(1,400)", "300"),
                 col3=c("", "4,500", "(1,100)", "500"))

df

col1       col2      col3
<chr>      <chr>    <chr>

assets     5,000    4,500
loss      (1,400)  (1,100)
liability   300      500

The task is -- if a value is within () [for example, loss value], I need to make that value as a negative number.
I am trying the following script:
clean_columns <- function(dataframe){

  dataframe_new <- copy(dataframe)

  for (idx in 2:length(names(dataframe))) {

      # Check if text contains -- ( )
      if (grepl(is.na(dataframe_new[, idx]), "(", fixed = TRUE)) {

      # Remove characters -- () , -- and multiply -1
      dataframe_new[, idx] <- gsub("[(,)]", "", dataframe_new[, idx]) %>%
        as.numeric(dataframe_new[, idx])*(-1)

      } else
      # Remove characters -- ,
      dataframe_new[, idx] <- gsub("[,]", "", dataframe_new[, idx]) %>%
        as.numeric(dataframe_new[, idx])
}
  return(dataframe_new)
}

The function removes the characters correctly, but make the loss value NA.
clean_columns(df)

col1       col2     col3
<chr>      <dbl>    <dbl>
            NA       NA
assets     5000     4500
loss        NA       NA
liability  300      500

Desired Output
col1       col2     col3
<chr>      <dbl>    <dbl>
            NA       NA
assets     5000     4500
loss      -1400    -1100
liability   300      500

Any suggestions would be appreciated. Thanks!

A: We loop across the columns having at least some digits, remove the ), replace the ( with - and parse it with parse_number
library(dplyr)
library(stringr)
 df %>%
  mutate(across(-1,
   ~ readr::parse_number(str_replace(str_remove(.x, "\\)"), fixed("("), "-") )))

-output
       col1  col2  col3
1              NA    NA
2    assets  5000  4500
3      loss -1400 -1100
4 liability   300   500

Or instead of removing the (, we can detect the ( to multiply by -1
df %>%
   mutate(across(-1, ~ c(1, -1)[1 + str_detect(.x, fixed("("))] *
         readr::parse_number(.x) ))

A: Here is one without my favorite function parse_number():
library(dplyr)
library(stringr)

df %>%
  mutate(across(-col1, ~str_replace_all(., "[[:punct:]]", ""))) %>%
  type.convert(as.is = TRUE) %>%
  mutate(across(-col1, ~ifelse(col1 == "loss", .*-1, .))) %>%
  as_tibble()

  col1         col2  col3
  <chr>       <dbl> <dbl>
1 ""             NA    NA
2 "assets"     5000  4500
3 "loss"      -1400 -1100
4 "liability"   300   500


text:
Q: Include Fonts in WPF Application Ok so everything I've been trying is not loading my fonts correctly, I've added them to the .csproj file which was done by switching copy to output directory so this is what it looks like
<Resource Include="Resources\Fonts\SourceSansPro-Black.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-BlackItalic.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-Bold.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-BoldItalic.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-ExtraLight.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-ExtraLightItalic.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-Italic.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-Light.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-LightItalic.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-Regular.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-SemiBold.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
    <Resource Include="Resources\Fonts\SourceSansPro-SemiBoldItalic.ttf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>

Then I've added the references inside my ui-dictionary which looks like
    <FontFamily x:Key="Black" >pack://application:,,,/Resources/Fonts/#SourceSansPro-Black</FontFamily>
    <FontFamily x:Key="BlackItalic" >pack://application:,,,/Resources/Fonts/#SourceSansPro-BlackItalic</FontFamily>
    <FontFamily x:Key="Bold" >pack://application:,,,/Resources/Fonts/#SourceSansPro-Bold</FontFamily>
    <FontFamily x:Key="BoldItalic" >pack://application:,,,/Resources/Fonts/#SourceSansPro-BoldItalic</FontFamily>
    <FontFamily x:Key="ExtraLight" >pack://application:,,,/Resources/Fonts/#SourceSansPro-ExtraLight</FontFamily>
    <FontFamily x:Key="ExtraLightItalic" >pack://application:,,,/Resources/Fonts/#SourceSansPro-ExtraLightItalic</FontFamily>
    <FontFamily x:Key="Italic" >pack://application:,,,/Resources/Fonts/#SourceSansPro-Italic</FontFamily>
    <FontFamily x:Key="Light" >pack://application:,,,/Resources/Fonts/SourceSansPro-Light.ttf</FontFamily>
    <FontFamily x:Key="LightItalic" >pack://application:,,,/Resources/Fonts/#SourceSansPro-LightItalic</FontFamily>
    <FontFamily x:Key="Regular" >pack://application:,,,/Resources/Fonts/#SourceSansPro-Regular</FontFamily>
    <FontFamily x:Key="SemiBold" >pack://application:,,,/Resources/Fonts/#SourceSansPro-SemiBold</FontFamily>
    <FontFamily x:Key="SemiBoldItalic" >pack://application:,,,/Resources/Fonts/#SourceSansPro-SemiBoldItalic</FontFamily>

But everytime I've tried to use it fonts do not load. So I've tried different methods in the uri
<!-- First Method -->
    <FontFamily x:Key="Light" >pack://application:,,,/Resources/Fonts/SourceSansPro-Light.ttf#SourceSansPro-Light</FontFamily>

<!-- Second Method -->
<FontFamily x:Key="Light" >pack://application:,,,/Resources/Fonts/#SourceSansPro-Light</FontFamily>

<!-- Third Method -->
<FontFamily x:Key="Light" >/Resources/Fonts/#SourceSansPro-Light</FontFamily>

<!-- Third Method -->
<FontFamily x:Key="Light" >/Resources/Fonts/#SourceSansPro-Light</FontFamily>

<!-- Fourth Method -->
<FontFamily x:Key="Light" >/Resources/Fonts/SourceSansPro-Light.ttf#SourceSansPro-Light</FontFamily>

Am I missing something here?

A: Embedding fonts in WPF as resources, is pretty simple. However, there are few gotchas that you need to be aware of.
Here is a step by step process that I followed in a sample app:
Added Resources/Fonts folders to my project
Dragged the Source Sans Pro .ttf files into the Fonts folder
Visual Studio automatically set their Build Action to Resource
Note: You don't need to copy them to the output directory if they are being used as resources
Created a Fonts.xaml ResourceDictionary with the following code
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <FontFamily x:Key="Regular">pack://application:,,,/WpfApp4;component/Resources/Fonts/#Source Sans Pro</FontFamily>
    <FontFamily x:Key="Black">pack://application:,,,/WpfApp4;component/Resources/Fonts/#Source Sans Pro Black</FontFamily>

</ResourceDictionary>

Then I merged in the Fonts.xaml resources into my App.xaml file.
<Application x:Class="WpfApp4.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Fonts.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

The first problem you have is an incorrect Pack Uri format.
pack://application:,,,/YourAppNamespace;component/Resources/Fonts/#Font Family Name
The second problem you have is an incorrect font family name
The font family name is usually not the same as the .ttf file name!
To get the right family name, I highly recommend using the dp4 Font Viewer.
I hope this helps!


text:
Q: A continuous function that is negative at some point will be negative around that point Proposition:

$f: [0, \infty) \to \mathbb{R}$ be a continuous function and
  suppose that $f(0) < 0$, then $\exists \alpha > 0, \text{s.t. }
 f(t)<0, \forall t \in [0, \alpha] .$

Sketch:

Proof attempt:

*

*Since $f$ is continuous, therefore for all $t, t^\prime \in
   \mathbb{R}_{\geq 0}$, $\forall \epsilon >0, \exists \delta >0$ such
that $|t^\prime - t| < \delta \implies |f(t^\prime) - f(t)| <
   \epsilon$.
Then take $t^\prime = 0$, we have for all $t$, $|t| < \delta \implies
   |f(0) - f(t)| < \epsilon$.
Take $\delta = \alpha$, then $|f(0) - f(t)| < \epsilon, \forall t \in
   (-\alpha, \alpha)$.
Since $|f(0) - f(t)| < \epsilon \Longleftrightarrow  -\epsilon < f(0)
   - f(t) < \epsilon$, therefore $f(t) < f(0) + \epsilon$.
Thus for any $0< \epsilon < |f(0)|$, $f(t) < 0$ for all $t \in (0,
   \alpha)$.
There are couple problems in the proof:

*

*how do I argue  that $f(t) <0$ for a closed interval as in the proposition?

*how do I go from $|t| < \alpha \Longleftrightarrow -\alpha < t < \alpha$ to $t \in (0, \alpha)$?
Please let me know if there are any other problems in the proof, feel free to post yours if you can construct a more concise one.

A: Your two questions can be simply addressed by just observing that you can shrink the range that $t$ can be in however you want.  For instance, if you know that $f(t)<0$ for all $t$ in $(-\alpha,\alpha)$, you also know that $f(t)<0$ for all $t\in[0,\alpha)$, since any $t\in[0,\alpha)$ is also in $(-\alpha,\alpha)$.  (Actually, note that you can only use values of $t$ which are in the domain of the function in the first place, so you actually only know that $f(t)<0$ for $t\in [0,\alpha)$, since for $t<0$ it is undefined.)  You can also use this idea to get a closed interval: can you think of a closed interval $[0,\beta]$ that would be contained in $[0,\alpha)$?  The answer is hidden below.

 Just take any $\beta$ such that $0<\beta<\alpha$, and then $[0,\beta]$ is a subset of $[0,\alpha)$.  So whenever $t\in[0,\beta]$, $t\in [0,\alpha)$ as well, so $f(t)<0$.  If you want a specific value of $\beta$, you could take $\beta=\alpha/2$.

There are some other issues in your proof.  First, your definition of continuity is incorrect.  Your definition would be true of any function at all, since you could just choose $\delta$ to be less than $|t-t'|$ so that the implication $|t^\prime - t| < \delta \implies |f(t^\prime) - f(t)| < \epsilon$ is vacuously true.  The "for all $t$" in the statement needs to come after the "there exists $\delta$" so that $\delta$ can't depend on $t$.
Also, beware that your choice of $\delta$ (and therefore $\alpha$) depends on $\epsilon$.  So you shouldn't really be talking about $\delta$ until you've chosen the $\epsilon$ you're going to use, as you do when you say $0<\epsilon<|f(0)|$.  Or, if you want to leave the choice of $\epsilon$ until the end, you should state explicitly that you are using an $\epsilon$ that will be chosen later.

A: Since the function is only defined for nonnegative values of $t$, continuity at zero in this context is: for every $\epsilon > 0$, there exists $\delta > 0$ such that $| f(0) - f(t) | < \epsilon$ whenever $t \in [0, \delta)$ (your usage of continuity talks about values of $t < 0$, which doesn't make sense in this context).
Now, let $\epsilon = |f(0)|$. This gives you a corresponding $\delta > 0$ such that $f$ is negative on $[0, \delta)$. Now, take $\alpha = \delta / 2$ to get that $f$ is negative on $[0, \alpha]$, since $[0,\alpha]\subset [0,\delta)$.

A: *

*you already spoiled $\alpha$, so I define $\beta = \frac{1}{2}\alpha$
It is clear, that $[ -\beta, \beta ] \subset (-\alpha, \alpha)$.
Hence if some statement is true for $ x \in (-\alpha, \alpha)$ it is true for $ x \in [-\beta, \beta ]$ as well.

*same reasoning: $[0, \beta] \subset [-\beta, \beta]$

A: With $\epsilon=-\frac {f (0)}{2} $
the continuity at $0$ insures that
$$\exists \eta>0\;  : \forall x\in (0,\eta) $$
$$f (0)+\frac{f (0)}{2}<f (x)<f (0)-\frac {f (0)}{2}<0$$


text:
Q: Is it possible to get Slack username as an entity in Watson assistant? I am thinking about a situation that we use Watson Assistant to pull data from a database using the username of Slack account initiating conversation with it. Is it possible? (Because the user is already authenticated using Slack, we do not need to deal with authentication anymore)
The Slack workspace is connected to Watson using the Bots.


text:
Q: Application to open default browser on scanning of QR code? We have a user scanning a QR code which we store a URL. USB QR code scanners are like keyboards in they type in whatever is stored in the QR code.
We need to find something that will open a browser when a scan is made so that the URL in the QR code, can be typed into the browser URL bar.
Any ideas?


text:
Q: $add operation returns null value I have collection with document structure :
 {
  'year' : 2014,
  'month' : 1
 }

I am executing the following operation :
db.collname.aggregate(
                        [
                           {
                             $project : {
                                    'year100' : {$multiply : ["$year" , 100]},
                                    'result' : { '$add' : ['$year100', '$month'] }
                                        }
                           }
                        ]
                      );

I get the following result :
 {
"result" : [
    {
        "_id" : ObjectId("5563596c515a88832210f0e4"),
        "year100" : 201400.0000000000000000,
        "result" : null
    },
}

Why is add operation returuning null value as against to actual value ? Please help.

A: MongoDb not allow to used same fields in project to arithmetic operation instead of one $project used two different projects like this :
db.collname.aggregate({ $project : { 'year100' : {$multiply : ["$year" , 100]} ,"month":"$month"} },{"$project":{"year100":1,"result":{"$add":["$year100","$month"]}}})


text:
Q: Background color during resize in matplotlib I have a matplotlib figure inside a QWidget, when I resize my window there is a black background visable for a very short time (until the figure is resized).
If the plotting widget is inside a layout, this looks very bad.
Is there any way to change this color?
code:
import sys
import matplotlib.pyplot as plt
from PyQt5 import QtWidgets, QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

class Plotwindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Plotwindow, self).__init__(parent)
        self.figure = plt.figure()
        self.figure.set_facecolor('none')
        plt.plot([1,2,3,4,5],[1,4,9,16,25])
        self.canvas = FigureCanvas(self.figure)
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.canvas)
        self.setLayout(layout)

if __name__ == '__main__':
    qApp = QtWidgets.QApplication(sys.argv)
    w = Plotwindow()
    w.show()
    sys.exit(qApp.exec_())

EDIT:
its the same for (without pyqt):
import matplotlib.pyplot as plt

if __name__ == '__main__':
    f = plt.figure()
    plt.plot([1,2,3,4,5],[1,4,9,16,25])
    plt.show()

EDIT2:
This seems to be a problem with the version and/or os.
I do not have the problem on Ubuntu 16.04 with matplotlib 2.1.0 and python3 or 1.5.1 and python2.
I only experienced this on windows 7 with matplotlib 2.0.2 and python3.


text:
Q: Is there a c++ compiler or add-on that supports builtin object serialization? The biggest pain of using libraries like boost::serialization is that a method needs to be supplied to each class that enumerates its fields. It's easy to make a mistake or forget to keep this method updated.
It seems that object serialization could easily be automated if there was extra support from the compiler. I guess it would be a language extension, but not visible directly to the user, only through a library. Is there a project that does this for gcc or perhaps clang?

A: Not really
Serialization isn't standardized in C++ (i.e. it's not in a standard library nor in a compiler). You'll need a special library.


text:
Q: How to restart network Interfaces on virtual machine instead of complete machine reboot/reset using pyvmomi API I am working on a application which cloned virtual machines from a running machine on a specific event in poweredon state. The machines later communicate each other based on event and I have to fetch out (sniff) the network packets through netmon virtual machine which is routed between them but I can't do so directly, I have to reboot the guest on virtual machines manually and then I can access the network reports.
I also tried to rebootguest of vm using pyvmomi but the machine guest will take too much time to be in initial state after boot, I also do poll in loop to check virtual machine guest tool status and network status as well but nothing work, I got the empty network reports.
I did some research and found this is the right place to post this question, please let me know I am in wrong direction.


text:
Q: Replace "Add to Cart" button with an "Enquire" button linking to the "Contact Us" page In both product listings (e.g. the category page) and the product view page, I need to replace the button "Add to Cart" with an "enquire" button which links to the "Contact Us" page.
Please help me to find a solution.

A: Edit the file app/design/frontend/{package}/{theme}/template/catalog/product/list.phtml.
Change this:
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><?php echo $this->__('Add to Cart') ?></button>

to this
<button type="button" title="<?php echo $this->__('Enquire') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getUrl('contacts') ?>')"><?php echo $this->__('Enquire') ?></button>


text:
Q: 2 icons for keyboard switch on gnome panel in Gnome Shell 3 I have 2 icon do the same think (switch keyboard layout) in Ubuntu 11.10/GnomeShell.
I think it is because I  whitelist whole systray-area. Icon in systray (num. 1 on picture) consume much space and I like remove it. It is posible?
screenshot:

A: bug on launchpad
Michael Milligan (milli) instructions how to apply the patch for gnome-settings-daemon
apt-get source gnome-settings-daemon
sudo apt-get build-dep gnome-settings-daemon
sudo apt-get install devscripts build-essential fakeroot patch    patchutils
cd gnome-settings-daemon-3.2.1
wget https://bugs.launchpad.net/ubuntu/+source/gnome-settings-daemon/+bug/805747/+attachment/2544403/+files/0001-change.patch
patch -p1 < 0001-change.patch
debuild -uc -us -b
cd ..
sudo dpkg -i gnome-settings-daemon_3.2.1-*
sudo killall gnome-settings-daemon

gsd-keyboard-kbd applet should be GONE.


text:
Q: Calculating elevation at point on line using ArcGIS Pro? I have two line layers showing stormwater and sanitary sewer pipes.  The attribute tables for both layers show elevations for the upstream and downstream ends of each pipe.  I have a point layer showing where they cross in planimetric view.  Many of the pipes have more than one crossing point.  The attribute table for the crossing points includes IDs for both pipes.
I need to find out which pipe is higher at the crossing points.  I'm using ArcGIS Pro with a Basic license and unfortunately I have minimal coding skills.
Can anyone suggest an approach for this?

A: Aha-- linear referencing.  Perhaps the obviousness of the answer is why I didn't get any replies!


text:
Q: PowerPivot YTD with Missing Data Problem with computation of YTD if Data on a particular period is not existing

Using formula
YTDUnits =CALCULATE(SUM(Data[TYUnits]),DATESYTD(Data[FullDate]),ALL(Data[Month])))
Data came from a csv file, and am only using 1 table in the data model.
In this example, Month 2 should have a value of 6 on TransactionType c.
Is there a way to fill this?
In the data model, no record exists for TransactionType c Month 2

A: I manually typed in your data sample, and built the data model:

Put Year-Month from the calendar table on the pivot, and added this DAX measure:
YTDUnits = CALCULATE(SUM(Data[TYUnits]), DATESYTD('Calendar'[Date]))

Result:


text:
Q: Proof of $x^n(1-x)$ uniformly converges to $0$ on $[0,1]$ I attempted to prove $x^n(1-x)$ converges uniformly to $0$ on $[0,1]$ but I'm not sure if my proof is right.
My proof is:
Let $\epsilon >0$ be given. Then we can find $N\in \mathbb N$ such that $N > 2/\epsilon$. For all $x \in  [0,1)$ if $n\ge N$ we have $$|f_n(x)-0| = |x^n(1-x)| \le |x|^n(1+|x|) \le 2x^n\le2x^N\le2N<\epsilon$$ and if $x=1$, for all $n\ge N, \quad |f_n(x)-0| = |0-0| = 0\le\epsilon$. So $f_n \rightarrow 0$ uniformly on $[0,1]$.
Is my proof correct? Thank you!

A: Hint:  $|f_n(x) - 0| = x^n(1-x)$ attains a maximum at $x^* = n/(n+1)$ where $$f_n(x^*) = \frac{1}{(n+1/n)^n(n+1)}$$

A: Your proof has a mistake.
$2x^N < \varepsilon$ is not given since $\lim_{x\to1}x^N = 1$ for any $N\in\mathbb{N}$.


text:
Q: GLM and implementation of Poisson regression model in R by hand first of, this is not my school exercise but a given example that I'd like to convert from Stan to my own code. I am very much a pragmatic learner so doing this helps me a lot to visualize the problem.
The problem is the following:
#The data give numbers of fatal accidents on scheduled airline flights per year over a ten-year
#period. Assume that the number of fatal accidents in year t follows a Poisson distribution with
#mean theta where log(theta)=a+bt.

#Year      1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
#accidents  24  25    31   31   22   21   26   20   16   22

#theta[i]  # `true' mean number of fatal accidents
y = c(24, 25, 31, 31, 22, 21, 26, 20, 16, 22)                      # number of fatal accidents
t = c(1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985) # year

#Using noninformative priors on a and b, obtain the posterior distributions of a and b. Plot
#the approximate probability density for the expected number of fatal accidents in year 1988.
#Obtain the predictive interval for the the number of fatal accidents in 1988.

Which is run with the following Stan model:
//Poisson_regression_model
data{
  int N; //the number of observations
  real x[N]; //years, real because of mean
  int y[N]; // accidents
}
parameters{
  real a_star;
  real b;
}
transformed parameters{
  vector[N] log_theta;
  vector[N] theta;
  real a;
  a=a_star-b*mean(x);

  for( i in 1 : N ) {
    log_theta[i] = a_star+b*(x[i]-mean(x));
  }

  theta=exp(log_theta);
}
model{
  //priors
  a_star ~ normal(0, 10^3);
  b ~ normal(0, 10^3);

  //likelihood
  for( i in 1 : N ) {
    //see Stan reference manual page 520
    y[i] ~ poisson_log(log_theta[i]);
  }
}

Full code and which I'd like to convert into my own, very naive implementation. So this is how far I got but I must have some mistake calculating my likelihood/log_theta.
a_param_space <- seq(0.1, 20, length=100)
b_param_space <- seq(0.1, 20, length=100)
a_prior <- function(x) dnorm(x, 0, 1e3)
b_prior <- function(x) dnorm(x, 0, 1e3)

theta_likelihood <- function(x, theta) dpois(x, theta, log = T)

y = c(24, 25, 31, 31, 22, 21, 26, 20, 16, 22)
t = c(1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985)

posterior <- function() {
  plen <- length(a_param_space)
  res <- matrix(rep(0, plen*2), ncol=2)
  for(i in 1:plen) {
    for(j in 1:plen) {
      a <- a_param_space[i]
      b <- b_param_space[j]
      log_theta <- a + b*(t - mean(t))
      print(log_theta)
      ab_likelihood <- theta_likelihood(y, log_theta)
      print(ab_likelihood)
      ab_prior_likelihood <- sum(a_prior(a) + b_prior(b) + ab_likelihood)
      print(ab_prior_likelihood)
      res[i, j] = ab_prior_likelihood
    }
  }
  a_sum <- sum(res[,1])
  b_sum <- sum(res[,2])
  normalized <- matrix(rep(0, plen*2), ncol=2)
  normalized[,1] <- res[,1]/a_sum
  normalized[,2] <- res[,2]/b_sum
  return(normalized)
}

Also I'm not sure have I named my variables correctly, it's very hard to me to convert the mathematical formula into programming terms. Say as another example I have a likelihood function $y_i|\theta_i \sim Bin(n_i, \theta_i)$ where $logit(\theta_i)=\alpha + \beta x_i$ with the link function $logit(\theta_i)=log(\theta_i/(1-\theta_i)$.
So this would mean I have to pass as a parameter to binomial density the values y-vector, n-vector and theta, where theta is computed from two parameters (with some values from parameter space), alpha and beta. Those two are then computed from the linear regression model: alpha + beta * x-vector which are inputted to the logit function (alpha + beta * x-vector)/(1-alpha + beta * x-vector) to get as a result a vector of log-odds? Am I almost correct?
Thank you in advance for answering, I am very much a caricature programmer who knows how to code but can't understand math. No need to rub it in.

A: Well I did manage to create the Poisson regression using MAP estimation (not MLE :)). Although I'm sure there is still some parts of it wrong, I'm happy that I managed to pull it off. It has pretty funky looking posterior distribution. However, I didn't figure out how to do the binomial regression. Dunno will I bother looking into it.
a_param_space <- seq(2, 4, length=100)
b_param_space <- seq(-1, 1, length=100)
a_prior <- function(x) dnorm(x, 0, 1e3)
b_prior <- function(x) dnorm(x, 0, 1e3)

poisson_log_ll <- function(y, x, a, b) {
  theta = exp(a + b*x) # link function
  return(sum(dpois(y, theta), log=TRUE))
}

y = c(24, 25, 31, 31, 22, 21, 26, 20, 16, 22)
t = c(1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985)
tt = t - 1976 # Normalize to 0

posterior <- function() {
  plen <- length(a_param_space)
  res <- matrix(rep(0, plen*plen), ncol=plen)
  for(i in 1:plen) {
    for(j in 1:plen) {
      a <- a_param_space[i]
      b <- b_param_space[j]
      ab_likelihood <- poisson_log_ll(y, tt, a, b)
      ab_prior_likelihood <- sum(a_prior(a) + b_prior(b) + ab_likelihood)
      res[i, j] = ab_prior_likelihood
    }
  }
  normalized <- matrix(rep(0, plen*plen), ncol=plen)
  normalized <- res/sum(res)
  return(normalized)
}

map <- function(post) {
  res = which(post==max(post), arr.ind = TRUE)
  return(c(a_param_space[res[1]], b_param_space[res[2]]))
}

pois_post <- posterior()
print(map(pois_post))
print(glm(y ~ tt, family=poisson)$coefficients)

contour(y=a_param_space, x=b_param_space, z=pois_post)
image(y=a_param_space, x=b_param_space, z=pois_post)
persp(y=a_param_space, x=b_param_space, z=pois_post, theta = 25, phi = 35)
persp(y=a_param_space, x=b_param_space, z=pois_post, theta = 0, phi = 90)


text:
Q: a system of finite difference equations Let $a,b>0$ such that $ab<1$  consider the system$$x_{t+1}=x_ty_t+ay_t$$ $$y_{t+1}=x_ty_t+bx_t$$
I would like you to help me answer the following:

*

*find values $a$ and $b$ for which  the solution $\left(\frac{1-ab}{1+b},\frac{1-ab}{1+a}\right)$ is of saddle type

*can one obtain the general solution explicitly?

any suggestion is welcome!

A: Find the Jacobian matrix and put the solution (fixed point) to obtain
$$J = \begin{bmatrix}y & x+a \\ y+b & x\end{bmatrix} \vert_{\left(\frac{1-ab}{1+b},\frac{1-ab}{1+a}\right)} = \begin{bmatrix}\frac{1-ab}{1+a} & \frac{1+a}{1+b} \\ \frac{1+b}{1+a} & \frac{1-ab}{1+b}\end{bmatrix}$$
Then the fixed point is a saddle point if and only if $\text{det} J < 0$ (for 2nd order systems of course).
Finding an explicit solution might be difficult. However, the system equations itself is a recursive solution.


text:
Q: How do I ensure WebChat is hidden when no workers are available? I dont see in the documentation anywhere the ability to hide the chat.
https://www.twilio.com/docs/flex/flex-webchat-basic-configuration
Essentially, I want the chat to NOT show on a website if no agents are available. Is this possible?

A: It looks like I have to call twilio flex to get avaialble workers, and set this property accordingly.
const defaultConfiguration: Config = {
...
available: {BoolValueDependingOnAgentAvail},

Here is an example of javascript that leverages the necessary API to obtain the worker count. Based on this variable, you can set the BoolValueDependingOnAgentAvail accordingly
    client.taskrouter
.workspaces('WSxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
.workers.list()
.then(workers => {
    data = {
        availWorkersCount: Object.keys(workers.filter(x=> x.available === true && x.attributes.includes("sales"))).length
    };


text:
Q: How to change this Runge-Kutta method implementation from first order ode solver to system of ODEs solver? I implemented 4-step Runge-Kutta method (k1..k4) ODE solver for a function  $u'(x) = f(x,u(x))$ with initial condition $u(x_0) = u_0$
But it solves just ODEs of the first order. How could I change the code, so that it also takes ODEs of higher order? ${\bf u}'(x)={\bf f}(x,{\bf u}(x))$ with initial condition ${\bf u}(x_0)= {\bf u}_0$? All as vectors here not scalars.
Here is the code for my solution, which takes first order ODEs:
def euler(f, x, y, h):
    yn = y + h*f(x,y)
    xn = x + h
    return xn, yn

def rk4(f, x, y, h):
    k1 = h*f(x,y)
    k2 = h*f(x+(1/2)*h,y+(1/2)*k1)
    k3 = h*f(x+(1/2)*h,y+(1/2)*k2)
    k4 = h*f(x+h,y+k3)
    yn = y + ((1/6)*(k1+(2*k2)+(2*k3)+k4))
    xn = x + h
    return xn, yn

def integrate(method, f, t0, y0, tend, h): # Depending on the 'method' (euler or rk4) this method solves the ode f)
    T = [t0]
    Y = [y0]
    t = t0
    y = y0
    while (t < tend):
        h = min(h, tend-t)
        t, y = method(f, t, y, h)
        T.append(t)
        Y.append(y)
    return np.array(T), np.array(Y)

#def f1(t, y):   # this is an 1st order ODE
    #return (t*y) + t

# Usage example
xv, yv = integrate(method=rk4, f=f1, t0=0, y0=2, tend=1, h=0.5)
yv[-1] # Output: 6.15203857421875

Is there a solution, to make this work also for a given system of ODEs? (dynamically, without knowing the input ODE if it's 1st or higher order)for example this one:
$$u''(x)+u(x)+u(x)^3 =0 ~~{\rm with}~~ u(0)=u'(0)=0 $$
or this one:
$$u_1'(x) = 98u_1(x) + 198u_2(x) ~~{\rm and}~~ u_2'(x) = −99u_1(x) − 199u_2(x) \\~~{\rm with}~~ u_1(0) = 1 ~~{\rm and}~~ u_2(0) = 0$$
EDIT:
changed the code to this now, to try if the 1st given example 2nd order ODE works:
def f(t,y):
    return np.array([ y[1], -y[0]-(y[0])**3 ])

Y0 = np.array([0.0,0.0])

xv, yv = integrate(method=rk4, f=f, t0=0.0, y0=Y0, tend=100.0, h=h)
print("[ %20.15f, %20.15f]"%(yv[-1,0], yv[-1,1]) )
print(yv)

but I get an output consisting of 0 vectors like this:
[    0.000000000000000,    0.000000000000000]
[[0. 0.]
 [0. 0.]
 [0. 0.]
 ...
 [0. 0.]
 [0. 0.]
 [0. 0.]]

A: There is not much to change, depending on how "user friendly" you want to make it. The quick solution is to explicitly use np.array for vectors, for the classical example of the physical pendulum $y''+\sin(y)=0$ you could code
def f(t, y): return np.array([ y[1], -np.sin(y[0]) ])

y0 = np.array([1.0,0.0])

for h in [0.5, 0.05, 0.005, 0.0005]:
    xv, yv = integrate(method=rk4, f=f, t0=0.0, y0=y0, tend=1.0, h=h)
    print("[ %20.15f, %20.15f]"%(yv[-1,0], yv[-1,1]) )

gives the output
[    0.600232949607472,   -0.754659515900116]
[    0.600085385678949,   -0.754963692069849]
[    0.600085366129492,   -0.754963713951030]
[    0.600085366127465,   -0.754963713953161]

correctly gaining 4 digits for every reduction of the step size by 10.

If you wanted to remove the np.array from the user side, you would have to change the integrate function to detect the type of y0 and if it is not a scalar, redefine initial vector and the input function
if y0 is not np.float:
    y0=np.asarray(y0);
    f_=f; f=lambda t,y:np.asarray(f_(t,y));

or similar.


text:
Q: the morphOne relation always return null im setting up a One To One (Polymorphic) like this
My Models:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payement extends Model{
    protected $table = 'payements';
    protected  $primaryKey = 'id';
    public function payementable(){
        return $this->morphTo();
    }}

class Recu extends Model{
    protected $table = 'recus';
    protected  $primaryKey = 'id';
    public function payement(){
        return $this->morphOne('App\Payement', 'payementable');
    }}

My Tables Schemas
Schema::create('recus', function (Blueprint $table) {
            $table->bigIncrements('id');
        });
Schema::create('payements', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('numero')->unique();
            $table->bigInteger('payementable_id');
            $table->string('payementable_type');
            $table->timestamps();
        });

the problem is this is working
App\Payement::find(1)->payementable;

this return null
App\Recu::find(1)->payement;

and this return empty collection
Recu::first()->payement()->get()

A: The settings you presented don't have any issue. Please test with this data:
payements:
---------------------------------------------
|id|numero|payementable_type|payementable_id|
---------------------------------------------
|1 |1     |App\Recu         |2              |
---------------------------------------------

recus:
----
|id|
----
|1 |
----
|2 |
----
|3 |
----


text:
Q: PHP Escape everything for date function I'm trying to escape every single character wrapped in {{ and }} in a string so this:
d-m-Y {{warning}}

Becomes this:
d-m-Y \{\{\w\a\r\n\i\n\g\}\}

I'm trying to achieve it using preg_replace:
$int = preg_match_all('/(\{\{.*?\}\})/', $format, $matches, PREG_SET_ORDER);
if( $int )
{
    $to_replace = preg_replace('/(.+?)/', "\\$1", $matches[0][0]);
    $format = str_replace( $matches[0][0], $to_replace, $format );
}

But the replace function converts it to $1$1$1$1$1$1$1$1$1$1$1, I'm obviously doing something wrong here...

A: Basically \\$1 should become \\\$1 in your pattern.
However, you can use preg_replace_callback() here:
$string = 'd-m-Y {{warning}}';

echo preg_replace_callback('/\{\{.*?\}\}/', function($match) {
    return preg_replace('/./', '\\\$0', $match[0]);
}, $string);

Output:
d-m-Y \{\{\w\a\r\n\i\n\g\}\}

During tests, I found out that there is even a faster way to replace the characters in the callback function than preg_replace(). You can use wordwrap():
echo preg_replace_callback('/\{\{.*?\}\}/', function($match) {
    return wordwrap($match[0], 1, '\\', true);
}, $string);

This will work ~15 % faster than the above attempt.


text:
Q: Issue while using inner join with sum I have two (2) tables:
ps_wk_mp_seller_transaction_history

And ps_wk_mp_seller_order_status

I want to totalize seller_amount only if current_state = 5
For that I have written this:
select sum(seller_amount) as seller_amount
from ps_wk_mp_seller_transaction_history th inner join
     ps_wk_mp_seller_order_status os
     on os.id_order = th.id_transaction and
        os.current_state = 5 and
        th.id_customer_seller = 2;

For id_customer_seller=2 I get this 4984.020000 (4950+34.02) and it is exact
But I get 25.848000 instead of NULL for id_customer_seller=5
Can someone help me?
May be you can test yourself, this the code: https://github.com/kulturman/fakerepo

A: First of all your records have some logic issue,  id_transaction have tow transactions with same id_transaction but different amount and different state ! so transaction with id 41  having state 5  and that why customer 5 will not be null because 41 is in state 5.
To fix this
transaction id must be unique id for every transaction in order to differentiate between transaction state and amount
the query should be like this
select sum(seller_amount) as seller_amount
from ps_wk_mp_seller_transaction_history th
left join ps_wk_mp_seller_order_status os
  on os.id_order=th.id_transaction
where
  th.id_customer_seller = 2
  and  os.current_state=5

working example here


text:
Q: How to get data from the database into objectlists fast (with entity framework) I'm using linq statements on entity framework objects to get data from the database into lists of objects. My problem is that the performance is abmyssal to say it nice. For a couple hundred or thousand of rows that I process it takes multiple seconds.
I'm putting in a code example further below but first I want to explain WHY I'm putting the data I get into lists of objects and also I'm coming to my question after that:
I'm putting the data into lists of objects to easily access the data and also fill gridviews, and fill comboboxes and be able to use additional methods for calculations and data gathering that are inside the objects.
As I'm pretty sure this usecase is not so seldom and the performance I get is really abmyssal I take it that either I'm using EF wrongly, doing the linq statements wrongly or part of my design idea is completely wrong there. So my question is what can I do to improve the performance (or do I need to completely throw my design idea out of the window and do it completely different...and if so how)?
Code example:
The objects are stored in object classes in the data layer which also have the data gathering methods inside (if there is an error in here let me know as I'm typing this from memory):
public class myobject
{
    public id;
    public name;

    public static List<myobject> GetData()
    {
         using (myentities entity = new myentities())
         {
              List<myobject> resultList = (from e in entity.mytable select new myobject{ id=e.id, name=e.name}).ToList();
         }
    }
}

When I call myobject.GetData() a few times for example to fill 3 comboboxes the problem is that for a few dozen entries it can take almost half a second each. If I have a couple thousand entries its over 1 second. After trying around a bit I saw that even the using (thus creating new connections) does not really make a dffierence and the performance really stems from how I use/get the object list (the sql that linq should generate is as fast as I would normally expect when I do it in sql server maanagement studio).
Update
I made a few tests and what is also a bit strange:
When I use String instead of an object it is still slow and the ToList itself takes way too long. If I for example get back 68 entries it takes 1.7 seconds. 0.5 of this is the ToList method (This phenomenon is clear as the data is only prepared and gathered when tolist is called BUT the 1.7 seconds before are way too long with only a few k of datarows).
public static void GetNameData()
{
     using (myentities entity = new myentities())
     {
          (from e in entity.mytable select e.name).Distinct().ToList();
     }
}

A: The code you provided, with the datasize of "few dozen" and "1 thousand" should be lightning fast. Of course unless you are returning a query of million columns, or unless you did something really strange to your ORM setup.
First, check your database server. It may be running on low priority, it may have indexes totally screwed up, it may have slow network connection, or (...).
Btw. are you always fetching whole table, or you just removed filters in your code example? If it works much faster without filters, check db indices. Otherwise, check network.
Also, try setting up the database locally. If it's too large, trim it down, it's just test. Then retry and check how long it takes. It should be fast. If it's not - then you can really start assuming you got your EF config, cache, data procesing broken in your app.


text:
Q: Map a Website using only Top-Level Domain I am working on a script that will extract emails from a given website. One complication I am running into is that oftentimes the email(s) I am looking for will be on "Contact Us" or "Our People" pages. So far what I have written will look for an email on the main webpage i.e. www.examplecompany.com, and if it doesn't find anything, it will look for emails in the pages linked on that page. See below:
import requests, bs4, re, sys, logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
print('Fetching Website...')
target_URL = 'www.exampleURL.com' #URL goes here
res = requests.get(target_URL)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
type(soup)
my_list = []
for link in soup.find_all('a'):
    my_list.append(link.get('href'))

emailregex = re.compile(r'''(
    [a-zA-Z0-9._%+-:]+
    @
    [a-zA-Z0-9.-]+
    \.[a-zA-Z]{2,4}
    )''', re.VERBOSE)

# Converts each item in list to string
myemail_list = list(map(str, my_list))
# Filters out items in list that to not fit regex criteria
newlist = list(filter(emailregex.search, myemail_list))

if len(newlist) < 1:
    new_site = []
    for i in range(len(my_list)):
        new_site.append(f'{target_URL}{(my_list[i])}')
    try:
        for site in range(len(new_site)):
            newthing = requests.get(new_site[site])
            newthing.raise_for_status()
            freshsoup = bs4.BeautifulSoup(newthing.text, 'lxml')
            type(freshsoup)
    except requests.exceptions.HTTPError as e:
        pass

    final_list = []
    for link in freshsoup.find_all('a'):
        final_list.append(link.get('href'))
    print(final_list)
else:
    print(newlist)

I think the biggest issue I am dealing with is that my method of putting together and searching for related URLs is just wrong. It will work on some sites, but not others and it is error prone. Can anyone give me a better idea of how to do this?
By the way, if it looks like I have no idea what I am doing, you are right. I just started learning python and this is a personal project to help me better grasp the basics, so any help is appreciated.
Thank you for your help.

A: Try:
import requests
import re
from bs4 import BeautifulSoup

all_links = [];mails=[]

# your url here

url = 'https://kore.ai/'
response = requests.get(url)
soup=BeautifulSoup(response.text,'html.parser')
links = [a.attrs.get('href') for a in soup.select('a[href]') ]
for i in links:
    if(("contact" in i or "Contact")or("Career" in i or "career" in i))or('about' in i or "About" in i)or('Services' in i or 'services' in i):
        all_links.append(i)
all_links=set(all_links)
def find_mails(soup):
    for name in soup.find_all('a'):
        if(name is not None):
            email_text=name.text
            match=bool(re.match('[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$',email_text))
            if('@' in email_text and match==True):
                email_text=email_text.replace(" ",'').replace('\r','')
                email_text=email_text.replace('\n','').replace('\t','')
                if(len(mails)==0)or(email_text not in mails):
                    print(email_text)
                mails.append(email_text)
for link in all_links:
    if(link.startswith("http") or link.startswith("www")):
        r=requests.get(link)
        data=r.text
        soup=BeautifulSoup(data,'html.parser')
        find_mails(soup)

    else:
        newurl=url+link
        r=requests.get(newurl)
        data=r.text
        soup=BeautifulSoup(data,'html.parser')
        find_mails(soup)

mails=set(mails)
if(len(mails)==0):
    print("NO MAILS FOUND")


text:
Q: При сборке проекта на objective-c в xcode9 под iOS11 смещаются созданные из кода subViews относительно navigationBar Проблема в следующем: проект написан на objective-c, все UI-элементы созданы из кода. На первом контроллере помимо navigation Bar добавляется скролл View во весь экран(включая navigation Bar) и в него добавляются несколько subView. При сборке проекта в Xcode 8 все элементы отображались верно, без смещений см.рисунок. Но при сборке проекта в Xcode 9 под iOS11, все subView добавляемые мною в ScrollView размещаются не с самого верха экрана, а с отступом, равным высоте navigation Bar. Если его сделать Hidden то окна перемещаются вверх как положено, видимо в iOS11 по умолчанию элемент типа NavigationBar находится в safe Area, как управлять границами safe Area из кода Objective-c найти нигде не могу. Прилагаю код создания скролла и окон... Если кто сталкивался с такой проблемой, пожалуйста подскажите как пофиксить safe Area из кода.
mainNavigationController = [[NavigationController alloc] initWithRootViewController:mainMenuViewController];
mainNavigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
mainNavigationController.delegate = self;
mainNavigationController.navigationBar.tintColor = [UIColor whiteColor];

UIWindow* window = self.window;
window.backgroundColor = [UIColor whiteColor];
window.rootViewController = mainNavigationController;
[window makeKeyAndVisible];

UIView* mainView = [[[MainViewControllerView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
self.view = mainView;

scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
scrollView.autoresizesSubviews = YES;
scrollView.autoresizingMask = UIViewAutoresizingNone;
scrollView.backgroundColor = [UIColor clearColor];
scrollView.bounces = NO;

[scrollView addSubview:myLogoView];
[scrollView addSubview:littleScrollView];
[scrollView addSubview:firstButton];
[scrollView addSubview:secondButton];
[scrollView addSubview:thirdButton];
[scrollView addSubview:fouthButton];
[scrollView addSubview:fifthButton];
[scrollView addSubview:sixthButton];
[scrollView addSubview:seventhButton];
[scrollView addSubview:activityIndicatorView];

![Скриншоты]https://www.dropbox.com/s/ttrkolgnch80kr9/safeArea.png?dl=0

A: Скорее всего проблема из-за scrollView.automaticallyAdjustsScrollViewInsets. В iOS 11 этот метод deprecated, попробуйте задать scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever.


text:
Q: SOLVED : Magento 2 : Any Specific Solution for "Front Controller Reached 100 Router Match Iterations" Error I m using magento 2.1.3. Looking Specific Solution for "Front controller reached 100 router match iterations" Error...?
I checked some answers on stackexchange but not working for magento 2.1.3.
public function match(\Magento\Framework\App\RequestInterface $request) {

    $identifier = trim($request->getPathInfo(), '/');

    /** @var \Magento\Cms\Model\Page $page */
    $page = $this->_pageFactory->create();
    if (strpos($identifier, 'xyz.html') !== false) {
        $request->setModuleName('My_Module')->setControllerName('mymodule')->setActionName('index');
    }
    if (strpos($identifier, 'pqr.html') !== false) {
        $request->setModuleName('My_Module')->setControllerName('mymodule')->setActionName('testing');
    }
    $request->setAlias(\Magento\Framework\Url::REWRITE_REQUEST_PATH_ALIAS, $identifier);
}

A: I am Not Extending This Class in Controller After Extending
\Magento\Framework\App\Action\Action
And Impliments its execute() method it Works.


text:
Q: Scaling SVG in HTML5 I have replaced a header logo image which was just text in an arc on the following website: Leeds Magic Circle
Disclaimer: I did not design or create this website I am just performing some small modifications to it.
The original image said "1919 - 2015" and needed updating, hence I chose SVG to replace it with a bit of javascript to update the date portion.
It looks good, however it doesn't scale down when the browser is reduced or viewed on a mobile device.
I need the SVG to fit the 800x116 which replaced the original image, but I need it to scale down too.
I am very new to playing with SVG and the answers on the web are somewhat confusing so hopefully someone here can help.
Also open to alternative methods to achieve this goal.
Thank you


text:
Q: How do I make a displayMethod() in AX? What are the steps that I have to complete to create a displayMethod() for later use on a TextEdit?

A: I wrote a blog post about this, showing how to create a Display Method template inside AX so that you could easily create a new Display method in only a few clicks:
Enhance your AX 2009 Editor Scripts

A: Have a look on Axaptapedia (or just use Google search as I did).


text:
Q: Android App (Webview) crashes because of splashscreen Some phones (e.g. Samsung S6 or S7) cannot start my android webview app. This is what I got from the google play store:
java.lang.RuntimeException:

  at android.view.DisplayListCanvas.throwIfCannotDraw (DisplayListCanvas.java:260)
  at android.graphics.Canvas.drawBitmap (Canvas.java:1420)
  at android.graphics.drawable.BitmapDrawable.draw (BitmapDrawable.java:545)
  at android.widget.ImageView.onDraw (ImageView.java:1286)
  at android.view.View.draw (View.java:18318)
  at android.view.View.updateDisplayListIfDirty (View.java:17296)
  at android.view.View.draw (View.java:18080)
  at android.view.ViewGroup.drawChild (ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw (ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty (View.java:17291)
  at android.view.View.draw (View.java:18080)
  at android.view.ViewGroup.drawChild (ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw (ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty (View.java:17291)
  at android.view.View.draw (View.java:18080)
  at android.view.ViewGroup.drawChild (ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw (ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty (View.java:17291)
  at android.view.View.draw (View.java:18080)
  at android.view.ViewGroup.drawChild (ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw (ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty (View.java:17291)
  at android.view.View.draw (View.java:18080)
  at android.view.ViewGroup.drawChild (ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw (ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty (View.java:17291)
  at android.view.View.draw (View.java:18080)
  at android.view.ViewGroup.drawChild (ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw (ViewGroup.java:3752)
  at android.view.View.draw (View.java:18321)
  at com.android.internal.policy.DecorView.draw (DecorView.java:919)
  at android.view.View.updateDisplayListIfDirty (View.java:17296)
  at android.view.ThreadedRenderer.updateViewTreeDisplayList (ThreadedRenderer.java:692)
  at android.view.ThreadedRenderer.updateRootDisplayList (ThreadedRenderer.java:698)
  at android.view.ThreadedRenderer.draw (ThreadedRenderer.java:806)
  at android.view.ViewRootImpl.draw (ViewRootImpl.java:3128)
  at android.view.ViewRootImpl.performDraw (ViewRootImpl.java:2924)
  at android.view.ViewRootImpl.performTraversals (ViewRootImpl.java:2516)
  at android.view.ViewRootImpl.doTraversal (ViewRootImpl.java:1515)
  at android.view.ViewRootImpl$TraversalRunnable.run (ViewRootImpl.java:7091)
  at android.view.Choreographer$CallbackRecord.run (Choreographer.java:927)
  at android.view.Choreographer.doCallbacks (Choreographer.java:702)
  at android.view.Choreographer.doFrame (Choreographer.java:638)
  at android.view.Choreographer$FrameDisplayEventReceiver.run (Choreographer.java:913)
  at android.os.Handler.handleCallback (Handler.java:751)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6682)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)

It seems to be my splashscreen, this is it:
activity_main.xml:
//splashscreen fullscreen
<ImageView
    android:id="@+id/splash1"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop"
    android:adjustViewBounds="true"
    android:screenOrientation="portrait"
    android:visibility="visible"
    android:src="@drawable/redsplashscreen"
    />

//shows the webview fullscreen
<WebView
    android:id="@+id/web1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"

MainActivity.java snippet:
boolean splashFinished = false;

    @Override
    public void onPageFinished(WebView view, String url) {
        //loads splashscreen once till website is loaded
        if (!splashFinished) {
            //hides loading image
            findViewById(R.id.splash1).setVisibility(View.GONE);
            //shows webview
            findViewById(R.id.web1).setVisibility(View.VISIBLE);
            splashFinished = true;
        }

Some people here said that I have to move the image from "drawable"-folder to "drawable-xxhd", and I tried it, but when I want to create a APK, android studio moves it back and changes the code of xml.
BTW the image is not really big, I changed the size from 1.7MB to 0.7MB.

A: In my case, some phone cannot handle big splash image file.
Mine was 1.xMB and after I reduce file size, no more crash.
Reduce file size.

A: I've got a solution: inside android studio I made "drawable-xxhdpi"-folder (right-click "res" -> new -> directory). And I put the same splashscreen image inside this folder. This way, it doesn't change anything of the aactivity_main.xml.


text:
Q: What is the splitting field of $t^4+2$? I currently beginning the study if Galois theory but my understanding of the construction of splitting fields could be better. So I must ask if I could see the steps in constructing the splitting field of $t^4+2$.

A: A splitting field of a polynomial must be computed over a field, and the choice of that field affects the resulting splitting field, since a splitting field is a field extension.
For instance, the splitting field of $t^4 + 2$ over $\mathbb R$ is $\mathbb C = \mathbb R(i)$.  The splitting field of that same polynomial over $\mathbb Q$ is something else (hinted by an above comment).  And the splitting field of that same polynomial over $\mathbb F_7$ is again something else.

A: First You must determine that the polynomial is considered to be in $\mathbb{Q}$ or $\mathbb{R}$ or any other field.
I suppose that we're going to find the splitting field of $t^4+2\in\mathbb{Q}[t]$.
Now you know $\mathbb{C}$ is an extension of $\mathbb{Q}$. This is a good start that every polynomial splits in $\mathbb{C}$.
Then let's try to split it!
$$t^4+2=(t-\sqrt[4]{2}\omega)(t-\sqrt[4]{2}\omega^3)(t-\sqrt[4]{2}\omega^5)(t-\sqrt[4]{2}\omega^7);$$
where $\omega=e^{\frac{\pi i}{4}}$.

Now it's sufficient to form the field $E=\mathbb{Q}(\sqrt[4]{2}\omega,\sqrt[4]{2}\omega^3,\sqrt[4]{2}\omega^5,\sqrt[4]{2}\omega^7)=\mathbb{Q}(\sqrt[4]{2}\omega,\omega^2)=\mathbb{Q}(\sqrt[4]{2}\omega,i)$
The last line is true as @Mariano Suárez-Alvarez♦ has mentioned in the comments.

#EDITED
It's definitely wrong that $\mathbb{Q}(\sqrt[4]{2}\omega,\sqrt[4]{2}\omega^3,\sqrt[4]{2}\omega^5,\sqrt[4]{2}\omega^7)=\mathbb{Q}(\sqrt[4]{2}\omega)$, as @Jyrki Lahtonen♦ has stated in the comment below.


text:
Q: Proving a property of groups assuming they are abelian or they have a prime divisor
Let $n \in \mathbb{N}, n \geq 3$ be an odd number and $(G, \cdot)$ a group with $2n$ elements. Let $A=\{x^2 \mid x \in G\}$. Show that $\lvert A \rvert = n$ if at least one of the following conditions is true:
\begin{gather}
\begin{aligned}
a)\, &(G, \cdot) \text{ is abelian} \\
b)\, &n \text{ is a prime number}
\end{aligned}
\end{gather}

My approach was to first assume $b)$ and solve the problem. If $n$ is a prime odd number then $n \neq 2$ so by Cauchy's theorem there exist two elements $x$ and $y$ such that $x^2=e$, $y^n=e$, where $e$ is the identity element. Therefore, we can define $H=\{y^k \mid k \in \mathbb{Z} \}$ and $K=\{e, x\}$. It is clear that $H$ and $K$ are subgroups of $G$ and $H$ is a normal subgroup(it has an index of $2$). Now $HK=\{hk \mid h \in H \text{ and } k \in K \}, \lvert HK \rvert = \frac{\lvert H \rvert \lvert K \rvert}{\lvert H \cap K \rvert}=\frac{2n}{\lvert H \cap K \rvert}$. Therefore $H$ and $K$ only have $e$ in common and $HK=G$. If $a \in G, a \notin H$, then $a=xy^k, 0 \le k \le n-1$. If $(xy^k)^2 \notin H \implies xy^kxy^k=xy^m \implies x=y^m(y^{-a})^2 \implies x \in H $ which is a contradiction. Therefore $A$ has at most $n$ elements. How would I prove $A$ has at least $n$ elements to get the double inequality and I have no ideea how to deal with $a)$

A: If $G$ is abelian, the map $x \mapsto x^{2}$ is a homomorphism, so its image $A$ is a subgroup. The kernel $K = \{ x \in G : x^{2} = 1 \}$ is a subgroup, which by Cauchy's lemma applied twice has order a power of $2$ greater than or equal to $2$, so by Lagrange's theorem it must have order exactly $2$. It follows that $A \cong G/K$ has order $n$.
If $n$ is a prime, then by Cauchy's lemma there is a subgroup $B$ of order $n$. Each element $b \in B$ is a square, as $b = b^{n + 1} = (b^{(n+1)/2})^{2}$, so $B \subseteq A$. On the other hand, $B$ has index $2$ in $G$, and thus it is normal. Since $G/B$ has order $2$, it follows that all squares are in $B$, so $A \subseteq B$, and $A = B$ has order $n$.

Perhaps it could be noted that the fact that $G$ has order $2 n$, with $n$ odd, implies that $A$ has order $n$ without any further assumptions. This is because such a $G$ has a subgroup of order $n$.

A: If $G$ is abelian, then the set $A$ is a subgroup. It can't be of even order. Otherwise, a larger power of $2$ would have to divide $|G|$.
Now, why is it $n$? Because there is a unique order $2$ element, $a^2=e$. If $a,b$ are order two elements, then $<a,b>$ is of order $4$ which is not possible.
If $a^2=b^2$, then $ab^{-1}$ is an element of order $2$ and by our previous argument, it is either $e$ or $a$. Therefore, $x \rightarrow x^2$ is a $\text{two-to-one}$ function. This settles Case $1$.
Now, if $|G|=2p$, there is a subgroup of order $p$, say, $H$. For every element in $g\in G-H$, look at its projection $gH\in G/H$. That element is of order $2$, which means $g^2\in H$. Therefore, $A\subset H$.
Since $H$ is cyclic of odd order, $h\rightarrow h^2$ is an isomorphism. Therefore, $A=H$.


text:
Q: Unix , Delete first column using awk I have a file named test.txt which has the following content
123,2,1
I want to print the contents of the file without "123,"
I used the following
awk -F, '{print substr($0, index($0, $2))} text.txt'

It doesn't work properly tho, it prints 23,2,1
But when I run it for this text '123,5,1' , it works without a problem (it prints 5,1)

A: You can use sub() function and remove the first field regardless of what it is.
$ echo '123,2,1' | awk '{sub(/[^,]+,/,"")}1'
2,1

$ echo '23,2,1' | awk '{sub(/[^,]+,/,"")}1'
2,1

A: Another awk
echo '123,2,1' | awk -F, '{$1="";sub(/,/,"")}1' OFS=,
2,1

Removes the first field, then the separator.

A: Use cut:
cut -d, -f2- file

-d, uses , as delimiter, and -f2- prints fields 2 to last.


text:
Q: Drives missing from "This PC", yet they are Online and have a letter assigned I'm facing this issue where the drives don't appear in This PC under the Windows Explorer or a Search folder prompt.
All my drives are online, have a letter assigned and are fully accesible by manually typing the path (E:\something) or by apps (Steam can play games stored in my F:\ drive).

The only drive showing is a network attached SBC.
Does anyone know how to fix this strange issue? Thank you.

A: So I finally fixed it by manually editting two registry keys:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer
If either one has a property named NoDrives with anything other than 0, change it to 0, then reboot and it should be fixed. It worked for me at least. ¯\_(ツ)_/¯
I hope it helps somebody out there!
Props to Neemobeer over at Windows Forum for finding the solution!

A: There are several approaches to fixing this problem. The simplest is to
Go to Control Panel
Open Administrative Tools
Open Computer Management
Select Storage
Open Disk Management
Right click on the required drive and select Change Drive Letter or Path
Add the correct drive letter


text:
Q: Create an array of objects that implements a specific protocol TL;DR
I'm looking for an array type (var array = [TheTypeImLookingFor]()) like 'all objects that subclasses UIViewController and implements the protocol MyProtocol.
Explanation
I'm building a kind of wizard view with a container view and embedded child views (controller). No problem, this will work as long, as I have only one base type of child view controllers.
Due to the content of screens, I have now a bunch of view controllers of type MyTableViewController which is a subclass of UITableViewController and other view controllers that have regular UIViewControllers as base.
All of the view controllers have one thing in common. A default data property myData: MyObject.
I created a protocol MyProtocol that contains this property.
Now, I have to combine all this view controllers into one array to use it as wizard steps. As long as I only have to access the view controller methods (array items are type of UIViewController) I'm able to use var viewControllers = [UIViewController]() or if I wanna only access the myData property, I change the array item type to MyObject.
But the problem is, I have to access the methods from the UIViewController and from the protocol.
That's why I'm looking for an array type like 'all objects that subclasses UIViewController and implements the protocol MyProtocol.
I tried:

*

*var viewControllers = [UIViewController: MyProtocol]() // is a dict

*`var viewControllers = UIViewController where MyProtocol

*`var viewControllers = UIViewController.conforms(to: MyProtocol)

*...

But nothing works as expected.

A: As far as I know, there's currently no way to type something so that it describes anything which inherits from a given class and conforms to a given protocol.
One possible hacky workaround would be to just create a wrapper type in order to perform typecasting for you in the case that you need to treat the instance as a MyProtocol.
struct MyProtocolViewController {

    let base: UIViewController

    init<T : UIViewController>(_ base: T) where T : MyProtocol {
        self.base = base
    }

    func asMyProtocol() -> MyProtocol {
        return base as! MyProtocol
    }
}

Now you can create a [MyProtocolViewController], and can either treat an element as a UIViewController, or a MyProtocol.
// given that ViewController and AnotherViewController conform to MyProtocol.
let viewControllers = [MyProtocolViewController(ViewController()),
                       MyProtocolViewController(AnotherViewController())]

for viewController in viewControllers {
    print(viewController.asMyProtocol().myData)
    print(viewController.base.prefersStatusBarHidden)
}

A: You could use protocol composition with a placeholder protocol for the class:
protocol UIViewControllerClass {}
extension UIViewController: UIViewControllerClass {}

protocol MyProtocol:class {}

class MySpecialVC:UIViewController,MyProtocol {}

var viewControllers = [UIViewControllerClass & MyProtocol]()

viewControllers.append( MySpecialVC() )

This covers the type safety part but doesn't let you access UIViewController methods without type casting.   You can reduce the type casting ugliness by adding a typed property to your protocol (when it applies to the base class)
extension MyProtocol where Self: UIViewControllerClass
{
   var vc:UIViewController { return self as! UIViewController }
}

// accessing the view controller's methods would then only require insertion of a property name.
viewControllers.first!.vc.view

Alternatively, you could define the UIViewController methods you need to call in the placeholder protocol but that could quickly become tiresome and redundant if you're going to use many of them.

A: Why not simply create :
Why not creating :
class ObservingViewController : UIViewController, MyProtocol {

}

var viewControllers : [ObservingViewController] = []

A: You can also create a protocol that defines all the UIViewController functions that you need. Make sure that you copy the method signature, otherwise you will have to implement the functions again.
protocol UIViewControllerInteractions {
    //copy the signature from the methods you want to interact with here, e.g.
    var title: String? { get set }
}

Then, you can extend your existing protocol.
protocol MyProtocol: UIViewControllerInteractions { }

Or create a new protocol that extends UIViewControllerInteractions and MyProtocol.
protocol MyProtocolViewController: UIViewControllerInteractions, MyProtocol { }

Now, when you extend your SubclassUIViewController, you still only have to add your myData because the methods in the UIViewControllerInteractions are already implemented by UIViewController (that's why we copied the method signature)
class SubclassUIViewController: MyProtocol {
    var myData ...
}

You can now have an array of MyProtocol or MyProtocolViewController and also call the methods defined in UIViewControllerInteractions which will call the UIViewController methods.
var viewController: [MyProtocol] = [...]
viewController.forEach { (vc) in
    print(vc.myData)
    print(vc.title)
}

A: I had a similar issue and solved it with a custom base class. Imagine an array like:
var viewControllers: [MapViewController]

which all should extend from UIViewController and implement the following protocol:
protocol MapViewControllerDelegate {
    func zoomToUser()
}

Then I've declared a base class like:
class MapViewController: UIViewController {
    var delegate: MapViewControllerDelegate?
}

Caution: this class doesn't implement the above protocol but holds a property which provides the desired functionality. The next step is to define one of the UIViewController that will be added to the array:
class GoogleMapsViewController: MapViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
    }
}

extension GoogleMapsViewController: MapViewControllerDelegate {
    func zoomToUser() {
        // Place custom google maps code here
    }
}

The important part is located in the viewDidLoad method. The view controller assigns itself as the delegate.
Usage:
let googleMapsViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "GoogleMapsViewController") as! GoogleMapsViewController
let mapboxMapsViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MapboxMapsViewController") as! MapboxMapsViewController
let mapViewControllers: [MapViewController] = [googleMapsViewController, mapboxViewController]
for mapVC in mapViewControllers {
    mapVC.delegate?.zoomToUser()
}

The benefits:

*

*The MapViewController is like an abstract class and If I change the MapViewControllerDelegate the compiler forces me to implement the changes in the GoogleMapsViewController and in the MapboxMapsViewController.

*If I need a second protocol I could just implement a second delegate property.

*No type casting needed like in the other answers. Each UIViewController is still a UIViewController and provides all its methods.


text:
Q: Windows server ignoring DNS resolution on private interface I have a Windows 2012 server with two interfaces - public internet facing, and private.
The private interface uses our internal DNS servers. This interface has no gateway. Static IP - not DHCP.
I want to disable the public interface, as we use a proxy for outgoing traffic.
Having disabled it, I'm finding DNS resolution failing:

*

*I cannot ping foo.external.com  - host cannot be found

*However, I can nslookup, notice that it connects to our internal DNS, and successfully resolve foo.external.com

*ipconfig /displaydns DOES show the correct entry.  I'm utterly confused why ping does not simply use this entry.

*If I manually add an entry to local hosts file, for "1.1.1.1 foo", as an experiment, and try ping foo, it fails - cannot resolve host.  Same for foo.external.com, and "foo.external.com.".   Pinging "foo.external.com", or "foo.external.com." also fails.

*If, however, I then re-enable the public interface, it all works.  Including the hosts file. I can ping "foo" (the resolution aspect).  Disable it, and it stops working again.
I've tried all the reboots, ipconfig /flushdns, nbtstat -R stuff.
a) Why is ping (and our application) not able to properly resolve things when the public interface is disabled, despite Windows being able to speak to its DNS server, and cache the result (as shown in ipconfig /displaydns).
b) Why is the hosts file being ignored for the private interface?
Many thanks.

A: A quick Google search returned this user with the same question:
The user took a Wireshark capture and found that when when trying to ping the host, no DNS query was being performed.
The explanation for this behaviour was:

I believe that nslookup opens a winsock connection on the DNS port and
  issues a query, whereas ping uses the DNS Client service. You could
  try and stop this service and see whether this makes a difference.
Some commands that will reinitialize various network states :
Reset WINSOCK entries to installation defaults : netsh winsock reset catalog
  Reset TCP/IP stack to installation defaults : netsh int ip reset reset.log
  Flush DNS resolver cache : ipconfig /flushdns
  Renew DNS client registration and refresh DHCP leases : ipconfig /registerdns
  Flush routing table : route /f (reboot required)

A: Are your internal DNS Servers on the same subnet as your private interface ? If not, then your server will not know a route to your DNS Servers, and your DNS query will fail.
Add a gateway to your private network settings, or add a static route, so your private NIC knows what it can reach from it.


text:
Q: create Panel at Pandas by multi-level dictionary I am a new to python and pandas.
And I found myself that I have a problem in creating Panel or multi-index DataFrame at pandas.
The fact is that I have a multi-level dictionary, currently three level where the final value is an integer, and I want it's key in each level to be an corresponding index for Panel ,that correspond Panel's item , major-axis,and minor-axis to my dict's first, second, third level. When I create one from my dictionary, the index is not match though.
Here is my dictionary.
d={'item1':{'major0':{'minor0':1,
                      'minor1':2},
            'major1':{'minor0':3,
                      'minor1':4}
           },
   'item2':{'major0':{'minor0':5,
                      'minor1':6},
            'major1':{'minor0':7,
                      'minor1':8}
           }
  }

Is there any simple way to do this. I have look through Pandas tutorial and just not saw any function support of this.

A: You can apply the swap_axes method after construction:
In [1]: p = pd.Panel(d)

In [2]: p.swapaxes()
Out[2]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 2 (minor_axis)
Items axis: item1 to item2
Major_axis axis: major0 to major1
Minor_axis axis: minor0 to minor1

It's worth mentioning the from_dict Panel method, which allows you to pass an orient (but apparently only items/minor are allowed, whilst you want to do major...):
In [11]: pd.Panel.from_dict(d, orient='minor')  # default orient is items
Out[11]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 2 (minor_axis)
Items axis: major0 to major1
Major_axis axis: minor0 to minor1
Minor_axis axis: item1 to item2

A: I'm not sure if this counts as a simple way, as collapsing the dictionary is definitely something you'll have to do by hand, but:
# Collapse the first two levels of keys into tuples
# The dict comprehension could (and maybe should) be written
# with standard for loops
d_collapsed = {(outer_k, inner_k): inner_v for outer_k in d
               for inner_k, inner_v in d[outer_k].items()}
df = pd.DataFrame.from_dict(d_collapsed)
# Now unpack the tuples again
df.columns = pd.MultiIndex.from_tuples(df.columns)

Output:
df
Out[18]:
         item1           item2
        major0  major1  major0  major1
minor0       1       3       5       7
minor1       2       4       6       8


text:
Q: Group episodes by seasons So i have 2 custom post types, Shows and Episodes. I want when im on example.com/show/better-call-saul, to group episodes by seasons for example:
-Season 1
  .Episode 1
  .Episode 2
  .Episode 3
-Season 2
  .Episode 1
  .Episode 2
  .Episode 3

Ive tried grouping by category for example, each episode need to be in category: Season 1 or Season 4, but that doesnt work so well or i dont know how do it properly. What structure would you have? what i need do add to make it work?
Do i need to add another post type, like "Seasons" ?
    <?php
$terms = get_terms( array(
  "taxonomy" => "category",
) );
foreach ($terms as $term) :
  $posts = get_posts(["post_type" => "episodes", "cat" => $term->term_id]);
?>

<?= $term->name; ?>

  <?php foreach($posts as $post) : ?>

        <?= $post->post_title; ?>

    <img src="<?php the_post_thumbnail_url(  ); ?>" alt="<?php the_title(  ); ?>">
    <?php endforeach; ?>

<?php endforeach; ?>


text:
Q: Capture + Save Screenshot in Pivot table using different filters I tried to record a macro to save screenshots of a selected area from my Pivot table using different filters.
But when I tried to re-run, it didn't return any pictures.
Is there a way I can create and save snapshots (and save as picture without links), so that whenever I change the filter, it creates another snapshot of the same area?


text:
Q: Stimulus Script tag not executed for content appended to the page after the page is fully loadedd I have a stimulus controller responsible for fetching and appending html to the page.
remote_ui_controller.js
import { Controller } from '@hotwired/stimulus';
import axios from 'axios';

export default class extends Controller {
  static values = {
    containerSelector: String,
    url: String,
    params: Object,
    uiLoaded: { type: Boolean, default: false }
  }

  fetchUI(){
    if (this.uiLoadedValue) { return; }
    axios.post(this.urlValue, this.paramsValue)
    .then((response) => {
      this.uiLoadedValue = true
      this.container().innerHTML = response.data
    }).catch((err) => {
      this.uiLoadedValue = false
      this.displayError()
    })
  }

  container() {
    return document.querySelector(this.containerSelectorValue);
  }

  displayError(){
    this.container().innerHTML = this.errorTemplate()
  }

  errorTemplate() {
    return `<p class='text-red-500'>An error happened, please try again later</p>`
  }

}.
Now in my specific case it renders this rails partial :
<%= render(
    'organizations/rows/program/available_sessions',
    product: @product,
    learning_item: @program,
    show_enroll_button: @show_enroll_button,
    button_type: @button_type,
    form: @form
  )
%>

<script type="text/javascript">
  alert('helllo')
  console.log("heyyyyyy")
  tippy('.collaborators-enrolled', {
    // default
    placement: 'right-start',
    allowHTML: true,
    arrow: true,
    theme: 'light',
  });
</script>

it works well but the code in the script tag is never executed. Why is this script tag not executed ?


text:
Q: Есть ли android x зависимость для navigation? Вот решил попробовать поработать с Navigation Architecture component
https://developer.android.com/topic/libraries/architecture/navigation/
и не могу понять , что я делаю не так
Вот мой градл зависимостей
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

//android
implementation "androidx.appcompat:appcompat:${libs.supportVersion}"
implementation "androidx.constraintlayout:constraintlayout:${libs.constraintLayout}"

//Stetho
implementation "com.facebook.stetho:stetho:${libs.stetho}"

//Crashlitics
implementation('com.crashlytics.sdk.android:crashlytics:2.9.5@aar') {
    transitive = true
}

//RxJava2
implementation "io.reactivex.rxjava2:rxjava:${libs.rx2Java}"
implementation "io.reactivex.rxjava2:rxandroid:${libs.rx2Android}"

//Dependency Injection
implementation "com.google.dagger:dagger:${libs.daggerVersion}"
implementation 'androidx.appcompat:appcompat:1.0.0-rc02'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
annotationProcessor "com.google.dagger:dagger-compiler:${libs.daggerVersion}"

//Timber
implementation "com.jakewharton.timber:timber:${libs.timber}"

//Architecture components
implementation "androidx.lifecycle:lifecycle-extensions:${libs.lifecycle_component}"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:${libs.lifecycle_component}"

// Retrofit 2
implementation "com.squareup.retrofit2:retrofit:${libs.retrofit2}"
implementation "com.squareup.retrofit2:adapter-rxjava2:${libs.retrofit2}"
implementation "com.squareup.retrofit2:converter-moshi:${libs.retrofit2}"
implementation "com.squareup.okhttp3:logging-interceptor:${libs.retrofitInterseptor}"

//test
testImplementation "junit:junit:${test.junit}"
androidTestImplementation "androidx.test:runner:${test.runner}"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
androidTestImplementation "androidx.test.espresso:espresso-core:${test.espresso}"
}

все работает на android x зависимостях
Но если мы хотим попробовать поработать с навигацией нужно добавить следующую зависимость
implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha05'

и как только мы ее добавляем, то при компиляции получаем вот такую ошибку

Error: Program type already present: android.support.v4.os.ResultReceiver$MyResultReceiver

Как мы знаем, android x не поддерживает использование библиотек support
а эта ошибка возникает именно по причине того, что где то в недрах этой зависимости используется support
Я начал искать в migrate файле https://developer.android.com/topic/libraries/support-library/refactor как заменить эту зависимость на android x, но там этого нет.
Вопрос как это сделать? Есть ли тут человек который пробовал использовать
Navigation Architecture component вместе и android x зависимостями?


text:
Q: Compound interest program The question goes like this - Bank pays Manish interest every month.         Manish is also a determined investor and refrains from withdrawing anything from         this account because he now believes in power of compounding. Given investment         corpus, fixed annual rate of interest and maturity period calculate the amount         the Manish will end up saving at the end of his tenure. These are the         constraints given:
    P > 0 ; it can be float value, where p is investment corpus
    R >=0 ; it can be float value, where r is rate of interest per annum
    T >0 ; it can be integer only, where t is tenure(given in months)
    Calculation should be done upto 11-digit precision.

My code goes like this:
import java.io.*;
import java.util.*;
public class CompoundInterest
{
public static void main(String args[])
{
float principal;
int months;
float rate;
double final_amount = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Principal: \n");
principal = sc.nextFloat();
System.out.println("Months: \n");
months = sc.nextInt();
System.out.println("Interest rate: \n");
rate = sc.nextFloat();
for(int x = 1;x<=months;x++)
{
double amount = principal*Math.pow(1+rate,x);
final_amount = final_amount+amount;
}
System.out.println("final_amount"+final_amount);
}
}

If I give input as 25,4 and 6 respectively.. Output should be 152.
I am getting output as 172.Can anyone help me to correct my procedure of this and run this program?

A: With your program and your input I am getting 7000 as result.
Bear in mind that using 6 as rate the way you are using it actually means 600%.
Also you have to consider. Is the rate monthly or yearly? Depending on the answer you may need to divide it by 12. Hint : read second line of your problem.
Also. Where do you get that the answer is 152 from?
Without doing any math it is quite obvious that 25 dollars at a 6% anual interest rate are never going to turn int 152 dollars in four months.


text:
Q: What classes need to 'Use' the Enterprise Application Block's dll's? I'm adding the the Microsoft Enterprise Application Block's "Exception Handling" module to my project. Following thier instructions mnsd MSDN it says I need to add a using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling; statement. Does this need to go in every single file that throws an exception handled by the the block, or just the file that catches the error?
For example, say I've got FormMainView, FormMainPresenter, and Class1, Class2, Class3. FormMainView is the view that calls FormMainPresenter, and that delegates specific tasks to the three classes. Classes 1 -3 throw various exceptions and they're caught in the Presenter. Do all 4 files need this using statement, or just the presenter?
Using the MS EAB 4.1, by the way.

A: The using statement needs to be in all .cs files that make use of the Exception. Both classes that throw the exceptions and classes that handle the thrown exceptions.
Visual studio will complain when you are missing a using. To double-check your usings you can remove one and see if the compiler complains, if it does then the using is required. If it doesn't complain then the using was redundant.

FormMainView is the view that calls FormMainPresenter, and that
  delegates specific tasks to the three classes.
Classes 1 -3 throw
  various exceptions and they're caught in the Presenter.
Do all 4 files
  need this using statement, or just the presenter?

If Exceptions are caught in FormMainPresenter, FormMainView will not need to know about them so no using is required in FormMainPresenter. A using in the other 4 classes is required.


text:
Q: How to delete a specific column from pandas dataframe I'm new to Python. I would like to ask regarding how can you delete a specific columns in a pandas dataframe. This is my dataframe:
Pandas Dataframe:

I would like to delete the column "tahun" and "jenis" as its have the same value for every month. Please help.

A: df.drop(columns=['tahun','jenis'], inplace=True)