text:
Q: How to find the probability of each element in a array getting a certain random variable? I created an array called new array and assigned the vales so the first node in the array is 0 and the rest is 1.
int[] arr = new int[10];
arr[0] = 0;
 for (int m = 1; m < 10; m++) {
         arr[m] = 1;
    }

Then I did a loop to assign a random variable between 0 and 1 to it
for(int i = 0;i < 100; i++){
    U = rnd.nextInt(2);
   int j = rnd.nextInt(10);
    arr[j] = U;
}

I am trying to write a code to find the probability that each element in this array gets assigned the number 0 at least once. The probabilty it will get assigned 0 is .1?

A: In your code the probability depends by the nextInt function implementation.
So, you have to study the random function that you use to determinate the final proability.

A: *

*For the first element: it's necessarily set to zero at the very beginning, so the probability is 1.

*For the second element:

*

*In each loop iteration:

*

*Every element is equally likely to be chosen, meaning that the second element has a one-in-ten chance (probability 0.1) of being chosen.

*The chosen element is equally likely to be set to either zero or one, meaning that it has a one-in-two chance (probability 0.5) of being set to zero.

*The events "the second is chosen" and "the chosen element is set to zero" are independent, so we can multiply their probabilities to get the probability of the event "the second element is set to zero" (meaning "the second element is chosen and the chosen element is set to zero"): 0.1 × 0.5 = 0.05.

*This means that the event "the second element is not set to zero" has probability 1 − 0.05 = 0.95.

*Overall:

*

*Since there are 100 iterations, and they're all mutually independent, the event "the second element is never set to zero" (meaning "in every single iteration, the second element is not set to zero") has probability 0.95100 ≈ 0.00592.

*This means that the event "the second element is set to zero at least once" has probability 1 − 0.95100 ≈ 0.994.

*The third, fourth, etc. elements are equivalent to the second element — I just chose the second element for convenience — so they, too, each have a probability of 1 − 0.95100 ≈ 0.994 of getting set to zero at least once.


text:
Q: Chrome Extension Issue Working on some background javascript for my chrome extension, and my test is to have it do something every x seconds according to a changing variable. I decided to use setTimeout. I then run it.. and it just spams me with alerts.
http://jsfiddle.net/Ultimate/TpsBv/2/ (Do NOT use the fiddle unless you have something like chrome where you can stop the alerts)
$(document).ready(function() {
    localStorage.seconds = 5; //Added for testing
    wait();
});
function sayHi() {
    alert(localStorage.seconds);
    wait();
}
function wait() {
    var time = localStorage.seconds * 1000
    setTimeout(sayHi(), time);
}

Note: *I made sure to do * 1000 because they're milliseconds, and jQuery IS enabled.*

A: Alright, fixed when the first comment reminded me to check my chrome console.
Anyway, I found the fix here: Determining where Maximum call stack size is being exceeded
EDIT: New fiddle here: http://jsfiddle.net/Ultimate/TpsBv/5/
setTimeout(function() { sayHi(); }, time);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Restoring Previous instance of AWS Appsync schema I hope I can explain this well.
So I created a react app with amplify and pushed my schema and went on to modify and create the various resolvers I require upon discovering that if I performed "amplify push" again because I changed or modified added a new field all the resolvers would also be reset I started updating my schema directly in the Appsync console so I won't have to redo the resolvers each time I wanted to change something. Now unfortunately I somehow performed amplify push which has removed all of my resolvers again. So my question is... is there a way to restore my shema to it's previous state and bring back all the missing resolvers?
Thanks.

A: First, did you version control your resolvers? I don't AppSync versions your resolvers or keeps backups, but you might want to contact the service team immediately to see if they can restore any resolvers that only existed in the AppSync API.
Second: did you change the default resolvers, or create new ones?
If you want to override the default resolvers, you can create them in /<project_root>/amplify/backend/api/<your_api_name>/resolvers. (Create this directory if it doesn't exist.)
The below are the official Amplify documentation on overriding resolvers. There is a page directly after the linked one

Let's say you have a simple schema.graphql…

type Todo @model {
  id: ID!
  name: String!
  description: String
}

and you want to change the behavior of request mapping template for the Query.getTodo resolver that will be generated when the project compiles. To do this you would create a file named Query.getTodo.req.vtl in the resolvers directory of your API project. The next time you run amplify push or amplify api gql-compile, your resolver template will be used instead of the auto-generated template. You may similarly create a Query.getTodo.res.vtl file to change the behavior of the resolver's response mapping template.

https://aws-amplify.github.io/docs/cli-toolchain/graphql#overwriting-resolvers
There is also documentation on creating custom resolvers and attaching them as a custom resource. https://aws-amplify.github.io/docs/cli-toolchain/graphql#overwriting-resolvers


text:
Q: Can not create NSURL object because of "|" symbol in url string I need to create an object of NSURL from url string like this. It contains | symbol. The problem is that NSURL constructor always returns nil, because of | symbol. How can I create this object?

A: I think it is lowercase l, not the pipe | character.
However, you can use stringByAddingPercentEncodingWithAllowedCharacters: with NSCharacterSet.URLQueryAllowedCharacterSet() to escape invalid characters in the URL:
url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

--
let url = "https://static-maps.yandex.ru/1.x/?l=map&pt=55,1583062965,61,3948104504,pm2rdm&size=600,300"
let escapedURL = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
print(NSURL(string: escapedURL))


text:
Q: Style for custom control inheriting a base control is not applied (WPF) In a WPF project, I have an 'ExtendedButton' UserControl which inherits from Button, and overrides the control template of the button to add things like a Border, allowing for easy addition of rounded corners. I like keeping this fairly generic so as it is, it still looks fairly plain.
In a project using the project above, in the App.xaml I have created a style with a custom key, and a target type of this 'ExtendedButton'. In a control in this project I have added an 'ExtendedButton' and set its style explicitly to the style mentioned above. It appears to have reverted to the style of the base of the 'ExtendedButton', a key symptom of this being setting width etc works, but the corner radius property, while recognised, is not applied.
I've tried setting the control template in my style, which correctly adds properties like the corner radius, but doesn't allow for any customisation in my control where the button is placed. No matter what I do it seems to revert to being a base button.
An MWE of the setup described above:
The button:
ExtendedButton.xaml:
<Button
    x:Class="Win10Themables.Controls.ExtendedButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:Win10Themables.Controls"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Name="buttonExtension"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">
    <Button.Resources>
        <SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD" />
        <SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070" />
        <SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD" />
        <SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1" />
        <SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6" />
        <SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B" />
        <SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4" />
        <SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5" />
        <SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383" />
    </Button.Resources>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="FocusVisualStyle" Value="{StaticResource ThemableFocusStyle}" />
            <Setter Property="WindowChrome.IsHitTestVisibleInChrome" Value="True" />
            <Setter Property="Background" Value="{StaticResource Button.Static.Background}" />
            <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}" />
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
            <Setter Property="BorderThickness" Value="1" />
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="Padding" Value="1" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border
                            x:Name="border"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            CornerRadius="{Binding Path=CornerRadius, ElementName=buttonExtension}"
                            SnapsToDevicePixels="true">
                            <ContentPresenter
                                x:Name="contentPresenter"
                                Margin="{TemplateBinding Padding}"
                                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                Focusable="False"
                                RecognizesAccessKey="True"
                                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

ExtendedButton.xaml.cs:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Win10Themables.Controls
{
    public partial class ExtendedButton : Button
    {
        public ExtendedButton()
        {
            InitializeComponent();
        }

        public CornerRadius CornerRadius
        {
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }
        public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
          "CornerRadius", typeof(CornerRadius), typeof(ExtendedButton), new PropertyMetadata(new CornerRadius(0)));
    }
}

The style:
<Application
    x:Class="Application"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:Win10Themables.Controls;assembly=Win10Themables"
    xmlns:svgc="http://sharpvectors.codeplex.com/svgc/">
    <Application.Resources>
        <ResourceDictionary>

            <Style x:Key="RoundButtonStyle" TargetType="{x:Type controls:ExtendedButton}">
                <Setter Property="Width" Value="20" />
                <Setter Property="Height" Value="20" />
                <Setter Property="CornerRadius" Value="10" />
            </Style>

        </ResourceDictionary>
    </Application.Resources>
</Application>

A control with the button and style applied:
<UserControl
    x:Class="UserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:Win10Themables.Controls;assembly=Win10Themables"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid>
        <controls:ExtendedButton
            Style="{StaticResource RoundButtonStyle}"
            HorizontalAlignment="Left">
        </controls:ExtendedButton>
    </Grid>
</UserControl>

A: Your custom control has no default style and that's why it doesn't behave as you would expect.
ExtendedButton should be defined as a standalone class including a static constructor but no XAML file:
public class ExtendedButton : Button
{
    static ExtendedButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(ExtendedButton),
            new FrameworkPropertyMetadata(typeof(ExtendedButton)));
    }

    public CornerRadius CornerRadius
    {
        get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        set { SetValue(CornerRadiusProperty, value); }
    }

    public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
      nameof(CornerRadius), typeof(CornerRadius), typeof(ExtendedButton), new PropertyMetadata(new CornerRadius(0)));
}

You should then define the default Style for it in a ResourceDictionary named generic.xaml located in a themes folder at the root of the project:
<Style TargetType="{x:Type local:ExtendedButton}">
    <Setter Property="FocusVisualStyle" Value="{StaticResource ThemableFocusStyle}" />
    ...
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                ...
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

themes/generic.xaml is a naming convention. WPF will look for the default template in this exact location.


text:
Q: Why does the top bar notify me about flagged posts when I have no flags left? Even when I have no remaining flags, the top bar still shows me (and updates) the flagged posts counter (highlighted in blue).

Is there a special reason for this?
AFAIK I can do nothing at /tools/flagged when I have no flags left, so there is no need to catch my attention (which this blue background color does).
If I don't miss something, I think it might be a good idea to hide this notifier unless I have at least one flag available again. Resp. replace it with a un-highlighted "tools" link.


text:
Q: Error while creating qcow2 file using qemu-img When I am creating an qcow2 file using qemu-img command I am getting error as librbd.so.1 file not found. When I check for the dependencies that .so file is present in the /usr/lib folder.
Can any one solve this issue?

A: First try to install this library if not exists:
sudo apt-get install librbd1

then try you qemu-img command. If failed find the library location:
sudo find / -name  librbd.so.1

make a symlink to it
ln -s /usr/lib/librbd.so.1 /path/to/your/librd.so.1

then execute qemu-img again


text:
Q: How to create makefile to compile JavaScripts? How can I (and what tools do I need to) create a makefile that:

*

*Combine all JavaScripts '/js/*.js' (in a manual order - possibly with cat)

*Verify that combined script works against unit tests (which using qUnit)

*Minify JavaScripts

*Verify that minified script works against same unit tests

I would like makefile to work on Mac OS command line.
I will be uploading the Makefile to a GitHub repository, so I would like something that other developers will be able to use easily.

A: Here is one complex script you could look for inspiration:
https://github.com/mobilizejs/mobilize.js/blob/master/release.py
(check also README)
Generally there are always project specific use cases and one solution does not fit every project, thus everyone is doing ad hoc scripts. Also, makefile is pretty limited in the end - I recommed to pick a real scripting tool.

A: Thanks for all the suggestions, here is the solution that I have decided to go with:

*

*Makefiles - just as a shortcut really

*Google V8 - to execute JavaScript from command-line

I can easily perform minification and unit testing using JavaScript.
I have made a few minor changes (added ability to write files) to the sample shell application that comes with V8 and compiled on OS X. I plan to somehow cross-compile for OS X and Windows in both 32bit and 64-bit. I will include binaries for V8 and custom application source in the GitHub repository. I will include instructions to obtain and compile V8 for those who want to customise or recompile.
V8 will be doing all of the work (essentially). Whilst I have yet to bring all of these things together, I believe that this should work.
The only downside is that DOM based unit testing cannot be automated. It might be possible to get the DOM stuff from the Chromium project, but this is probably going to be too time consuming. I'll leave that to an enthusiastic contributor (should anybody want to).


text:
Q: Доступ к ArrayList, заполняемому в цикле, за пределами этого цикла for (int i = 0; i <= Voltage_array.length - 1; i++)
{
    if (Voltage_array[i] <= 0.7)
    {
        period = true;
    }
    if (Voltage_array[i] > 0.7 & period)
    {
        ArrayList<Double> list = new ArrayList<Double>();
        list.add(time_array[i]);
        period = false;
    }
}

Как мне сделать так, чтобы доступ к динамическому массиву был за пределами цикла и чтобы он наполнялся значениями? Так как сейчас в него записывается одно значение, а потом идет перезапись.

A: Чтобы иметь доступ к переменной вне блока, нужно её объявить на том уровне, где мы хотим с ней работать или выше.
http://kulibaba.net/programming/java/lesson4
У вас каждый раз создаётся новый объект list. Соответственно, все значения, что в нём были, стираются. И на выходе получается только один элемент.
То есть достаточно создать список перед циклом.
ArrayList<Double> list = new ArrayList <Double> ();
for (int i=0; i<=Voltage_array.length-1; i++){
    if (Voltage_array[i] <= 0.7)
        period = true;

    if (Voltage_array[i] > 0.7 & period){
        list.add(time_array[i]);
        period = false;
    }
}

A: Вынести строку ArrayList<Double> list = new ArrayList <Double> (); за пределы цикла(если, конечно, я правильно понял вопрос и доступ нужен именно к этому листу)


text:
Q: "When I return to Tokyo, we are going to visit the same places we visited on my birthday" A German guy said this sentence was wrong:

When I return to Tokyo, we are going to visit the same places we visited on my birthday.

He said you can't use the past to define places because the whole sentence is in the future.
What do you guys think?

A: No, that's completely correct English. I can't even figure out why your German friend would think that was wrong.
"In the future, you will visit some places. You have visited those places before." That meaning is unambiguously communicated by your sentence - there is no other way to read it.
It perhaps sounds a little clearer to say "We are going to visit the same places which we visited on my birthday", though.


text:
Q: 3 row div with 100% height content always i have 3 rows div layout with footer on bottom of page, but i need to have content div always full size from header to footer.
inside the content div i have also a iframe, and i need to have this iframe always at 100% height of conent, then 100% heigt of space between header and footer.
this is my (sample) page:

                    logo

 Home

                <button name="menu" type="button" id="menuopen"> Menu
                </button>

this is my css:
html, body {
font-family: sans-serif;
padding: 0em;
margin: 0em;
color: #444;
background: #fff;
text-align: center;
height: 100%; /* Important */
width: 100%;
}

#container {
margin: 0px auto;
text-align: center;
height: 100%;
}

thanks advance

A: Using this as your markup:

HEADER

hi

and this as your CSS:
html, body {
    height: 100%;
    margin: 0px;
    padding: 0px;
}

#wrapper {
    width: 100%;
    height: 100%;
    margin: auto;
    position: relative;
}

#header {
    height: 40px;
    background-color: green;
    color: #fff;
}

#content {
    position:absolute;
    bottom:40px;
    top: 40px;
    width:100%;
    overflow: auto;
    background-color: #333;
    color: #666;
}

#footer {
    height: 40px;
    width:100%;
    position:absolute;
    bottom:0;
    background-color: blue;
    color: #fff;
}

Does that get you on your way?

A: This Header, Body, Footer with CSS... will show you how.
But really this is simple enough that even if you didn't know...

Also in the comments section Elgoog has given a link to an answer already answered on this site.
Please do your research.


text:
Q: How to increase and decrease a counter from one button - click and click again jQuery This is the code that I am currently using:
<script>
   $(".lk").click(function(){
   $(this).find("#lke").html(function(i, val) { return val*1+1 });
   });

   $(".lk").click(function(){
   $(this).find("#lke").html(function(i, val) { return val*1-1 });
   });
</script>

When the user clicks on the button, the value of #lke increases by 1. When he clicks again, the value decreases by 1. The code that I am currently using does not work so how would I fix this?

A: Your code doesn't work because you assign two events for every click - one which increases the value and one which decreases it, so nothing happens.
You could use an external variable such as toAdd to determine which action to do:
var toAdd = 1;
$(".lk").click(function(){
    newValue = oldValue + toAdd;
    toAdd *= -1;
    ...
});

A: You can use an external var to decide if you have to increment o decrement the value
<script>
   var increment = true;
   $(".lk").click(function(){
      var lke = $(this).find("#lke"),
          value = parseInt(lke.html()) || 0;

      lke.html( increment ? value + 1 : value - 1);
      increment = !increment;
   });
</script>

A: Try something like this:
$(".lk").click(function() {
   if ($(this).hasClass('clicked')) {
       $(this).removeClass('clicked'));
       $(this).find("#lke").html(function(i, val) { return val*1-1 });
   } else {
       $(this).addClass('clicked');
       $(this).find("#lke").html(function(i, val) { return val*1+1 });
   }
});

You could also use a data attribute instead of checking for a class aswell.
Or use toggleClass().
$(".lk").click(function() {
   if ($(this).hasClass('clicked')) {
       $(this).toggleClass('clicked'));
       $(this).find("#lke").html(function(i, val) { return val*1-1 });
   } else {
       $(this).toggleClass('clicked');
       $(this).find("#lke").html(function(i, val) { return val*1+1 });
   }
});

A: You put two call of the same object, try this instead
<script>
   var val = 0; // Put the original value
   var negative = false;
   $( document ).ready(function() { // You need to declare document ready
      $(".lk").click(function(){
         val = val + ((negative) ? -1 : 1); // Change if its positive or negative
         negative = (negative) ? false : true;
         $("#lke").text(val); // Adjust the html ?
      });
   });
</script>


text:
Q: Laravel always return 404 I use Laravel as backend (API REST) and AngularJS as frontend (consuming API).
I would like to have redirects:
/api --> /backend/public (Laravel)
/    --> /frontend/app   (AngularJs)

Frontend runs without problem, but Laravel always return 404 for existing routes (NotFoundHttpException in RouteCollection.php).
Where I make a mistake?
My folder structure:
/var/www
-- .htaccess (1)
-- frontend
---- app
------ index.html
------ .htaccess (2)
-- backend
---- public
------ index.php
------ .htaccess (3)

.htaccess (1)
<IfModule mod_rewrite.c>
   <IfModule mod_negotiation.c>
      Options -MultiViews
   </IfModule>

   RewriteEngine On

   # Redirect Trailing Slashes...
   RewriteRule ^(.*)/$ /$1 [L,R=301]

   # Backend
   RewriteRule ^api(.*) backend/public/$1 [L]

   # Frontend
   RewriteRule ^(.*) frontend/app/$1 [L]
</IfModule>

.htaccess (2)
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [L]
</IfModule>

.htaccess (3)
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteBase /api/

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Apache configuration
<VirtualHost *:80>
    ...
    DocumentRoot /var/www/
    <Directory />
        Options FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
    ...
</VirtualHost>

Part of backend/app/Http/routes.php
<?php

Route::get('/', function()
{
    return 'Hello World';
});

Route::get('/test', function()
{
    return 'Hello Test';
});

Every request to backend (http://domain.com/api*) return NotFoundHttpException in RouteCollection.php line 145 from Laravel (so backend/public/index.php is running), for example:
http://domain.com/api
http://domain.com/api/test

Thank you for your time.

A: You need wrap your routes inside a route group with a prefix of api. For example:
Route::group(['prefix' => 'api'], function(){
    Route::get('/', function()
    {
        return 'Hello World';
    });

    Route::get('/test', function()
    {
        return 'Hello Test';
    });
});

The reason is your Laravel application is not served at root domain but inside a child folder. Therefore, the URI of each request will start by api.


text:
Q: A few lines in my image save function don't run after the first time the image is saved I'm making an app that allows you to have a textview over an image, then save that as a brand new image. I'm having a problem keeping the new extended area above the image white to simulate the textview.
Here's what the basis of the app is:

Heres what it looks like after I save it the first time:

and heres what it looks like after i save it more than once while the app is open:

(ignore the white border that's from screenshotting the simulator)
This is my save function, it extends the saved image the same amount as the textview (if its actively showing) then it colors the extended area white. it then super imposes the textview text over the white. For some reason it will only color in the extended area white on the first time the image is saved. after that the backgroundColor.setFill() doesn't activate as seen in the screen shots above:
 @IBAction func save(_ sender: Any) {
    guard image != nil else { return }

    let offset = scrollView.contentOffset
    let screenHeight = screenSize.height

    let normalSize = CGSize(width: scrollView.bounds.size.width, height: scrollView.bounds.size.height)
    let textViewWithImageSize = CGSize(width: scrollView.bounds.size.width, height: ((screenHeight * 0.17) + scrollView.bounds.size.height))
    var yPos: Int = Int(-offset.y)

    //if textView is active or not and the different y position for saved image to include the textview if it is active
    // screenHeight * 0.17 is the dynamic height of the textview per device.

    if textView.isHidden == true {
        UIGraphicsBeginImageContextWithOptions(normalSize, true, UIScreen.main.scale)
        textView.text = ""
        yPos = Int(-offset.y)
    }else if textView.isHidden == false {
        yPos = Int(-offset.y + (screenHeight * 0.17))
        UIGraphicsBeginImageContextWithOptions(textViewWithImageSize, true, UIScreen.main.scale)

        //sets saves text area background to white, extendind the image area on its own colored the void black.
        let backgroundColor: UIColor = UIColor.white
        backgroundColor.setFill()
        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: (offset.y - (screenHeight * 0.17)), width: scrollView.bounds.size.width, height: scrollView.bounds.size.height))
    }

    UIGraphicsGetCurrentContext()!.translateBy(x: -offset.x, y: CGFloat(yPos))
    scrollView.layer.render(in: UIGraphicsGetCurrentContext()!)

    let textColor = UIColor.red
    let textFont = UIFont(name: "Helvetica", size: 14)!
    let textFontAttributes = [NSFontAttributeName: textFont,NSForegroundColorAttributeName: textColor] as [String : Any]
    let rect = CGRect(x: offset.x + 5, y: (offset.y + 5 - (screenHeight * 0.17)), width: scrollView.bounds.size.width, height: scrollView.bounds.size.height)

    textView.text.draw(in: rect, withAttributes: textFontAttributes)

    image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
    centerScrollViewContents()

 let alert = UIAlertController(title: "Image Saved", message: "your image has been saved", preferredStyle: .alert)
    self.present(alert, animated: true, completion: nil)
    alert.addAction(UIAlertAction(title: "Neat", style: .default, handler: nil))
}

above is my entire save and render image function, and below is the simple case switch I use to switch whether the textview is present or not:
   @IBAction func frame(_ sender: Any) {
     guard image != nil else { return }

    switch currentFrame{
    case 0:
        textView.isHidden = true
    case 1:
        textView.isHidden = false
    default:
        break
    }
    currentFrame += 1
    if currentFrame > 1 {
        currentFrame = 0
    }
}

I imagined setting the if statements up in the save function based on whether the textview is hidden or not would be the cleanest solution, which actually seems to be working. but the
backgroundColor.setFill()

Is being bypassed for some reason after the initial save, but the image still extends and super imposes the text correctly.
Im at a loss and any advice would be greatly appreciated.

A: I found it. This line:
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: (offset.y - (screenHeight * 0.17)), width: scrollView.bounds.size.width, height: scrollView.bounds.size.height))

The y: needed to be
y: 0 - (screenHeight * 0.17))

instead of trying to match the scrollview image offset like I was trying to do.


text:
Q: How to draw graphs in LaTeX? I need to draw simple graph (for example Petersen Graph) in LaTeX. I am using Kile in Ubuntu. I exactly don't know that which package should I use. Any suggestion with example is highly expected.

A: As there lacks an answer with pstricks, here a very simple code for the Petersen graph; it uses pst-poly:
\documentclass[12pt, pdf, x11names]{standalone}%

\usepackage{pstricks-add}
\usepackage{pst-poly}

\begin{document}

\begin{pspicture*}(-1.1,-1)(1.1,1.1)
\providecommand{\PstPolygonNode}{%
\psdots[dotstyle=o, dotsize=3pt,fillstyle=solid, fillcolor=cyan](1;\INode)}
\psset{linewidth=0.6pt}
\rput(0,0){\PstPentagon[PolyName=A]}
\rput(0,0){\PstPentagon[unit=5mm, PolyOffset=2,PolyName=B]}
\multido{\i=1+1}{5}{\ncline[nodesep=1.5pt]{A\i}{B\i}}
\end{pspicture*}

\end{document}

A: I think the best approach is to use the tkz-berge from Altermundus. You can also find a complete guide here.
However, to make a simple example just using TikZ, you can follow this approach:
\documentclass {article}

% example taken from
% http://www.guitex.org/home/images/doc/GuideGuIT/introingtikz.pdf

\usepackage {tikz}
\usetikzlibrary {positioning}
%\usepackage {xcolor}
\definecolor {processblue}{cmyk}{0.96,0,0,0}
\begin {document}
\begin {center}
\begin {tikzpicture}[-latex ,auto ,node distance =4 cm and 5cm ,on grid ,
semithick ,
state/.style ={ circle ,top color =white , bottom color = processblue!20 ,
draw,processblue , text=blue , minimum width =1 cm}]
\node[state] (C)
{$1$};
\node[state] (A) [above left=of C] {$0$};
\node[state] (B) [above right =of C] {$2$};
\path (A) edge [loop left] node[left] {$1/4$} (A);
\path (C) edge [bend left =25] node[below =0.15 cm] {$1/2$} (A);
\path (A) edge [bend right = -15] node[below =0.15 cm] {$1/2$} (C);
\path (A) edge [bend left =25] node[above] {$1/4$} (B);
\path (B) edge [bend left =15] node[below =0.15 cm] {$1/2$} (A);
\path (C) edge [bend left =15] node[below =0.15 cm] {$1/2$} (B);
\path (B) edge [bend right = -25] node[below =0.15 cm] {$1/2$} (C);
\end{tikzpicture}
\end{center}
\end{document}

which leads to:

It is an example of a Markov Chain in which several TikZ options are used. In the same guide, you will find an example in which nodes are placed in a matrix.

A: You can use the tkz-berge package . This package uses TikZ it's possible to add all the commands of TikZ.
Here the three classic forms of Petersen's graph
\documentclass[11pt]{scrartcl}
\usepackage{tkz-berge}

\begin{document}
\begin{tikzpicture}[scale=.5]
\GraphInit[vstyle=Art]
\SetGraphArtColor{red}{olive}
\grPetersen[form=1,RA=5,RB=3]%
\end{tikzpicture}
\begin{tikzpicture}[scale=.4]
   \GraphInit[vstyle=Art]
   \SetGraphArtColor{red}{olive}
   \grPetersen[form=2,RA=7,RB=3]%
\end{tikzpicture}

\begin{tikzpicture}[scale=.5]
   \GraphInit[vstyle=Art]
   \SetGraphArtColor{red}{olive}
   \grPetersen[form=3,RA=7]%
\end{tikzpicture}
\end{document}

I wrote a document with some classic named graphs. It's inside the your distribution (>2011 I think)
texdoc NamedGraphsin the terminal
I added the sources and all the examples you can also find them here
NamedGraphs

A: Here an example to draw the Petersen's graph only with TikZ
I try to structure correctly the code. The first scope is used for vertices ans the second one for edges. The only problem is to get the edges with `mod``
       \pgfmathtruncatemacro{\nextb}{mod(\i+1,5)}
       \pgfmathtruncatemacro{\nexta}{mod(\i+2,5)}

The complete code
  \documentclass[border=6pt]{standalone}
  \usepackage{tikz}

  \begin{document}

  \begin{tikzpicture}
    \begin{scope} [vertex style/.style={draw,
                                       circle,
                                       minimum size=6mm,
                                       inner sep=0pt,
                                       outer sep=0pt,
                                       shade}]
      \path \foreach \i in {0,...,4}{%
       (72*\i:2) coordinate[vertex style] (a\i)
       (72*\i:4) coordinate[vertex style] (b\i)}
       ;
    \end{scope}

     \begin{scope} [edge style/.style={draw=gray,double=white}]
       \foreach \i  in {0,...,4}{%
       \pgfmathtruncatemacro{\nextb}{mod(\i+1,5)}
       \pgfmathtruncatemacro{\nexta}{mod(\i+2,5)}
       \draw[edge style] (a\i)--(b\i);
       \draw[edge style] (a\i)--(a\nexta);
       \draw[edge style] (b\i)--(b\nextb);
       }
     \end{scope}

  \end{tikzpicture}
  \end{document}

A: In case you do not want to do the layout yourself, you can use Graphviz to do so.
That will result in a ".dot" file, that can be converted to Latex with dot2tex.
I just used my GraphvizFiddle tool to get "circo" layout for Petersen graph and verified that dot2tex works. Here is share link for the Petersen graph, switch output from "svg" to "dot" and press "Draw" button to get the Petersen ".dot" file. The tex output uses "tikzpicture" as well.


text:
Q: not understanding of async await concept I do not understand when I read the Microsoft documents about async and await working, as it says

Async methods are intended to be non-blocking operations. An await
  expression in an async method doesn't block the current thread while
  the awaited task is running. Instead, the expression signs up the rest
  of the method as a continuation and returns control to the caller of
  the async method.

so consider my code:
public  Form1()
{
    InitializeComponent();
    AsyncTest();
    Test(1);
}

private async void AsyncTest()
{
    HttpClient client = new HttpClient();
    var ss =  TT(2);

    var s = await ss;

    for (int i = 0; i < 10; i++)
    {
        //loop
    }
}

private async Task<int> TT(int i)
{
    while (true)
    {
        if (i  > 1000000000)
            break;
        i++;
     }

     return  i;
    }
}

when ever I call  AsyncTest(), it just waits behind TT method as it specified with await key, but what does it mean it return control to the main caller??
it is not been returned to the form1, if TT is an infinite loop it just remains forever.
thanks

A: It seems to me you are a newbee to async-await. You violate several rules about how to use async-await.
To make a function async do the following:

*

*Declare the function async

*Return Task<TResult> instead of TResult; return Task instead of void

*ONLY EXCEPTION: event handlers return void instead of Task

*there should be one await inside your async function. Your compiler will warn you if you omit this.

*Make sure that all async functions that you call are awaited for before you return

Guideline: let async be a suffix to your async functions. This allows you to create a sync and an async function that do the same: void MyTest() and Task MyTestAsync()
Following these rules, you can't call an async function from within a constructor. As you are using Winforms your code could be like this:
public  Form1()
{
    InitializeComponent();
}

public async void OnButton1_Clicked(object sender, ...)
{   // because this is an event handler the return value is void

    // Start the first test and await until ready
    await TestAsync();

    // Start the second test and await until ready:
    int i = await TestAsync(1);
}

If you call an async function you know that somewhere inside this function is an await. If you have meaningful things to do while the inner function is awaiting, do not await yet. Do your useful things after the call and await the returned Task as soon as you need the result:
public async void OnButton2_Clicked(object sender, ...)
{
    // Start a test, but don't await yet
    var task1 = TestAsync(1);

    // if here, function TestAsync is awaiting somewhere
    // it is not finished yet, so you can't use the result of it
    // But you can do Something else:
    DoSomethingElse();

    // if here you really need the result of TestAsync, await for it
    int i = await task1;

    // if here you know that TestAsync is finished, i has the proper return value
}

You don't have to start and await the tasks one by one, you can start several tasks and await for them as soon as you need the results:
public async void OnButton3_Clicked(object sender, ...)
{
    // start several tasks. Don't await yet:
    var task1 = TestAsync(1);
    var task2 = TestAsync(2);
    var task3 = TestAsync(3);

    DoSomethingElse();

    // if here I need the results of all three tasks:
    var myTasks = new Task[] {task1, task2, task3};
    await Task.WhenAll(myTasks);
}

An article that really helped me understanding async-await is this interview with Eric Lippert, where he compares async-await with a cook making breakfast. If a cook has to wait for the water to boil, he doesn't wait idly, but looks around to see if he can do other things. Search somewhere in the middle for async-await.
Another article that helped me following the guidelines of async-await is Async and Await by the ever so helpful Stephen Cleary


text:
Q: Simple yet slow mongodb query I think I'm missing out on something - I have a collection of about 2GB, trying to find documents by a specific value (appearing as a number or string)
I have about 14K documents in the collection.
This is the query, quite basic:
db.e_69.find({
    "field_groups.fields_data" :
    {
    "$elemMatch": {
        "field_id": "502",
        "value": {"$in": ["223384",223384]}
    }
}})

I'm using mongoDB 3.2, small AWS server with two replica sets.
I know this is not much info - but as I'm new I'm not sure what info is required and will be happy to add according to what's needed. It's just odd for me that such a query from 14K docs would take over 3 seconds.
Am I missing something?
Thanks!

A: Sort by number works faster, but you have an array, so it will slow your query down, cause it has 2 types in it.
I would suggest to add a simple boolean column and during addition of new doc if doc has "223384",223384, just set this boolean column to true value.
Then your query will be simple and search fast.
I hope that helps.


text:
Q: Como capturar o erro: SERVER RESPONDS REQUEST-URI TOO LONG, STATUS = 414 Estou fazendo um aplicativo de chat, que abre um arquivo (via file input) e então converte em DATA URI. (Estou usando PubNub) quando eu envio a string, recebo um erro de 'URI too long'. Como eu posso compactar a URI, ou ao mínimo capturar esse erro? (try..catch parece não funcionar)

//LOCAL GLOBAL VAR TECHNIQUE
  var rethtml = "";

  function encodeImageFileAsURL() {

    var filesSelected = document.getElementById('inputImg').files;
    if (filesSelected.length > 0) {
      var fileToLoad = filesSelected[0];

      var fileReader = new FileReader();

      fileReader.onload = function(fileLoadedEvent) {
        var srcData = fileLoadedEvent.target.result; // <--- data: base64

        var newImage = document.createElement('img');
        newImage.src = srcData;

        //shortening the name, and also making the local variable public (for other purposes)
        rethtml = newImage.outerHTML;

        //CHANGING LOCAL IMG
        document.getElementById("imgTestLocal").innerHTML=rethtml;

        //SENDING TO SERVER CHAT
      pubnub.publish({channel : channel,message : rethtml});

      }
      fileReader.readAsDataURL(fileToLoad);

    }
  }
.fileContainer {
    overflow: hidden;
    position: relative;
 width:50px;
 height:50px;
}

img {

  display:inline-block;
  width:30px;
  height:30px;
}

.fileContainer [type=file] {
    cursor: inherit;
    display: block;
    font-size: 999px;
    filter: alpha(opacity=0);
    min-height: 100%;
    min-width: 100%;
    opacity: 0;
    position: absolute;
    right: 0;
    text-align: right;
    top: 0;
}

#bwui_file{

 background-color:#222;
 color:#fff;
 display:block;
 padding:0;
 margin:10px;
 width:30px;
 height:30px;
 transition:500ms;
 font-size:15pt;
 text-align:center;
 border:none;
 outline:none;
 border-radius:50%;
}

.fileContainer:hover > #bwui_file {

 margin:5px;
 width:40px;
 height:40px;
 background-color:#fff;
 color:#222;
 font-size:20pt;
 transition:500ms;
}

Ele funciona perfeitamento aqui (carregando a imagem localmente) mas quando eu tento enviar uma imagem muito pesada, somente a local carrega..

<input type="button" value="➕" id="bwui_file"/>

<input id="inputImg" type="file" onchange="encodeImageFileAsURL();" />

LOCAL:

PUBNUB (preciso deste para o chat):


text:
Q: Can you use self in the assignment of a default parameter? I am trying to convert some java code to a python equivalent so that I can interface between the two. So in Java I have some code like this:
public int[] toArray(boolean order) {
    return toArray(order, this.length());
}
public int[] toArray(boolean order, int length) {
    ...
}

and a logical equivalent in python might look like this:
def to_array(self, order):
  return self.to_array(order, self.length())
def to_array(self, order, length):
  ...

except... python doesn't allow function overloading, instead it allows for default parameters, so, again, it would seem logical that you would want to do something like this:
def to_array(self, order, length = self.length()):
  ...

however... this is also not allowed in python, likely since self doesn't really "exist" until within the body of the function.
so what would be the correct way to do this in python? or is it just not possible?
EDIT: I realized I used void functions in my java code that is supposed to return a value so now they return int[]

A: The pythonic way to do this would be to use None as default value, then test against it:
def to_array(self, order, length=None):
    if length is None:
        length = self.length()


text:
Q: socket.io not loading on heroku I'm using node.js, express, socket.io, mongodb, mongoose, mongolab and heroku to build simple chat.
Everything work great on the localhost (without heroku), but when I deploy my app on the heroku the socket.io.js not loading.
https://prnt.sc/gm6fz0
I've read about 10-20 other similiar questions and tried other variations, but socket.io.js still won't load.
app.js - server side
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var mongoose = require('mongoose');
var mongodb = require('mongodb');

server.listen(8080);

var uri = 'mongodb://username:password@ds141264.mlab.com:41264/chat';

var index = require('./routes/index');
var users = require('./routes/users');

mongoose.connect(uri, function(err){
  if(err) {
    console.log(err);
  } else {
    console.log('connected to mongo db');
  }
});

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function callback () {

  var chatSchema = mongoose.Schema ({
    msg: String,
    created: {type: String, default: function(){return new Date()}}
  });

  var Chat = mongoose.model('Message', chatSchema);

  io.on('connection', function(socket){
    console.log('a user connected');
    var query = Chat.find({});
    query.sort({'_id': -1}).limit(10).exec(function(err, docs){
      if (err) throw err;
      console.log('sending old msgs');
      socket.emit('load old msgs', docs);
    });

    socket.on('disconnect', function(){
      console.log('user disconnected');
    });
    socket.on('chat', function(msg){
      console.log('message: ' + msg);
      var newMsg = new Chat({ msg: msg });
      newMsg.save(function(err){
        if(err) throw err;
        io.emit('chat', msg);
      });
    });
  });
});

app.use(express.static(__dirname + '/public'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

global.js - client-side
var socket = io.connect();

$('#send-message-btn').click(function () {
    var msg = $('#message-box').val();
    socket.emit('chat', msg);
    $('#message-box').val('');
    return false;
});

socket.on('chat', function (msg) {
  var dadd = new Date;
  $('#messages').append($('<time>').text(dadd));
  $('#messages').append($('<p>').text(msg));
});

socket.on('load old msgs', function(docs){
  for(var i=0; i < docs.length; i++) {
    $('#messages').prepend($('<p>').text(docs[i].msg));
    $('#messages').prepend($('<time>').text(docs[i].created));
  }
});

A: As Per the documentation provided on heroku (Apps using Socket.io should enable session affinity. If you plan to use node's Cluster module or to scale your app to multiple dynos, you should also follow Socket.io's multiple-nodes instructions.), You Basically have to execute the following command from you project directory.
heroku features:enable http-session-affinity

Best,
Daksh Miglani


text:
Q: Can't read property "useLayoutEffect" of undefined from vendor.js file This error doesn't appear in localhost, it only appears in the dev / stage / etc environments.
vendors.c058a202.chunk.js:2 Uncaught TypeError: Cannot read property 'useLayoutEffect' of undefined
    at vendors.c058a202.chunk.js:2
    at vendors.c058a202.chunk.js:2
    at Module.<anonymous> (vendors.c058a202.chunk.js:2)
    at i (client.991c6b9d.js:formatted:38)
    at Object.<anonymous> (vendors.c058a202.chunk.js:2)
    at i (client.991c6b9d.js:formatted:38)
    at Object.<anonymous> (vendors.c058a202.chunk.js:2)
    at i (client.991c6b9d.js:formatted:38)
    at Object.<anonymous> (vendors.c058a202.chunk.js:2)
    at i (client.991c6b9d.js:formatted:38)

Any thoughts on where to look? I didn't see any package.json updates. We don't actually push package-lock.json to the repo. The docker container runs nginx with static webpack build files, but running that locally doesn't reproduce the issue either.


text:
Q: Top Bar broken on the Tour page The Tour Page on the new MSE is busted for me. The link to /review works, but the various pop-out menus don't. The main multicollider just takes me to https://stackexchange.com/ when I click it, and the inbox, rep listing, and help menus don't do anything. Seems to be a JS error getting thrown up in the console on first loading the page:

System Info: Win7, IE11, no toolbars, no add-ons, no userscripts, etc.

A: I fixed this late last night - needed some JavaScript love with differing content


text:
Q: Contest geometry problem $|AM|=|CM|$
$\angle BCA = 15^{\circ}$
$\angle CBM = \angle ABH$
$\angle BHC = 90^\circ$
Find $|AC|$

The solution states that $\overline{BM}$ is the isogonal conjugate of $\overline{BH}$ but I did not understand this at all. Could you explain this to me or maybe find another way to solve it?

A: $\overline{BM}$ is the Isogonal conjugate of $\overline{BH}$ means BM is pass through the circumcentre as  $\overline{BH}$ is pass the orthocentre. so $M$ is circumcentre $\implies \angle CBA= 90^\circ $. now you can find every thing.

A: Call the angle at $A$ $\alpha$ and let $O$ be the circumcenter.
Clearly, $\measuredangle HBA = 90-\alpha$.
Now, by the inscribed angle theorem: $\measuredangle CBO = \frac{180-\measuredangle BOC}2 =90-\measuredangle BAC = 90- \alpha$
Therefore, both $M$ and $O$ lie on the line $BM$ as well as on the perpendicular bisector of $CA$. This means that either the triangle isosceles or $M=O$. In the first case, $M=H$ which is clearly impossible from the given distance.
However, if $M=O$, the triangle has be orthogonal at $B$. The similarity of $ABC$ and $AHB$ now permits to calculate all angles.
You can finally use the sine law and the given distance to calculate $BH$, $AH$ and $CH$ which gives you $AC$.


text:
Q: Styling pandas dataframe to show negative numbers in red I am trying to following the instructions here to apply styling to a pandas dataframe.
However I can't understand how to combine the elements of
set_table_styles()

and
df.style.applymap()

Here is my code:
df = pd.DataFrame([[1,2,3,4], [5,6,7,8], [3,-5,6,7]], columns=['Foo', 'Bar', 'Buzz', 'Fuzz'], index=['First', 'Second','Third'])

I can apply the negative red coloring:
def style_negative(v, props=''):
    return props if v < 0 else None

df.style.applymap(style_negative, props='color:red;')

Which works as expected:

And here is my styling code:
styles = [
    dict(selector="tr:hover",
                props=[("background", "#D6EEEE")]),
    dict(selector="th", props=[("color", "#fff"),
                               ("border", "1px solid #eee"),
                               ("padding", "12px 35px"),
                               ("border-collapse", "collapse"),
                               ("background", "#1D4477"),
                               ("font-size", "18px")
                               ]),
    dict(selector="td", props=[("color", "#000000"),
                               ("border", "1px solid #eee"),
                               ("padding", "12px 35px"),
                               ("border-collapse", "collapse"),
                               ("font-size", "15px")
                               ]),
    dict(selector="table", props=[
                                    ("font-family" , 'Helvetica'),
                                    ("margin" , "25px auto"),
                                    ("border-collapse" , "collapse"),
                                    ("border" , "1px solid #eee"),
                                    ("border-bottom" , "2px solid #00cccc"),
                                      ]),
    dict(selector="caption", props=[("caption-side", "bottom")]),
    dict(selector="tr:nth-child(even)", props=[
        ("background-color", "#f2f2f2"),
    ]),
]
df = df.set_table_styles(styles).format(precision=2)

Which gives:

But I don't know how to combine the two, such that I get the table styling as well as the negative numbers showing as red.

A: You can chain both methods, but first remove color parameter for td elements like mentioned @Attack68
:
styles = [
    dict(selector="tr:hover",
                props=[("background", "#D6EEEE")]),
    dict(selector="th", props=[("color", "#fff"),
                               ("border", "1px solid #eee"),
                               ("padding", "12px 35px"),
                               ("border-collapse", "collapse"),
                               ("background", "#1D4477"),
                               ("font-size", "18px")
                               ]),
    dict(selector="td", props=[("border", "1px solid #eee"),
                               ("padding", "12px 35px"),
                               ("border-collapse", "collapse"),
                               ("font-size", "15px")
                               ]),
    dict(selector="table", props=[
                                    ("font-family" , 'Helvetica'),
                                    ("margin" , "25px auto"),
                                    ("border-collapse" , "collapse"),
                                    ("border" , "1px solid #eee"),
                                    ("border-bottom" , "2px solid #00cccc"),
                                      ]),
    dict(selector="caption", props=[("caption-side", "bottom")]),
    dict(selector="tr:nth-child(even)", props=[
        ("background-color", "#f2f2f2"),
    ]),
]

(df.style.applymap(style_negative, props='color:red;').set_table_styles(styles))

(df.style.applymap(style_negative, props='color:red;')
         .set_table_styles(styles))


text:
Q: Как передать аргумент COLOR из функции конвертированный в 0x? нужен способ решения задачи.
На вход мы получаем команду со следующими аргументами:
async def create_family(inter, familyname, colour, leader: disnake.Member):

В colour поступает HTML код цвета, который нужно конвертировать с помощью 0x.
Пример: на вход получаем AEEEEEE, на выходе должно получится 0xAEEEEE, пытался сделать так:
familyrole = await guild.create_role(name=familyname, colour=f'0x{colour}')

Не вышло.
Попробовал по другому:
sep = 0x
colourforsep = colour
sep.join(colourforsep)

Не получилось, выдает ошибку в строке familyrole = await guild.create_role(name=familyname, colour=f'0x{colour}')
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'value'
Помогите решить!!!
Пробовал решение пользователя из комментариев:
class Families:
    def str_to_hex(myStr):
        base16INT = int(myStr, 16)
        hex_value = hex(base16INT)
        return hex_value

    @bot.slash_command()
    async def create_family(inter, familyname, colour, leader: disnake.Member):
        for role in inter.author.roles:
            if role.id in high_perms:
                guild = inter.guild
                familyid = uuid.uuid4()
                availableColor = str_to_hex(colour)
                familyrole = await guild.create_role(name=familyname, colour=disnake.Colour(availableColor))

A: Если я правильно понял, то туда надо передать hex. Написал небольшую функция перевода строки в hex. Попробуйте так
def str_to_hex(myStr):
    base16INT = int(myStr, 16)
    hex_value = hex(base16INT)
    return int(hex_value,0)

async def create_family(inter, familyname, colour, leader: disnake.Member):
    .......
    availableColour = str_to_hex(colour)
    familyrole = await guild.create_role(name=familyname, colour=discord.Colour(availableColour))


text:
Q: Oracle xml_dom.writeToClob does ignore the character set I'm trying to generate a xml file using oracle. After generating the xml using dbms_xmldom, it is stored in a CLOB and later written to a table.
The problem is that the character set ('UTF-8') is not included in the header even though it is specified using setCharset() procedure.
Following is the oracle script,
declare
  export_file_   CLOB ;
  str_export_file_ xmldom.DOMDocument;
  main_node xmldom.DOMNode;
  root_node xmldom.DOMNode;
  root_elmt xmldom.DOMElement;

begin

    str_export_file_ := xmldom.newDOMDocument;
    xmldom.setVersion(str_export_file_, '1.0');
    xmldom.setCharset(str_export_file_ , 'UTF-8');
    main_node := xmldom.makeNode(str_export_file_);
    root_elmt := xmldom.createElement(str_export_file_,'TextTranslation');
    xmldom.setAttribute( root_elmt, 'version' ,'1.0');
    xmldom.setAttribute( root_elmt, 'language' ,'ja');
    xmldom.setAttribute( root_elmt, 'module' ,'DEMOAND');
    xmldom.setAttribute( root_elmt, 'type' ,'VC');
    root_node := xmldom.appendChild(main_node, xmldom.makeNode(root_elmt));

   export_file_ :=' ';
   xmldom.writeToClob( str_export_file_,export_file_,'UTF-8');

   dbms_output.put_line ( export_file_ );
end;

The output is ,
<?xml version="1.0"?>
<TextTranslation version="1.0" language="ja" module="DEMOAND" type="VC"/>

A: Nothing wrong so far. As a workaround you can use
export_file_ := REPLACE(
     export_file_
    ,'<?xml version="1.0"?>'
    ,'<?xml version="1.0" encoding="UTF-8" ?>'
);


text:
Q: Making balls bounce off each other (openGL) I'm trying to make an application where balls bounce off the walls and also off each other. The bouncing off the walls works fine, but I'm having some trouble getting them to bounce off each other. Here's the code I'm using to make them bounce off another ball (for testing I only have 2 balls)
 // Calculate the distance using Pyth. Thrm.
        GLfloat x1, y1, x2, y2, xd, yd, distance;
        x1 = balls[0].xPos;
        y1 = balls[0].yPos;
        x2 = balls[1].xPos;
        y2 = balls[1].yPos;

        xd = x2 - x1;
        yd = y2 - y1;

        distance = sqrt((xd * xd) + (yd * yd));

        if(distance < (balls[0].ballRadius + balls[1].ballRadius))
        {
            std::cout << "Collision\n";
            balls[0].xSpeed = -balls[0].xSpeed;
            balls[0].ySpeed = -balls[0].ySpeed;

            balls[1].xSpeed = -balls[1].xSpeed;
            balls[1].ySpeed = -balls[1].ySpeed;

        }

What happens is that they randomly bounce, or pass through each other. Is there some physics that I'm missing?
EDIT: Here's the full function
// Callback handler for window re-paint event
void display()
{
    glClear(GL_COLOR_BUFFER_BIT);    // Clear the color buffer
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);

    // FOR LOOP
    for (int i = 0; i < numOfBalls; i++)
    {
        glLoadIdentity();                // Reset model-view matrix
        int numSegments = 100;
        GLfloat angle = 0;
        glTranslatef(balls[i].xPos, balls[i].yPos, 0.0f);  // Translate to (xPos, yPos)

        // Use triangular segments to form a circle
        glBegin(GL_TRIANGLE_FAN);
        glColor4f(balls[i].colorR, balls[i].colorG, balls[i].colorB, balls[i].colorA);
        glVertex2f(0.0f, 0.0f);       // Center of circle

        for (int j = 0; j <= numSegments; j++)
        {
            // Last vertex same as first vertex
            angle = j * 2.0f * PI / numSegments;  // 360 deg for all segments
            glVertex2f(cos(angle) * balls[i].ballRadius, sin(angle) * balls[i].ballRadius);
        }
        glEnd();

        // Animation Control - compute the location for the next refresh
        balls[i].xPos += balls[i].xSpeed;
        balls[i].yPos += balls[i].ySpeed;

        // Calculate the distance using Pyth. Thrm.
        GLfloat x1, y1, x2, y2, xd, yd, distance;
        x1 = balls[0].xPos;
        y1 = balls[0].yPos;
        x2 = balls[1].xPos;
        y2 = balls[1].yPos;

        xd = x2 - x1;
        yd = y2 - y1;

        distance = sqrt((xd * xd) + (yd * yd));

        if(distance < (balls[0].ballRadius + balls[1].ballRadius))
        {
            std::cout << "Collision\n";
            balls[0].xSpeed = -balls[0].xSpeed;
            balls[0].ySpeed = -balls[0].ySpeed;

            balls[1].xSpeed = -balls[1].xSpeed;
            balls[1].ySpeed = -balls[1].ySpeed;

        }
        else
        {
            std::cout << "No collision\n";
        }

        // Check if the ball exceeds the edges
        if (balls[i].xPos > balls[i].xPosMax)
        {
            balls[i].xPos = balls[i].xPosMax;
            balls[i].xSpeed = -balls[i].xSpeed;
        }
        else if (balls[i].xPos < balls[i].xPosMin)
        {
            balls[i].xPos = balls[i].xPosMin;
            balls[i].xSpeed = -balls[i].xSpeed;
        }

        if (balls[i].yPos > balls[i].yPosMax) {
            balls[i].yPos = balls[i].yPosMax;
            balls[i].ySpeed = -balls[i].ySpeed;
        }
        else if (balls[i].yPos < balls[i].yPosMin)
        {
            balls[i].yPos = balls[i].yPosMin;
            balls[i].ySpeed = -balls[i].ySpeed;
        }
    }
    glutSwapBuffers();  // Swap front and back buffers (of double buffered mode)
}

**Note: Most of the function uses a for loop with numOfBalls as the counter, but to test collision, I'm only using 2 balls, hence the balls[0] and balls[1]

A: Here are some things to consider.
If the length of (xSpeed,ySpeed) and is roughly comparable with .ballRadius it is possible for two balls to travel "thru" each other between "ticks" of the simulation's clock (one step). Consider two balls which are traveling perfectly vertical, one up, one down, and 1 .ballRadius apart horizontally. In real life they would clearly collide but it would be easy for your simulation to miss this event if .ySpeed ~ .ballRadius.
Second, you change in the vector of the balls results in each ball coming to rest, since
balls[0].xSpeed -= balls[0].xSpeed;

is a really exotic way of writing
balls[0].xSpeed = 0;

A: For the physics almost correct stuff, you need to invert only the component perpendicular to the plane of contact.
In other words take collision_vector to be the vector between the center of the balls (just subtract one point's coordinates from the other's). Because you have spheres this also happens to be the normal of the collision plane.
Now for each ball in turn, you need to decompose their speeds. The A component will be the one aligned with the colision_vector you can obtain it by doing some vector arithmetic A = doc(Speed, collision_vector) * collision_vector. This will be the thing you want to invert. You also want to extract the B component that is parallel to the collision plane. Because it's parallel it won't change because of the collision. You obtain it by subtracting A from the speed vector.
Finally the new speed will be something like B - A. If you want to get the balls to spin you will need an angular momentum in the direction of A - B. If the balls have different mass then you will need use the weight ratio as a multiplier for A in the first formula.
This will make the collision look legit. The detection still needs to happen correctly. Make sure that the speeds are significantly smaller than the radius of the balls. For comparable or bigger speeds you will need more complex algorithms.
Note: most of the stuff above is vector arithmetics. Also It's late here so I might have mixed up some signs (sorry). Take a simple example on paper and work it out. It will also help you understand the solution better.


text:
Q: table sorting not working after append the value I want to short the table even I append some values in table.Now I have created a sample which is sorting in double click.If I click 'ok'  button I have cleared the table and append with new values.Newly appended value doesn't get sorting

 $(document).ready(function() {
     $("#myTable").tablesorter();

      $('#filter_records').click(function(){
   $('#myTable').html('');
   var html = "

" +
   "name	"+
   "Count	" +

            "

";

   for(var i=0;i<3;i++)
   {
    html = html + "

"+
    "name" +i+"	" +
    "count"+i+ "	" +
    "

";
      }
      $("#myTable").append(html);
     });
          });

      name
   count

      sample
   count

      sample1
   count1

   <button type="button" id="filter_records" class="btn btn-default1">Ok</button>

Fiddle

A: After append data you need to call table update function
$("#myTable").trigger("update");
$("#myTable").trigger("sorton",[sorting]);

For ref. you can take a look
http://tablesorter.com/docs/example-ajax.html
Please find updated fiddle:
http://jsfiddle.net/ByGVE/49/


text:
Q: Classification of the singularities of $\frac{1}{z^2+1}$ at $a=1$ I have to classify the singularities of $\frac{1}{z^2+1}$ at $a=1$ and compute the radius of convergence of his power serie at the point $a$.
Is it possible to proceed without using the Laurent serie directly?
Thanks!

A: Factoring,
$$ \frac{1}{z^2 + 1} = \frac{1}{(z-i)(z+i)}
$$
By definition, $f$ has a pole of order $m$ at $z_0$ if there exists a function $g$ that is holomorphic in a neighbourhood of $z_0$ with $g(z_0) \neq 0$ such that
$$ (z-z_0)^m f(z) = g(z)
$$
so at $z_0 = -i$, we can choose $m = 1$, $g(z) = \frac{1}{z-i}$. This shows that $f$ has a simple pole at $z_0 = -i$, and likewise for $z_0 = +i$.
If you let the centre of the power series be $a = 1$, since the function $\frac{1}{z^2 + 1}$ is holomorphic in the disk centred at $a$ with radius $\sqrt{2}$, the series should have radius of convergence of $\sqrt{2}$, by  Laurent's theorem.


text:
Q: Pulseaudio issues - line out/headphones defaulting; connection to other programs ("not running as session daemon") I am running Pulseaudio with a combined digital+analogue channel (the digital is an HDMI connection to my monitor('s speaker); the analogue is a connection to separate speakers).
Whenever the pulseaudio daemon starts it seems to default to "Headphones" rather than "Line out" (both report as "unplugged" even though the line out is, in fact, plugged in). Is there a way to set the default to "Line out" rather than "Headphones"?
A separate (though potentially related) issue is that when monitor has gone to sleep and been re-awaked Pulseaudio apparently is no longer running as a session daemon - as when I try to connect with pulseaudio-ctl it can't find the connection, reporting "No PulseAudio daemon running, or not running as session daemon."  I have to kill the daemon, and then it will restart in a way that pulseaudio-ctl can access it.


text:
Q: facebook sdk 4.17 iOS sending gift with FBSDKGameRequestContent Hi I am using Facebook sdk 4.17 in my iOS app.
I am trying to send a gift with FBSDKGameRequestContent and I get 2 different errors with 2 different gifts while I am sending from the same code:
FBSDKGameRequestContent *gameRequestContent = [[FBSDKGameRequestContent alloc] init];

gameRequestContent.message = @"Your gift is waiting for you";
gameRequestContent.title = @"Choose Friends";
gameRequestContent.recipients = recipentsToSend;
gameRequestContent.objectID = collection_item;
gameRequestContent.actionType = FBSDKGameRequestActionTypeSend ;

// Assuming self implements <FBSDKGameRequestDialogDelegate>
FBSDKGameRequestDialog* dialog = [[FBSDKGameRequestDialog alloc] init];
dialog.content = gameRequestContent;
dialog.delegate = self;
[dialog show];

gift 1 error 1:

Error Domain=com.facebook.sdk.share Code=2 "(null)" UserInfo={com.facebook.sdk:FBSDKErrorDeveloperMessageKey=The objectID is required when the actionType is either send or askfor., com.facebook.sdk:FBSDKErrorArgumentNameKey=objectID}

gift 2 error 2:

Error Domain=com.facebook.sdk.share Code=100 "(null)" UserInfo={com.facebook.sdk:FBSDKErrorDeveloperMessageKey=Parameter object_id: Invalid id: "ChristmasHomeOrnament"}

Anyone have any idea?


text:
Q: Receiving An Intermittent EXC_BAD_ACCESS When Updating an EKEvent I have a Cordova app with a custom plugin that is creating and updating EKEvents in the user's iCloud calendar.
I am using the following function to find a specific EKEvent based on its URL:
- (EKEvent*) getEventWithURL:(NSString *)pstrURL store:(EKEventStore *)pStore
{

    EKCalendar* calendar = [self getCalendarByName:mstrCalendarName store:pStore createIfDoesNotExist:false];

    NSArray* calendars = [[NSArray alloc] initWithObjects: calendar, nil];

    NSDateFormatter *sDate = [[NSDateFormatter alloc] init];
    [sDate setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *myStartDate = [sDate dateFromString:@"2013-11-01 00:00"];

    NSDateFormatter *eDate = [[NSDateFormatter alloc] init];
    [eDate setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *myEndDate = [eDate dateFromString:@"2014-12-31 23:59"];

    NSPredicate *predicate = [pStore predicateForEventsWithStartDate:myStartDate endDate:myEndDate calendars: calendars];

    // Fetch all events that match the predicate.
    NSArray *events = [pStore eventsMatchingPredicate:predicate];

    EKEvent *foundEvent = nil;
    EKEvent *event;

    for (id oEvent in events)
    {
        event = (EKEvent *)oEvent;

        if ([event.URL isEqual:[NSURL URLWithString:pstrURL]])
        {
            foundEvent = event;
            break;
        }
    }

    return foundEvent;
}

It is then modified (start and end dates are changed) and saved in another method with the following code:
EKEvent *myEvent = nil;

BOOL saved = false;

EKCalendar* calendar = nil;

if(pstrCalendarTitle == nil)
{
    calendar = pStore.defaultCalendarForNewEvents;
}
else
{
    calendar = [self getCalendarByName: pstrCalendarTitle store: pStore createIfDoesNotExist:true];
}

// find event if it exists
myEvent = [self getEventWithURL:[NSString stringWithFormat: @"custom://%@", pstrTSDID ] store:pStore];

// if an event wasn't found, create a new one
if (myEvent == nil)
{
    myEvent = [EKEvent eventWithEventStore: pStore];
}

// set all the fields to new values
myEvent.title = pstrTitle;
myEvent.location = pstrLocation;
myEvent.notes = pstrMessage;
myEvent.startDate = pdtStartDate;
myEvent.endDate = pdtEndDate;
myEvent.calendar = calendar;
myEvent.URL = [NSURL URLWithString:[NSString stringWithFormat: @"custom://%@", pstrTSDID ]];

// only add an alarm if one hasn't been created already
if ([[myEvent alarms] count] == 0)
{
    EKAlarm *reminder = [EKAlarm alarmWithRelativeOffset:-2*60*60];
    [myEvent addAlarm:reminder];
}

When creating a whole bunch of EKEvents (about 30 in a row) I don't get the EXC_BAD_ACCESS error, however when updating events I get the EXC_BAD_ACCESS error intermittently. Sometimes it is on the first update, and sometimes I am able to update 10 before seeing the error, which then crashes my app.
I suspect it may have something to do with the foundEvent variable not being retained, however my project is using ARC so it is my understanding that I don't need to do any memory management tasks. Unless ARC is getting confused with the way the event variable is being cast and then passed around in the loop in getEventWithURL?
For full disclosure, I do have Enable Zombie Objects enabled and the stack trace that I see doesn't reference any of my methods specifically, it starts at start_wqthread and then references some EKEventStore _databasechangedexternally internal methods.

A: For what it's worth I wasn't able to figure out what the issue was with modifying the events so I am instead deleting the event (if it exists) and creating a new one. My getEventWithURL method is now called deleteEventWithURL which does the removal of the event from the store. The app is no longer crashing after making this change.


text:
Q: Setup tools for android things1.0 Where to find the setup tools for building an Android Things 1.0 image for Raspberry PI3.
Whith actuel Android Things console , using download tools give Android Things DP8 image.
Thank's for help


text:
Q: Find the square root of $14+6\sqrt5 $ Find the square root of $14+6\sqrt5$
I don't just want the answer, can you please tell me the method how you get the answer

A: Hint:
$$(a+b \sqrt{5})^2 = 14 + 6 \sqrt{5}$$
Solve for $a$ and $b$.

A: As you expect the solution to be nice (as in you don't just write $\sqrt{14+6\sqrt{5}}$), one can use "creative writing" to receive a square via the binomial formula:
$$14+6\sqrt{5}=9+5+6\sqrt{5}=9+6\sqrt{5}+5=9+2\cdot 3\cdot\sqrt{5}+\sqrt{5}^2$$
I'm sure you can take it from here!

A: Hint:
$$6\sqrt5=2\cdot3\cdot\sqrt5$$
Compare with $$2ab$$ in $$a^2+b^2+2ab$$


text:
Q: TypeError: 'str' object is not callable Python 3.7.0 Sorry guys for wasting your time with a newbie here. Today I ran at a problem . This is my code :
from turtle import *
shape("turtle")

def draw_square(length,color):

for i in range(4):
    forward(length)
    color('color')
    left(90)
return length,color

draw_square(100,'red')

mainloop()

The project is to draw a turlte square using function with 2 arguments : 'length' and 'color' . 15 mins ago I did succeeded in drawing correctly corresponding to the project requirements . After that , I re-ran the project again then this problem showed up . Im totally dead with this . Can u guys help me out please ? Thank you very much.
This is what VS said to me :
Traceback (most recent call last):
File "ex3.py", line 15, in <module>
draw_square(100,'red')
File "ex3.py", line 9, in draw_square
color('color')
TypeError: 'str' object is not callable

A: color is a local variable (that is provided as an argument) in the draw_square function. You pass a string ('red') as said argument and then call it as if it were a function
color('color')  # color == 'red', so 'red'('color') is tried here

You can avoid that by not shadowing the turtle function color in draw_square:
def draw_square(length, given_color):
    for i in range(4):
        forward(length)
        color(given_color)  # color here will be the actual function from turtle
        left(90)
    return length, given_color


text:
Q: Peer review 2.0 I have an idea for a website that could improve some well-known difficulties around peer review system and "hidden knowledge" in mathematics. It seems like a low hanging fruit that many people must've thought about before. My question is two-fold:
Has someone already tried this? If not, who in the mathematical community might be interested in creating and maintaining such a project or is working on similar projects?
Idea
A website dedicated to anonymous discussions of mathematical papers by experts.
Motivation 1: Hidden knowledge
Wilhelm Klingenberg's "Lectures on closed geodesics" can be found in every university's math library. One of the main theorems in the book is the following remarkable result, a culmination of decades of work on Morse theory of the loop space by many mathematicians: Every compact Riemannian manifold contains infinitely many prime closed geodesics.
Unfortunately, there is a mistake in the proof. 44 years after the book's publication the statement is still a widely open problem. The reason I know this is because when I was in grad school I mentioned the book to my adviser and my adviser told me about it. If I tried to look for this information online I wouldn't find it (in fact, I still haven't seen it written down anywhere).
This is one of many examples of "hidden knowledge", information that gets passed from adviser to student, but is inaccessible to an outsider. In principle, a new Ramanujan can open arxiv.org and get access to the cutting edge mathematical research. In reality, the hidden knowledge keeps many mathematical fields impenetrable to anyone who is not personally acquainted with one of a handful of experts.
Of course, there is much more to hidden knowledge than "this paper form 40 years ago actually contains a gap". But I feel that the experts' "oral tradition" on papers in the field is at the core of it. Making it common knowledge will be of great benefit to students, mathematicians from smaller universities, those outside of North America and Europe, people from adjacent fields, to the experts themselves and to the mathematical progress.
Motivation 2: Improving peer review
Consider the following situations:

*

*You are refereeing a paper and get stuck on some minor issue. It will take the author 5 minutes to explain, but a few hours for you to figure it out on your own. But it doesn't quite feel worth initiating formal communication with the author through the editor over this and you don't want to break the veil of anonymity by contacting the author directly.

*You are being asked to referee a paper, but don't have time to referee the whole paper. On the other hand, there is a part of it that is really interesting to you. Telling the editor "yes, but I will only referee Lemma 5.3" seems awkward.

*You are refereeing a paper that is at the intersection of your field and a different field. You would like to discuss it with an expert in the other field to make sure you are not missing anything, but don't know a colleague in that area or feel hesitant revealing that you are a referee for this paper.

These are some of many situations where ability to anonymously discuss a paper with the author and other experts in a forum-like space would be helpful in the refereeing process. But also outside of peer review mathematicians constantly find small errors, fillable gaps and ways to make an old paper more understandable that they would be happy to share with the others. At the same time, they often don't have time to produce carefully polished notes that they would feel comfortable posting on arxiv, or if they post notes on their website they may not be easy to find for anyone else reading the paper. It would be helpful to have one place where such information is collected.
How will it work?
The hope is to continue the glorious tradition of collaborative anonymous mathematics.  One implementation can work like this:
Users of the website can create a page dedicated to a paper and post questions and comments about the paper on that page. To register on the website one needs to fill in a form asking for an email and two links to math arxiv papers that have the same email in them (this way registration does not require verification by moderators) and choose their fields of expertise. When a user makes a comment or question only their field/fields are displayed.

A: I'm one of the founders of info.inquire.pub (main site not yet available to the public).  We're a non-profit startup with a similar purpose. We aim to be a Q&A site with a reputation system and upvotes, where each question is associated with a specific paper (we support ArXiv or DOI so far).
We are still deciding exactly how anonymous we want to be.  We continually discuss potential issues like those @TerryTao brings up in a comment above and are committed to designing a system which will be robust against trolling and weaponisation.
In my opinion, academic research is one of societies greatest resources.  We want to improve the state of research.  We want to save researchers time and effort. We'd also like to provided a venue for cross-disciplinary review and for the general public to ask high quality objective questions about academic literature.  We take possible negative impacts seriously.
The current peer review process is far from perfect and once articles are published they're rarely every edited again. If anyone would like to help us (including simply joining the conversation), my contact info is available at mathandy.ai.

A: I'm 100% in agreement about the need for such a site.  In fact I'm currently in the process of coding what I hope can grow into such a site.
The apps mentioned above like Papers$^\gamma$ are all nice but they all just kinda throw the user at a list of papers and say: go comment/review.  That can work to collect some objections or point out issues but only if people are visiting the site enough to think that's where the comment goes and it's not that helpful to aggregate knowledge about what's a great paper.
The challenge here is that you need a website which is first and foremost useful and engaging enough for mathematicians to visit it on a regular basis.  Something like the question system here (or at least regular professional gossip etc) is one obvious possibility but stack exchange already exists so another possibility is a good system for managing collaboration (so like a scratch pad where you can annotate notes someone else made, version controlled uploads of papers etc)
Furthermore, a good website for this purpose should also have

*

*The ability to rate or at least upvote articles without saying anything.  Comments are nice enough for issues but do little to help other people find the best articles.

*Some way to feature particular articles that are either hand selected or are well rated by users.
I'm thinking allowing users with enough karma/trust create a list of articles that they can add to regularly thus creating something like a mini-journal as well as allowing the creation of lists of good references for various subjects.

*The ability of authors to claim papers and respond to questions about them (both publicly and privately) as well as offer notes to be displayed alongside the paper/link (eg in Lemma 5 n must be at least k+1 not k as written)
I think it would also be desierable to have some way to verify participants as mathematicians (defined broadly to basically mean anyone who can understand a math paper..but it needs to exclude ppl looking for homework help and cranks) which could be easily done via the system arxiv uses of vouching someone else in or even do it on trust initially.
Anyway in some sense this isn't an answer yet but I think it's important to convey that the existing solutions either lack the features that would aggregate information (thinking academia.edu and researchgate) or lack the features which would enable a community to grow up around the site or both.
I'm going to give writing such a site myself a go because I've wanted it to exist for 15 years and so far all the attempts fail at the generating interest level.  But I'm likely to fail down to just a fancy blog so I'm mentioning these aspects in the hope someone else will create a site with them.

A: I'm the founder of https://papers-gamma.link, an Internet place
to discuss scientific articles, mentioned by Matthieu Latapy.  I have
been supporting this site for 6 years now. I hope that one day it will
become popular (in a good sense of the word) and useful for the entire
scientific community. As you may imagine, I'm pretty convinced that
the idea of public review and public comments is, potentially, a very
promising one. My persuasion is less than 6 years ago though, and here's why.
Observing that Papers$^\gamma$ gains its
popularity very slowly, I started to think more and more about the
scientific review and publishing processes.  I'll share with you my
current understanding of this subjects, admitting that these issues
are more likely to be in the field of sociology rather than
mathematics.
The original goal of scientific journals was to inform about and
discuss the research currents.  But after, this had to make room for
other things: archiving and bibliometrics. I'm OK with archiving. But,
it seems that the optimization of bibliometric statistics negatively
affects the discussion power, the original (!)  goal of the scientific
journals.
Let me try to illustrate exactly what I mean by "discussion power" of
scientific journals.  Consider Miller's one-page paper [2], which is
an excellent example of conversational mathematics.  The paper
contains an alternative proof of Miles' results [1] about the
characteristic equation of the $k$-th order Fibonacci
sequence. Miller's paper can be considered as a response to Miles's
paper. Compare this to the modern Internet forums like MathOverflow.
Does any journal, wiki, or another internet portal is attracted to
archiving and bibliometrics as time goes forward?  Maybe there is a
natural or induced drift from "discussion" towards "judgment"?  If it
is the case, should we consider to create a new journals every, say,
10 or 20 years, to restart discussion processes?  Or should we be
extremely careful, trying to keep the discussion power of existing
scientific journals?
Here are main arguments against the mass acceptance of
public review and comments, that I can imagine:

*

*Existing systems works pretty well.

*Not all conversations should be made public.  Private reviews and
conversations have their advantages.  People feel more free to
commit errors, express misunderstanding, and criticize in
private. Good reviews help the authors to polish and publish almost
perfect articles.

*The more a resource is open, the more it is susceptible to spam.

*Anonymous public discussions may be used as a platform for attacking
other scientists.
Here is a list of some online resources related to the idea of public reviews and collaborative science in general:

*

*MathSciNet and Zentralblatt MATH,
databases with post-publication reviews.

*nLab wiki and The $n$-Category Café, collaborative works on Mathematics, Physics and Philosophy.

*Polymath Project, a collaborative project that aims to solve important and difficult mathematical problems.

*Machine Learning Paper Discussions subreddit.

*Atmospheric Chemistry and Physics journal with interactive public peer review process.

*CoScience, a service that aims to "recreate scientific communication as a virtuous, open, community-driven process".

*F1000Research, a platform covering the life science publications.

*PubPeer, a online platform for
post-publication peer review. "The site has served as a
whistleblowing platform, in that it highlighted shortcomings in
several high-profile papers, in some cases leading to retractions
and to accusations of scientific fraud", as Wikipedia says.

*BibSonomy, a social bookmark service allowing comments.

*Selected Papers Network was an open-source project for share and comment scientific articles.
I wonder if certain usenet groups in sci.* hierarchy are still active.
In any case, the source code of Papers$^\gamma$
is open under CC0 Public Domain Dedication.
And you are welcome to send me a patch or fork it if you wish so.
To conclude, I think that "Hidden knowledge" will always be here, and the solution to this issue lies not in the technical but rather in the societal dimension. Someone just need to write it down in some searchable place. For instance, in enumerative combinatorics Sloane's The On-Line Encyclopedia of Integer Sequences helps a lot, but we need to watch out and constantly update it.
Conclusion update:
for me, both OEIS and MathOverflow are popular because their main
purpose is to allow people make a research together and not to judge
each other.
Paywalled Biblio
[1] Miles, E. "Generalized Fibonacci numbers and associated matrices". The American
Mathematical Monthly, 67(8), 1960, 745–752
[2] Miller, M. D. "On generalized Fibonacci numbers".
The American Mathematical Monthly, 78(10), 1971, 1108–1109.

A: *

*SelectedPapers was created "as a space where academics could read, share, and give feedback on articles and papers related to their field.". It is no longer in operation.

*Scirate is an active discussion forum for papers on arXiv, mostly in the area of quantum information processing. It copies the arXiv subcategories in mathematics, so this could well function in that area as well.

Most contributors on these sites disclose their names, but that is not required. Some journals have implemented an open discussion functionality.

*

*SciPost is one of these, it welcomes anonymous discussions --- both comments by experts invited as reviewers of a manuscript and also unsollicited comments.
The physics branch of SciPost is well developed, the mathematics branch has just started with two editors, it now needs more editors who are willing to help set up this branch. (Disclosure, I'm a SciPost Physics editor, feel free to get in touch if this is something you might consider doing.)

*Perhaps most relevant for MathOverflow, I mention that PhysicsOverflow has implemented a review section, where authors can ask the community to comment on their work. The discussion could be a critical appraisal or just a summary of the paper.
I do note that, unlike MO, PhysicsOverflow is not part of the StackExchange ecosystem, I don't think such functionality could be implemented as part of SE. I also note that the PhysicsOverflow review functionality has not been a success: Less than 10 reviews per year are entered.

A: Imho, mathematics has already a good culture and a relatively rich informational ecosystem to detect, document, and disseminate these issues (many options are mentioned above); what might be lacking is a kind of (semi)automated system of interlinked communication that helps spreading the information further.
Judging from the several examples we had to deal with at zbMATH Open (and the discussions involved), I would certainly agree that it seems less feasible to have a single seemingly authoritative source, but we need to employ and coordinate our existing procedures. A natural problem would be, e.g., the scope - there is a number of problematic (mostly, APC) journals around where one has doubts about the proper peer review - would you like to have a website that addresses all of them (including simple Fermat/Goldbach proofs etc.)? Likely, serious mathematicians lack the resources to do that.
But also with restricted scope, every single issue is a tedious work. To give a recent example, even in a rather clear-cut case
Ramm, Alexander G., Solution of the Navier-Stokes problem, Appl. Math. Lett. 87, 160-164 (2019). ZBL1410.35100.
it was impossible to convince the author of the reviewer's arguments (although we employed another expert as arbiter who went through the arguments and clearly ruled in favour of the reviewer). Every such issue is different and needs to be handled carefully.
On the technical side, e.g., if we detect such an issue with a widely accepted older article via zbMATH Open (documented usually as an additional "Editorial remark" in the original) which is lacking an erratum/corrigendum for this, I currently post this also manually as an answer at the standard question at MathOverflow
Widely accepted mathematical results that were later shown to be wrong?
which has the additional advantage that an automated backlink in the respective zbMATH entry is generated (e.g., see the entry
Saito, Masa-Hiko, On the infinitesimal Torelli problem of elliptic surfaces, J. Math. Kyoto Univ. 23, 441-460 (1983). ZBL0532.14019.)
Of course, this doesn't mean everyone is aware of this information, and there are likely various ways to improve/automatize things further. One could think about creating a specific MathOverflow entry/tagging for each issue/publication that needs discussion/updates which could trigger an activity on our and other sites. But the main effort will likely always be mathematically, not technically, and require mathematicians who are willing to explore things deeply. The platforms are there, we should just make sure that the documentation is appropriate, accessible, and ideally increasingly interoperable.

A: It seems to me that Papers$^\gamma$ is close to what you describe: people can upload a paper, inform its authors, and publicly (anonymously or not) discuss it.
I would also like to mention PCI (Peer Community In), "a free recommendation process of scientific preprints based on peer reviews" that published the discussion between authors, reviewers, and editors (or their equivalent); there is a nice video presentation.


text:
Q: What does work mean here? I have seen an article regarding whether should we exercise first thing in morning or not and I came across a sentence which seems a little odd to understand.

Early morning exercise can be bad for your health, say researchers.
They claim the body's immune system is not ready to cope with intense
  exercise first thing in the morning.
A pre-breakfast work-out puts the exerciser at greater risk of
  infection than the same level of exertion after work, the study by
  sports scientists suggests.

(Source)
What does "work" mean here?

A: "Work" here assumes the reader is engaged in some sort of daily routine which involves waking up, eating breakfast, then performing some sort of job function for a significant amount of time.
For the purposes of this sentence you could replace "after work" with "in the evening."

A: here work means daily activities (job) of the person.They are trying to say that exercise after coming back from office is less risky and better than early morning exercise.


text:
Q: Google clone exercise, why can´t i align the content? I´m new to web development, like I just did 3h and am trying to finish a google clone as an exercise and I don´t seem to understand much about how the things relate.
I tried adopting several type of positions for the divs and buttons but nothing seems to change for the search field and the 2 buttons below.
running out of ideas.
Can you perhaps tell me which style rules are clashing with each other?

body {
  margin: 0;
}
#Search {
  margin: 150px auto;
  width: 50%;
}
.holder {
  text-align: center;
}
.loginbutton {
  background-color: blue;
  color: white;
  position: absolute;
  top: 20px;
  right: 20px;
  border-radius: 5px;
}
.gbutton1 {
  background-color: lightGrey;
  padding: 5px;
  border-radius: 5px;
  height: 50%;
  top: 50%;
  margin: auto;
}
.gbutton2 {
  background-color: lightGrey;
  padding: 5px;
  border-radius: 5px;
  height: 50%;
  top: 50%;
  margin: auto;
}
}
.box {
  position: absolute;
  right: 50%;
  top: 50%;
  margin: auto;
}
.footer {
  position: fixed;
  width: 100%;
  bottom: 0px;
}
<!doctype html>

  <meta charset="utf-8">
  <title>My crappy Google</title>
  <meta name="author" content="n00b">

  <button class="loginbutton">Login</button>

      <input type="text" name="search" placeholder="Search....">

      <button class="gbutton1">Google-search</button>
      <button class="gbutton2">i´m feeeling like crap</button>

footer


text:
Q: Increasing efficiency of run-time complexity of comparing vector elements? I have two vectors:
std::vector<int> V1 {1,2,3,4,5,6,7};
std::vector<int> V2 {1,2,3};

Executing the following would result in quadratic run-time complexity:
for(auto IT = V1.begin(); IT != V1.end(), IT++)
{
  for(auto IT2 = V2.begin(); IT2 != V2.end(); IT2++)
  {
    if(*IT == *IT2){std::cout<<"Found a match!"<<std::endl;}
    else{std::cout<<"No match!"<<std::endl;}

  }
}

Are there any clear ways to bring this down to linear time?
Would using an STL algorithm enable this?
For instance:
for(auto IT = V1.begin(); IT != V1.end(); IT++)
{
  std::find(V2.begin(), V2.end(), *IT);
}

A: You are going to need to keep one array at linear time (your source array as you're obviously searching from it's 0th to it's Nth element).
However, you can bring the other search term down by ensuring that the contents of the search space are sorted first.  This will allow the use of binary search algorithms which are log(n) complexity.
Good luck!
An example of this:
std::vector<int> V1 {1,4,5,6,3};
std::vector<int> V2 {100, 104,101,3};
bool condition {false};
std::sort(V2.begin(), V2.end());

for(auto IT = V1.begin(); IT != V1.end(); IT++)
{
  auto result {std::binary_search(V2.begin(), V2.end(), *IT)};
  if(result > 0){ condition = true};
}


text:
Q: iOS Developer Enterprise Program membership Renewal Before Expiration I Received an email from the apple for renewal of Enterprise Membership Program, and below are my questions regarding that.

*

*Is there any effect on the distribution certificates in case of renewal of program before expiration?

*Will the application signed with the distribution certificates continue to run without any problem in case of renewal of program before expiration?

*Will there is need to distribute the enterprise applications again, after renewal before expiration?

Thanks for your answer in advance!

A: No. Yes. No.
Renewing before expiration causes no affects on existing provisioning profiles. Renewing early will extend your membership one year after the current expiration date. You don't lose any calendar time on your membership by renewing early. Failing to renew on time will invalidate your distribution certificate, causing your enterprise distribution app to fail to install after the expiration date.
So renew before it expires.