text:
Q: Flutter: ImagePicker from gallery won't pop up on web in iOS I'm using the package image_picker on a flutter app to load a picture, and it works fine in the web when accessed by an Windows, MacOs, Android, but in the iOS (16.3) the pop up to choose the image won't show up.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import "package:image/image.dart" as img;

class ProgramScreen extends StatefulWidget {
  @override
  _ProgramScreenState createState() => _ProgramScreenState();
}

class _ProgramScreenState extends State<ProgramScreen> {
  TextEditingController _destinationController = TextEditingController();
  TextEditingController _subjectController = TextEditingController();

  late Uint8List _clipboardImage;
  bool hasImage = false;
  bool hasText = false;
  double heightImg = 1;
  double widthImg = 1;

  Future _getImageFromPicker() async {
    final ImagePicker _picker = ImagePicker();
    final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery, requestFullMetadata: false);
    var bytes = await image!.readAsBytes();
    var photoData = img.decodeImage(bytes);
    heightImg = photoData!.height * 0.5;
    widthImg = photoData.width * 0.5;
    setState(() {
      hasImage = true;
      hasText = false;
      _clipboardImage = bytes;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Theme.of(context).colorScheme.primaryContainer,
      padding: EdgeInsets.all(16),
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10)),
                color: Colors.white,
              ),
              padding: EdgeInsets.all(16),
              child: Column(
                children: <Widget>[
                  TextField(
                    decoration: InputDecoration(hintText: 'Destinatáio'),
                    controller: _destinationController,
                  ),
                  TextField(
                    decoration: InputDecoration(hintText: 'Assunto'),
                    controller: _subjectController,
                  ),
                ],
              ),
            ),
            SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                ElevatedButton(
                  onPressed: () async {},
                  child: Text('Enviar Grupo'),
                ),
                ElevatedButton(
                  onPressed: () async {},
                  child: Text('Enviar Todos'),
                ),
              ],
            ),
            SizedBox(height: 100),
            hasText
                ? Text(
                    "O conteúdo copiado não é uma imagem!",
                    style: TextStyle(
                        color: Colors.red, fontWeight: FontWeight.bold),
                  )
                : SizedBox(height: 1),
            !hasImage
                ? Column(children: [
                    ElevatedButton(
                      onPressed: () async {},
                      child: Text('Verificar área de transferência'),
                    ),
                    SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: () async {
                        _getImageFromPicker(); // Here is the function call
                      },
                      child: Text('Escolher da galeria'),
                    ),
                  ])
                : Column(
                    children: [
                      Container(
                        height: heightImg.toDouble(),
                        width: widthImg.toDouble(),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(10)),
                          image: DecorationImage(
                            image: MemoryImage(_clipboardImage),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                      SizedBox(height: 20),
                      Column(children: [
                        ElevatedButton(
                          onPressed: () async {},
                          child: Text('Verificar área de transferência'),
                        ),
                        SizedBox(height: 16),
                        ElevatedButton(
                          onPressed: () async {
                            _getImageFromPicker(); // Here is the function call
                          },
                          child: Text('Escolher da galeria'),
                        ),
                      ])
                    ],
                  ),
          ],
        ),
      ),
    );
  }
}

here is my flutter doctor
[✓] Flutter (Channel stable, 3.3.10, on macOS 13.2 22D49 darwin-arm, locale pt-BR)
[!] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.2)
[✓] VS Code (version 1.74.3)
[✓] Connected device (3 available)
[✓] HTTP Host Availability

the pop up supposed to apper
I tried to use older versions of the packages, but still have the same issue. Also, setting the "NSPhotoLibraryUsageDescription" has no effect

A: Can't tell the reason why, but changing
onPressed: () async {
    _getImageFromPicker(); // Here is the function call
}

to
onPressed: () { // removed the async modifier
    _getImageFromPicker(); // Here is the function call
}

Solves the problem! Now the pop up shows up as expected


text:
Q: how to find a linear combination of predictors maximizing correlation between its score and dependent variable in R Please correct me if I am wrong as I am not good at R. I think I can find a linear combination maximizing correlation between predictors and dependent variables by running partial least squares analysis with standardized X without intercept and standardized Y matrix.
But how can I do that with pls or any other package in R? Does it do that with default settings?

A: No, PLS package does not maximize correlation between scores and response values in default settings. I couldn't so far find whether the package has that functionality or not although manual mentioned about it with a sentence.
And you are right. You need to deal with standardized matrices to do PLS for the correlation maximization.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plotting symbolic functions in OCTAVE I am new to Octave and was practising trying to represent the function y=e^(-t) as a Fourier series. When I use a series of three terms I get this plot
Plot with 3 terms
However, when I start adding more terms, the plot shows discountinuities.
Plot with 5 terms
Any ideas? Thanks
clear all
t0=0;T=3;w=2*pi/T;
syms t
x=exp(-t);
ezplot(x,[t0 t0+T])
title('')
hold
for k=-2:2
  a(k+3)=(1/T)*int(x*exp(-j*k*w*t),t,t0,t0+T);
  ex(k+3)=exp(j*k*w*t);
end
xx=sum(a.*ex);
ezplot(xx,[t0 t0+T])
title('')
axis([0 3 0 1.3])


text:
Q: Trying to convert login from mysqli to sqlsrv I am currently trying to convert a php login I have that uses mysql (I know this is a bit dated) to using sqlsrv. This is just a learning task as I wanted to learn to migrate a site from mySQL to MSSQL.
<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    //Start session
    session_start();

    //Array to store validation errors
    $errmsg_arr = array();

    //Validation error flag
    $errflag = false;

    //Connect to mysql server
    $serverName = "localhost";
    $connectionInfo = array( "Database"=>"dbname", "UID"=>"sa", "PWD"=>"123");
    $conn = sqlsrv_connect( $serverName, $connectionInfo );
    if( $conn === false ) {
        die( print_r( sqlsrv_errors(), true));
    }

    //Function to sanitize values received from the form. Prevents SQL injection
    function clean($str) {
        $str = @trim($str);
        if(get_magic_quotes_gpc()) {
            $str = stripslashes($str);
        }
        return $str;
    }

    //Sanitize the POST values
    $login = clean($_POST['username']);
    $password = clean($_POST['password']);

    //Input Validations
    if($login == '') {
        $errmsg_arr[] = 'Login ID missing';
        $errflag = true;
    }
    if($password == '') {
        $errmsg_arr[] = 'Password missing';
        $errflag = true;
    }

    //If there are input validations, redirect back to the login form
    if($errflag) {
        $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
        session_write_close();
        header("location: index.php");
        exit();
    }

    //Create query
    $qry="SELECT * FROM users WHERE Username='$login' AND Password='".md5($_POST['password'])."'";
    $stmt = sqlsrv_query( $conn, $qry );

    //Check whether the query was successful or not
    if($stmt) {
        $row_count = sqlsrv_num_rows( $stmt );
        if($row_count == 1) {
            //Login Successful
            session_regenerate_id();
            $member = sqlsrv_fetch_assoc($stmt);
            $_SESSION['SESS_MEMBER_ID'] = $member['idUsers'];
            $_SESSION['SESS_FIRST_NAME'] = $member['FirstName'];
            $_SESSION['SESS_LAST_NAME'] = $member['LastName'];
            session_write_close();
            header("location: home.php");
            exit();
        }else {
            while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
                echo $row['FirstName'];
                $row_count = sqlsrv_num_rows( $stmt );
                echo $row_count;
                echo $stmt;
            }
            //Login failed
            //header("location: index.php");
            exit();
        }
    }else {
        die("Query failed");
    }
}
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Asset Manager</title>

    <link rel="stylesheet" href="assets/main.css">
    <link rel="stylesheet" href="assets/login.css">

        <form class="form-login" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

Log in

                            Username
                            <input type="text" name="username" id="username">

                            Password
                            <input type="password" name="password" id="password">

                        <button type="submit" name="Submit" value="Login">Log in</button>

        </form>

The issue is it just keeps going to the last else. I have been doing some troubleshooting as you can see in the code. the issue I think is that the rowcount does not work. When I echo ut the row count I just get a Resource 5 showing.
Any ideas?

A: The fix is to change
if($stmt) {
    $row_count = sqlsrv_num_rows( $stmt );
    if($row_count == 1) {

to:
if($stmt) {
    $rows = sqlsrv_has_rows( $stmt );
    if($rows === true) {

A: If project is old and messy, you might consider to write wrapping functions, something like this:
function mysql_num_rows($result){
   $rows = sqlsrv_num_rows($result);
   // change $rows in the way you need
   return $rows;
}

Update
If you have no mysql extension, mysql_num_rows() will not be available and there will be no problem to define this function.
If you can not remove mysql extension, make it my_mysql_num_rows() and replace "mysql_" with "my_mysql_".


text:
Q: A device attached to the system is not functioning. (0x1F) Error while using selenium send_keys method from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
chrome_driver = 'D:\Code\chromedriver'
driver = webdriver.Chrome(executable_path=chrome_driver)
driver.get("https://secure-retreat-92358.herokuapp.com/")

first_name = driver.find_element(By.NAME, "fname")
first_name.send_keys("Sumukh")
Second_name = driver.find_element(By.NAME, "lname")
Second_name.send_keys("Sharma")
email = driver.find_element(By.NAME, "eamil")
email.send_keys("devilanime088@gmail.com")
button = driver.find_element(By.CSS_SELECTOR, "form button")
button.click()
driver.quit()

[23876:10720:1025/231637.440:ERROR:device_event_log_impl.cc(214)] [23:16:37.440] USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[23876:10720:1025/231637.444:ERROR:device_event_log_impl.cc(214)] [23:16:37.444] USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[23876:10720:1025/231637.445:ERROR:device_event_log_impl.cc(214)] [23:16:37.444] USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[19832:25172:1025/231835.237:ERROR:gpu_init.cc(521)] Passthrough is not supported, GL is disabled, ANGLE is
While running this simple automated script i'm getting this error i tried to looked into various stack overflow answers for the similar type of problem but can't seem to find the answer
p.s. - my chrome version is matches with my chrome driver version (Version 106.0.5249.119 (Official Build) (64-bit)


text:
Q: iOS - UITableViewCell image adjust/resize I have create a table view and have filled its cells with text. What I'm trying to do is add an image to the cell but whats happening is the image is coving the whole cell and it looks bad...
This is what I'm doing: cell.imageView.image = [UIImage imageNamed:@"test2.jpeg"];
And this is what it looks like:
What I'm trying to get it to look like is:
How do i resize the image of the table view cell in order to get the desired result?
Update
This is what I have tried suggested in the answers below:
cell.imageView.frame = CGRectMake(0.0f, 0.0f, 30.0f, 30.0f);
cell.imageView.layer.cornerRadius = 8.0;
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
cell.imageView.layer.masksToBounds = YES;
cell.imageView.image = [UIImage imageNamed:@"test2.jpeg"];

but still the output I'm getting is:

Update 2.0
Ive tried some other ways suggested:
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(30, 30, 30, 30)];
imageView.backgroundColor = [UIColor clearColor];
[imageView.layer setCornerRadius:8.0f];
[imageView.layer setMasksToBounds:YES];
[imageView setImage:[UIImage imageNamed:@"test2.jpeg"]];
[cell.contentView addSubview:imageView];

but now I'm getting this:

A: I spent the last few hours figuring out how to do this, so I'll share what I've found. Your code from Update 2.0 is a good start:
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(30, 30, 30, 30)];
imageView.backgroundColor = [UIColor clearColor];
[imageView.layer setCornerRadius:8.0f];
[imageView.layer setMasksToBounds:YES];
[imageView setImage:[UIImage imageNamed:@"test2.jpeg"]];
[cell.contentView addSubview:imageView];

You can mess with the numbers in the first line to get the image to appear where you need it; for my purposes, I used (20, 5, 40, 40).
Add this line before [cell.contentView addSubview:imageView] :
[imageView setTag:99];

We need this tag to identify which subview we just added. If you don't remove the image every time you reload a cell, the images will just start piling up there. For your case, this doesn't make much of a difference because it will keep using the same image, so it will look the same. However, if you get a user that likes to scroll up and down a lot, you could run into problems with a couple hundred or more of those images loaded. And if your cells will have different images, they will start displaying on top of each other, which will look really bad if they're different sizes. So before you initialize *imageView, run this loop:
for (UIImageView *subview in cell.contentView.subviews)
{
    if (subview.tag == 99)
    {
        [subview removeFromSuperView];
    }
}

With this code, your image should look the same as it does in Update 2.0, but it should run better. To move your text over, use cell.indentationLevel and cell.indentationWidth. Make sure your cell style is set to "basic" (it looks like yours is) and somewhere before you return your cell, use
cell.indentationWidth = 10; // The amount each indentation will move the text
cell.indentationLevel = 7;  // The number of times you indent the text

so this code will move the text over 10 points 7 times. You can play with it until you get it to look right; this is just what I used in my project. Hope this helps!

A: First you need to set the cell's imageView to the max size you want. Then assure via Interface Builder or via code that you have the correct content mode:
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;

Basically with this mode it will try to fit the space you created for your image but it will maintain the aspect ratio.
Jackson posted a good image that shows the content modes here:

For the corner you will need QuartzCore and you can do set it with this code:
#import <QuartzCore/QuartzCore.h>

...

cell.imageView.layer.cornerRadius = 4;
cell.imageView.layer.masksToBounds = YES;

UPDATE
If your imageView isn't an outlet you are better off adding one imageView yourself to the cell. You can (and you should) do that via storyboard/xib. This tutorial might help you on that, although there are a lot of them on the internet. This stackoverflow question gives other solutions to that problem.

A: Can you edit the image itself? Try editing the image down the size you'd like and manually rounding the corners. Then call
  cell.imageView.image = [UIImage imageNamed:@"test3.jpeg"];

A: The best way to implement this is to add the below where you call cell.imageView.image
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;

For the rounded corners #import <QuartzCore/QuartzCore.h>
cell.imageView.layer.cornerRadius = 8.0;


text:
Q: macos Big Sur matplotlib chart displaying extra data, while Windows, Linux Mint working properly Pls help, I'm desperate and behind schedule , I've tried to solve this over 1 week for a solution but nothing!
I have been working on a relatively simple cross platform python app. This app works correctly in Windows 10/11 and Linux Mint but not in MacOS, Big Sur.
The app uses matplotlib + tkinter to display an animated chart, updated  every 1 second, with live data yanked from the OS (wireless signal strength)
I have used the following commands code to suppress any X-axis labeling-
ax.tick_params(reset=True)
ax.tick_params('y', left=False, right=False, bottom=False, labelsize=8)
ax.tick_params('x', labelbottom=False, bottom=False, top=False)

This code properly ensures no data is displayed on x-axis (as expected) on Windows 10, 11, Linux Mint, BUT on MacOS Big Sur (11.7) it displays the latest/newest x-axis, x value on the extreme rhs of the chart, basically only labeling the newest data value of the x-axis. See image below, the number in the red dashed rectangle shouldn't display.

Interestingly I was able to recreate the same issue for all OS's by changing the above lines to the following code:
ax.tick_params('x', labelbottom=False, bottom=False,reset=True)
ax.tick_params('y', left=False, right=False, bottom=False, labelsize=8)

PS I did see the issue with macos backends and using the framework version, my understanding is that I am using the Macos "framework version": pythonw on the macos installed thru anaconda

A: It looks a lot like an offset rather than the newest value to me.
Have you tried to
ax.xaxis.get_major_formatter().set_useOffset(False)

Just to see if it changes something (or even solve the problem)?
Another thing you could try, in case it is really a label, not an offset, is to specify a formatter
import matplotlib.ticker as ticker
ax.xaxis.set_major_formatter(ticker.NullFormatter())

or
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter("tick"))

This last one, is a test to check if this is really ticks.
If you only see "tick", you can try to solve the problem (bypass it, rather) by
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter(" "))

(Tho, if this works, then NullFormatter should have work either. But, hard to say what works in a situation where none of that should have been necessary anyway)


text:
Q: I am frequently getting this error - null is not an object (evaluating '_await$Location$getLa.coords') working with expo-location This is my code of custom hook from where i am returning the location of the device and asking the permission.This is a simple implementation but it is giving error
import * as Location from "expo-location";
import { useEffect, useState } from "react";

export default useLocation = () => {
  const [location, setLocation] = useState();

  const getLocation = async () => {
    try {
      const { granted } = await Location.requestForegroundPermissionsAsync();
      if (granted) {
        const { coords } = await Location.getLastKnownPositionAsync();
        const { latitude, longitude } = coords;
        setLocation({ latitude, longitude });
      } else {
        return;
      }
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    getLocation();
  }, []);

  return location;
};

I am using the function by importing it like this
import useLocation from "../hooks/useLocation";
And soring the value like this
  const location = useLocation()
It is giving error of null is not an object (evaluating '_await$Location$getLa.coords')

A: I think that the problem is related to the fact that the getLastKnownPositionAsync() function is returning null on some occasions.
This happens when the last position is not available or doesn't match certain requirements, as specified in the documentation
When this function is returning null, you can't destructure its result by using const { coords } = await Location.getLastKnownPositionAsync();.
Adding a null check should resolve the problem.
import * as Location from "expo-location";
import { useEffect, useState } from "react";

export default useLocation = () => {
  const [location, setLocation] = useState();

  const getLocation = async () => {
    try {
      const { granted } = await Location.requestForegroundPermissionsAsync();
      if (granted) {
        /* Change the code below this comment */
        const lastKnownPosition = await Location.getLastKnownPositionAsync();
        if (!lastKnownPosition) {
            return;
        }
        const { latitude, longitude } = lastKnownPosition.coords;
        setLocation({ latitude, longitude });
      } else {
        return;
      }
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    getLocation();
  }, []);

  return location;
};


text:
Q: Dereference member pointer before operator[] I can't seem to manage the syntax to access the elements of a vector, the pointer of which is contained in a structure. More after the MWE:
#include <vector>
#include <stdio.h>

typedef struct vectag
  {
    std::vector<float> *X;
  } vec;

int main ()
  {
    vec A;
    A.X = new std::vector<float>(0);

    A.X->push_back(5.0);

    // This next line is the problem:
    float C = A.X[0];

    printf("%f\n", C);
    return 1;
  }

GCC (G++) says
14:24: error: cannot convert 'std::vector<float>' to 'float' in initialization

and of course, it's quite right. In the line float C = A.X[0];, B.X[0] would be correct IF X was not a pointer (recall, std::vector<float> *X;).
What is the proper syntax for dereferencing X before operator[], so that I can access the elements of X?
P.S.
I am aware of the member function at(), and it is not an option for me because I don't want the overhead of range checking. This is part of a performance critical code.

A: A.X is the pointer. You need to dereference it to access the vector that it points to:
float C = (*A.X)[0];

But if you haven't initialized A.X to point to anything, dereferencing it has Undefined Behavior, which it looks like you have in this program.

A: A.X[0] attempts to access the first vector pointed to by X - which, remember, is a pointer.
To use operator[] on the vector itself, you can use A.X->operator[](0), although quite honestly I don't see the reason why your member is a pointer and not an object.
Your code exibits undefined behavior, because X is an unitialized pointer
vec A;
A.X->push_back(5.0);

here.


text:
Q: var does NOT keep it's value across bars //@version=4
study("Keep data across bars (var)", overlay=true)

// Variables
var bool canGoShort = true
var bool canGoLong = true
var int myTest = 5

// Functions
f_print(_txt) => t = time + (time - time[1]) * 3, var _lbl = label.new(t, high, _txt, xloc.bar_time, yloc.price, #00000000, label.style_none, color.gray, size.large), label.set_xy(_lbl, t, high + 3 * tr)

// MAIN
if canGoShort
    myTest := myTest + 1

if canGoLong
    myTest := myTest + 1

f_print("myTest=" + tostring(myTest))

I'm baffled by this simple script that doesn't seem to work as intended.
I initialize a var variable myTest with value 5.
Since canGoShort and canGoLong both are always true, I'd expect the value of myTest to be incremented by 1, twice on each bar:
Once in the if canGoShort, and once in the if canGoLong.
Say we have 5000 bars, then I'd expect it to finish at 5 + (5000 * 2) = 10005.
However, when running the script, myTest=7 is printed?
I'm getting the impression that the declaration var int myTest = 5 is executed on each bar.
It was my understanding that a variable defined with the keyword var keeps its value across all bars, but it doesn't appear to be that way.
The documentation clearly says that it should keep it's value:

*

*https://www.tradingview.com/pine-script-reference/#op_var
var is the keyword used for assigning and one-time initializing of the variable.

*https://www.pinecoders.com/faq_and_code/#techniques
Since v4 the var keyword provides a way to initialize variables on the first bar of the dataset only, rather than on every bar the script is run on, as was the case before. This has the very useful
benefit of automatically taking care of the value's propagation
throughout bars
What am I missing here?

A: Calcs are happening as expected. What's wrong there is our f_print() function. Apologies for that. The version you picked up doesn't refresh the text. This code has a newer version of f_print() that does that.
Note that to inspect values bar by bar, as you would want here, our plotchar() trick is more useful, if you also have your Data Window open to inspect the value, as you can inspect each bar's value when you mouse bar to bar. See our answer here for our AHK macro that generates the statement from a variable name, if you have a Windows setup and are interested.
//@version=4
study("Keep data across bars (var)", overlay=true)

// Variables
var bool canGoShort = true
var bool canGoLong = true
var int myTest = 5

// Functions
f_print(_txt) => var _lbl = label.new(bar_index, highest(10)[1], _txt, xloc.bar_index, yloc.price, #00000000, label.style_none, color.gray, size.large, text.align_left), label.set_xy(_lbl, bar_index, highest(10)[1]), label.set_text(_lbl, _txt)
// MAIN
if canGoShort
    myTest := myTest + 1

if canGoLong
    myTest := myTest + 1

f_print("myTest=" + tostring(myTest, "0.0"))
plotchar(myTest, "myTest", "", location.top)

Again, apologies for the trouble. We updated all the instances of f_print() in our FAQ. Note, btw, that we use that version mostly for debugging because it holds on one line. This is the AHK code we use to generate our f_print() with Ctrl+Shift+p for debugging:
^+P:: SendInput f_print(_txt) => var _lbl = label.new(bar_index, highest(10)[1], _txt, xloc.bar_index, yloc.price, {#}00000000, label.style_none, color.gray, size.large, text.align_left), label.set_xy(_lbl, bar_index, highest(10)[1]), label.set_text(_lbl, _txt)`nf_print(){Left}

In scripts that will be published, we use this version, which is more flexible and more efficient, but can't be compressed to one line because of the if statements:
// ————— Print a label at end of chart.
f_print(_txt, _y, _color, _offsetLabels) =>
    var label _lbl = na
    _t = int(time + (time - time[1]) * _offsetLabels)
    if barstate.islast
        if na(_lbl)
            // Only create label once.
            _lbl := label.new(_t, _y, _txt, xloc.bar_time, yloc.price, #00000000, label.style_none, color.gray, size.large)
            // Fudge return type of `if` block so compiler doesn't complain (thx midtownsk8rguy for the trick).
            int(na)
        else
            // Rather than delete and recreate the label on every realtime bar update, update the label's information; it's more efficient.
            label.set_xy(_lbl, _t, _y)
            label.set_text(_lbl, _txt)
            label.set_textcolor(_lbl, _color)
            int(na)


text:
Q: increase font for all apps/menus in mac Is there an app to increase/change default fontsize for all applications in mac ?
It is really painful for me to read default fonts or to increase fontsize in every app I open, and even worse, the fontsize in many menus(as well as Finder match results) can not be modified!


text:
Q: How arr.sort() in nodeJS works? i am getting a strange result using arr.sort() below is the code
const arr=[1,99,102,121,2,2,3,7]
arr.sort()
console.log(arr)

I am getting the following output
[
  1, 1000, 121,  2,
  2,    3,   7, 99
]

can someone please explain what is happening and why?

A: Array.sort accepts a function as parameter:

compareFunction Optional
Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

You need arr.sort((a,b) => a - b)

A: As stated in the docs

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Thus your values are converted to strings first and then compared lexicographic. Ie "101" is less than "2"
If you want to do a numerical sort, you have to provide a compare function

const arr=[1,99,102,121,2,2,3,7]
arr.sort((a,b) => a-b);
console.log(arr);


text:
Q: in ldap make the default bind the current logged in user I do not want to specify a default bind_dn in the sssd.conf file for ldap (either openldap or active directory). Is it possible to configure the system in a way, that the first logged in user becomes the "default bind dn" user - from what I see any logged in user has the necessary permission to do the "default bind dn" job, to search the ldap directory for groups and users.
Therefore it would be nice if on a booted Linux (on which usally I am the only logged in user the first time), this functions which sssd requires to use would be my user, but without requiring to set a password in in sssd, simply by using my valid kerberos ticket from my login to search ldap, which i believe the default bind dn does most of the time.
Does anyboy have a solution, which would do such a trick?


text:
Q: How to print Custom Cell Rendered JTable data in Jasper Report I have a JTable with my own rendered column.I need to print table data with jasper report,as showing on swing application.is there any suggestion to do this with jasper report?
I tried with JRTableModelDataSource,but it is not what I need.
My table is look like this.


text:
Q: ArrayFormula not working as expected My original array formula worked fine:
=ArrayFormula(if(E3:E="NULL"),"Unknown",E3:E))

With this formula whenever the sheet imported data that expanded the number of rows, the array formula would fill down.
But this new formula does not. The formula calculates for the cell in which it is typed, but does not automatically copy down:
=ArrayFormula(if(or(E3:E="NULL",ISBLANK(E3:E)),"Unknown",E3:E))

How can I edit my second formula to copy all the way down the length of the document?

A: In array formulas instead OR() use ADD() or the + operator
=ArrayFormula(If((E3:E="NULL")+ISBLANK(E3:E),"Unknown",E3:E))


text:
Q: Understanding why $\vert \sum_{k = 1}^n \alpha_k f(x_k) \vert = \sum_{k = 1}^n \vert \alpha_k \vert$ in the calculation of a norm. The question and its solution are given in the following link:
Finding the norm of an operator.
Here is the solution:
Yes, your bound is correct. Let $X = C[0,1]$ with the $\sup$-norm and let $\{\alpha_k\}_{k = 1}^n \subset [0,1]$ as in the question. Let $f \in X$ be arbitrary with $\Vert f \Vert = 1$, then
$$  \vert Tf \vert = \vert \sum_{k = 1}^n \alpha_k f(x_k) \vert \leq \sum_{k = 1}^n \vert \alpha_k \Vert f \Vert_{\infty} \vert = \sum_{k = 1}^n \vert \alpha_k \vert $$
and hence $$\Vert T \Vert = \sup_{f \in X, \Vert f \Vert = 1} \vert Tf \vert \leq \sum_{k = 1}^n \vert \alpha_k \vert ~~.$$
In fact, this is the norm of the functional, since $\sum_{k = 1}^n \vert \alpha_k \vert$ is attained by the following function $f$. Define
$$ f(x) = \begin{cases} 1 & x = x_k, \alpha_k \geq 0 \\
-1 & x = x_k, \alpha_k < 0 \\
0 & x \in \{0,1\} \setminus \{x_k\}_{k =1}^n
\end{cases}$$
and linear interpolation otherwise. Then this function is continuous on $[0,1]$, it has $\Vert f \Vert = 1$, and we have
$$ \vert Tf \vert = \vert \sum_{k = 1}^n \alpha_k f(x_k) \vert = \sum_{k = 1}^n \vert \alpha_k \vert$$
where in the last step we use that all summands are positive. Hence $\Vert T \Vert \geq \sum_{k = 1}^n \vert \alpha_k \vert$, and thus we have equality.
My question is:
Why in the second line from below in the solution we have:
$$\vert \sum_{k = 1}^n \alpha_k f(x_k) \vert = \sum_{k = 1}^n \vert \alpha_k \vert$$

A: What $f$ is doing is basically swapping the sign of $\alpha_k$ if it is negative. In other words,
$$\alpha_k f(x_k) = |\alpha_k|$$
for each $1\leqslant k\leqslant n$. Thus equality follows immediately since all the summands are positive.


text:
Q: Android: Unable to create PDFRenderer I am currently having problem create PDFRenderer object. I have a pdf file inside the assets folder and using getAssets().openfd to get the file descriptor.
My code creating the object is:
try {
        _fileDescriptor = activity.getAssets().openFd(assetFile).getParcelFileDescriptor();
        _pdfRender = new PdfRenderer(_fileDescriptor);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

The error saying : java.io.IOException: not create document.  The fileDescriptor isn't null and the assetFile has a correct file path.
I am using the correct android api 21. I tried using lower version android but force close so I think not the phone problem


text:
Q: Cursor as PNG image? I am trying to make my cursor be a PNG image that I have already preloaded in an art game I am designing on P5.js.
I have tried so many things, but it still won't work!
Can someone please let me know where to put the cursor function as well as what to put inside the parentheses? Thanks so much!
function preload() {

  uImg = loadImage('assets/ufo.png');

  rImg = loadImage('assets/asteroid.png');

  bImg3 = loadImage('assets/bimg3.jpg');

}

function setup() {

  createCanvas(1200, 600);

  mode = 3; //level 3 in game

  noCursor();

}

// END OF SET UP

function draw() {

   levelThree();

}

// END OF DRAW

function levelThree() {

  clear();

  if (mode == 3) {

    lost = false;

    score = 0;

    background(bImg3);

    cursor(uImg,mouseX,mouseY);

  }
}

A: I think simply using image() instead of cursor() will do what you want. I don't know why, but I think that when using cursor() you can't input a p5.Image, you have to put a string of a URL to an image that exists on the internet.
Also, when using cursor(), the other two parameters should be between 0 and 31. They describe where the "active point" of the cursor is, relative to where the actual mouse point is.

A: You could just do something like this:
let img

function preload(){
  img = loadImage('cursor.png')
}

function setup() {
  createCanvas(400, 400);
  imageMode(CENTER)
  noCursor()
}

function draw() {
  background(20);
  image(img,mouseX,mouseY)
}

And you should put the option stuff in setup()   so the imageMode() and fill() and idk rectMode()... in setup, though what ever you're going to draw multiple times in draw() and you should load images in preload, cause javascript doesn't reallly care if images are loaded in or not and callback functions are meh, preload is good in my opinion. I also don't think that you really need the assets in assets/image.png
And also why exactly do you have mouseX and mouseY in the cursor() at the end of your code snippet???
hope this is actually answering the right question...


text:
Q: Inverse Laplace Transformation of incomplete gamma function in julia Recently, I have a problem in julia related with inverse laplace.
Here is the code that I write in julia.
using SpecialFunctions
using InverseLaplace

value = Talbot(u -> gamma_inc(1,u,2)[2], 80)
value(2)

This code make some error message like
MethodError: no method matching gamma_inc(::Float64, ::BigFloat, ::Int64, ::String)

Actually, I can calculate that kind of function in python already, based on mpmath.
import mpmath as mp

laplace = lambda u: mp.gammainc(1,u)
result = mp.invertlaplace(laplace, t = 2, method= 'talbot',degree = 80)

print(result)

and the result is
5.6730679553874e-43

I want to solve this problem on julia, and is there anyone who can give me any suggestion?
p.s. Sorry for my bad English. Hope you understand it..


text:
Q: Attaching Window Resize event to each element saparately I've been trying to figure out how, can I attach a Windows Resize event separately to each element (these elements are appended dynamically by PHP via ajax invoke).
The problem I also have is that I am utilizing global variables i.e. the variable id.
I am trying to figure out how I can attach Window Resize even separately to each element.
EDIT: Here's a screenshot.

A: If you are using jQuery, you can attach custom events to any element.
So, add the event "resize" (this event only exist for window element, so here, it's a custom event, you can name it like you want)
$("#" + id).on("resize", function(){

    // Do stuff here

});

And trigger it from window resize
$(window).on("resize", function(){

    $("#" + id).trigger("resize");

});

EDIT :
If you want that every "#" + id has "resize" event, event if appended in document later.
$(document).on("resize", "#" + id, function(){

    // Do stuff here

});

A: It had to do with the PHP and the id it assigned to the element, so all three elements have the same ID. That makes sense. So I modified the ID inline and realized the .each() method works.


text:
Q: Add add-on (extra) product in Shopify product page as a dropdown I want to add an add-on product to Shopify's product page as a dropdown. If the customer selects the add-on products, it adds it to the cart and the customer is redirected there.
For example, if the product page has a T-shirt, the add-on dropdown would be a cap. When clicking "Add to cart", the two are added to the cart if the add-on product is selected.

A: A checkbox makes more sense in your use case better than a drop down. What you need to do is:

*

*If the addon product checkbox is checked then you need to override the "add to cart" button behaviour or the product form submit, it depends if the form is ajaxified or not.

*Then you are going to have to use Shopify store Ajax API to add the two products, you won't be able to add the two products in one request to you are going to have to add one then add the other product when the first request is a success, then once its a success you get to redirect to cart page.

I didn't get into implementation details this is just a high level of what needs to be done, if you get stuck please share the code that you are working with so you may get some more help.
Good luck!


text:
Q: Searching SQL query after using INNER JOIN When displaying the table without the search it prints perfectly, when when adding the where query (which works fine in other search tables without inner join included) it produces a syntax error. Here is the code:
SELECT Date_entered, photo1, photo2, UserName, reserveName, species FROM Plant_Reserves
                        INNER JOIN Plant_Species ON Plant_Reserves.plantID = Plant_Species.plantID
                        INNER JOIN reserves ON Plant_Reserves.reserveID = reserves.reserveID
                        ORDER BY UserName WHERE UserName LIKE '%$search%'

Here is a copy of the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE UserName LIKE '%zz%'' at line 4

A: where comes before order by
SELECT Date_entered, photo1, photo2, UserName, reserveName, species
FROM Plant_Reserves
INNER JOIN Plant_Species ON Plant_Reserves.plantID = Plant_Species.plantID
INNER JOIN reserves ON Plant_Reserves.reserveID = reserves.reserveID
WHERE UserName LIKE '%$search%'
ORDER BY UserName

The defined order of keywords is
select
from
join
where
group by
having
order by
limit


text:
Q: Zend Framework: Ajax post data That is my function:
function deleteAutoAd(id, title) {
    alert(title);
    $.ajax({
        dataType: 'json',
        url: '/ajax/deleteautoad',
        type: 'POST',
        data: {
            id : id,
            title : title
        },
        success: function(data) {
            alert(data);
        }
    });
}

In this function when I try alert(title) and popup 'This is title'(because title = 'This is title'). But in ajax/deleteautoad I try this:
public function deleteautoadAction() {
    if ($this->getRequest()->isPost()) {
        echo $param1 = $this->_request->getParam('id');
        echo $param2 = $this->_request->getParam('title');
    }
}

Echo param1 show 5, but echo param2 don't show nothing.

A: i think you should try :
function deleteAutoAd(id, title) {
    alert(title);
    $.ajax({
        dataType: 'json',
        url: '/ajax/deleteautoad',
        type: 'POST',
        data: {
            'id' : id, // Note the quotes
            'title' : title // Note the quotes
        },
        success: function(data) {
            alert(data);
        }
    });
}

regards
mimiz

A: I agree with the above answer
Also, For my application, I also have to post the full url. So you might want to try
var root = location.protocol + '//' + location.host;

and then on your url
url: root+'/ajax/deleteautoad',

A: You should return from controller a valid JSON with Success status.
public function deleteautoadAction() {
    if ($this->getRequest()->isPost()) {
        $x->Status = 'Success';
        $x->Message = $this->_getParam('id') . $this->_getParam('title');
        $this->_helper->json($x);
    }
}

And also you should change your alert statement
function deleteAutoAd(id, title) {
    $.ajax({
        dataType: 'json',
        url: '/ajax/deleteautoad',
        type: 'POST',
        data: {
            id : id,
            title : title
        },
        success: function(data) {
            alert(data.Message);
        }
    });
}

A: Moved from the OP question to a CW answer:

I fixed the problem by removing: dataType: 'json'.


text:
Q: Error in the namenode, localhost during import of the file from hdfs I am using python-spark for a word count problem. My lines of codes for importing the text file located in my hdfs are:
file="hdfs://localhost:50070/user/hduser/input/sample.txt"
input=sc.textFile(file)

When I execute the program I get the following error:

py4j.protocol.Py4JJavaError: An error occurred while calling
  o25.collect. : java.io.IOException: Failed on local exception:
  com.google.protobuf.InvalidProtocolBufferException: Protocol message
  end-group tag did not match expected tag.; Host Details : local host
  is: "quickstart.cloudera/127.0.0.1"; destination host is:
  "localhost":50070;

Please help me to eradicate it. I am stuck.

A: Try running input=sc.textFile(file) where file="/user/hduser/input/sample.txt"
You don't need hdfs://localhost:50070/


text:
Q: Echo data json by json_decode I want echo value json_encode by json_decode, how is it?
Following php code is my try that not work:
$json = '[{"dg_j":"1390\/02\/05","dg_sh":"2011\/4\/25"}]';

$obj = json_decode($json);

echo $obj->{'dg_j'};
echo '<br>';
echo $obj->{'dg_sh'};

A: What you've got is actually an array that contains a single object. You'd want
$obj[0]->dg_j

Doing a var_dump($obj) will show you what the JSON actually turned into.

A: You can use either var_dump() or print_r(). var_dump is preferable as it would print all levels of object hierarchy.


text: Q: Android app, slow rotation My android app takes about 3-5 seconds before it actually rotates. The whole activity is just too big to post here. Can anyone provide me some general suggestions that can make this better? Thanks all.


text:
Q: Can a Google Glass application have menu buttons like an Android app? Can a Google Glass application have menu buttons like an Android app?

A: I assume you're referring to buttons that bring up context menus, etc in your app and you're loading your application on to the device directly rather than using the Mirror API.
Can it have buttons like a "standard" Android app? It's just Android so you can do whatever you want. At I/O 2013 there was a demo of running a regular Android app on Glass. A bluetooth keyboard was used to send input.
Should it have buttons like a "standard" Android app? The answer is probably no, because Glass provides a somewhat different interaction paradigm than a phone.


text:
Q: Implementing writes for a Play 2.1.1 I'm new to Play (and Scala). I'm trying to write a simple Play application that calls some Java code.
I want to convert a scala.collection.mutable.Map[String,Array[String]] to a JSON String. But this clearly doens't work.
Based on this I'm assuming I've to implement Writes. My current code (which is clearly incorrect) looks like the following:
implicit val myWrites = new Writes[scala.collection.mutable.Map[String,Array[String]]] {

def writes(res: scala.collection.mutable.Map[String,Array[String]]) = {

  val x  = res.foreach { kv => Json.obj(
      kv._1 -> ( kv._2.reduceLeft(_ + "," + _).mkString)

    ) }

    Json.toJson(x)

  }

}

Any pointers that will help me make progress would be appreciated.

A: You don't have to write any Writes implementation. All you need to do is transform the mutable map into an immutable one, simply by calling the toMap method:
scala> import play.api.libs.json._
import play.api.libs.json._

scala> import scala.collection.mutable
import scala.collection.mutable

scala> val im = Map("foo" -> Array("bar", "baz"))
im: scala.collection.immutable.Map[String,Array[String]] = Map(foo -> Array(bar, baz))

scala> Json.stringify(Json.toJson(im))
res8: String = {"foo":["bar","baz"]}

scala> val mm = mutable.Map("foo" -> Array("bar", "baz"))
mm: scala.collection.mutable.Map[String,Array[String]] = Map(foo -> Array(bar, baz))

scala> Json.stringify(Json.toJson(mm))
<console>:20: error: No Json deserializer found for type scala.collection.mutable.Map[String,Array[String]]. Try to implement an implicit Writes or Format for this type.
              Json.stringify(Json.toJson(mm))
                                        ^

scala> Json.stringify(Json.toJson(mm.toMap))
res10: String = {"foo":["bar","baz"]}


text:
Q: Convergence of Sum of Random variable to another - Cantor function Let $(X_{n})_{n\geq1}$ be i.i.d. Ber$\left(\frac{1}{2}\right)$. I want to show that $$\sum_{{n\geq1}}\frac{2X_{n}}{3^{n}}$$ converges almost surely to a random variable $X$, without saying that this random variable distribution is Cantor-Distribution. I guess we should use Borel–Cantelli somehow - but I am not sure about it. Can you please help?
Thanks.

A: Note that the $X_n$ are bounded by $1$, so the absolute convergence follows from the convergence of the sum $\sum \limits_{n = 1}^\infty \frac{2}{3^n}$.

A: Formally, there is a probability space $Ω$ (with a $σ$-algebra $\mathcal F$ and a probability measure $P$) and the random variables $X_n$ map $Ω$ to $\mathbb R$ (with $\mathcal B(\mathbb R)$) as follows
\begin{align}X_n:Ω&\mapsto \mathbb R\\[0.2cm]ω &\to \{0,1\} \end{align} with $P(\{ω:X_n(ω)=1\})=P(\{ω:X_n(ω)=1\})=1/2$. Now, take an $ω \in Ω$ and see what happens to the series $$\sum_{n\ge 1}\frac{2}{3^n}X_n(ω)$$ By definition $X_n(ω)=0$ or $=1$ and therefore certainly $X_n(ω)\le 1$. Hence, $$\sum_{n\ge 1}\frac{2}{3^n}X_n(ω)\le \sum_{n\ge 1}\frac{2}{3^n}=2\cdot\frac{1}{1-\frac13}=3$$ and therefore by comparison test, the series converges. This is true for any $ω\in Ω$, therefore in particular almost surely. (Note: we did not calculate the limit of the series, we just showed that is converges for almost all (actually for all) $ω\in Ω$).


text:
Q: Yii2 pjax don't update div in container I have code like this in my view:
<?php \yii\widgets\Pjax::begin(['id'=>'client-info']);?>

<?php \yii\widgets\Pjax::end(); ?>

I am updating container via js like this
 $.pjax.reload({container:'#client-info',timeout:false});

Can I prevent #some-div from updating?
I need pjax to update all except one #some-div. I cannot change pjax begin and end position because then I will have to change page layout fully.

A: You can have multiple pjax sections.
<?php \yii\widgets\Pjax::begin(['id'=>'some-id-one']);?>

<?php \yii\widgets\Pjax::end(); ?>

<?php \yii\widgets\Pjax::begin(['id'=>'some-id-two']);?>

<?php \yii\widgets\Pjax::end(); ?>

And then you need to reload both containers.
$.pjax.reload({container:'#some-id-one',timeout:false});
$.pjax.reload({container:'#some-id-two',timeout:false});

Probably you can have better solution by modifying pjax.


text:
Q: Processor Throttling, Speeds and Battery life Does throttling the CPU down give you more battery life? Does i3 give you more battery life over an i7? Just I've not had the options to really test this theory as it requires having the same laptops just different CPUS.

A:
Does throttling the CPU down give you more battery life?

Yes. Throttling the CPU would result in less of it's processing power being utilized, which would result in it requiring less energy and generate less heat.

Does i3 give you more battery life over an i7?

It depends on which i3 and i7 you are comparing, there are many versions of each. You could simply look at the wattage rating for the processors you are comparing and the one that is higher would consume more power. No testing necessary.


text:
Q: Can I script Data Classifications in SQL Azure I am looking into SQL Data Classifications in SQL Azure.
To do this I must log onto the Azure Portal for each database and configure the Data Classifications. I have 100 databases for seperate clients all with the same schema.
Is there a way I can Script these classifications using SQL?
I'm guessing there is a sys table where these classicfication tags are stored?

A: I just received the following answer from the  SQL Security Vulnerability Assessment Team at Microsoft: "Such scripting capabilities are coming for Data Classification soon". At this time there are no scripting capabilities.


text:
Q: toString() of Undefined in Universally Rendered(React&Express&AltJS) through Webpack I have a strange issue and I'm not sure what part of my stack is responsible for throwing the error. I currently have an es6/webpack/react-router rc2/flux(altjs) isomorphically(universally) rendered application. If there are any bugs on any part of the frontend(syntax error or otherwise) or an api endpoint is incorrect/not responding the appropriate data format(i.e. an array isn't being sent back which therefore cannot be mapped over by one of my react components) the server crashes with the following error

Cannot read property statuscode.toString() of undefined

Is this react-router related? Webpack related? React related? I wish I could have a more informative stack trace because as I work through the backend as I'm not sure what is incorrect, whether it is front-end code or backend code. Is there any way to "catch" what is occurring. To clarify nothing else changes but the expected data structure which throws this error.
Edit:
export default class Dashboard extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        data: DataStore.getState().data
    };
}

render() {
    return (
        <div className='dashboard'>
            <Tile gridWidth='cute-6-laptop' linkTo='/data/temperature/water' size='regularTile' title='Water Temperature'>
                <OverviewChart data={this.state.data.Water_Demand.devices} mapObj={mapObjs.water} keyData={[{key: null, value: this.state.data.Water_Demand.devices[2].readings[this.state.data.Water_Demand.devices[2].readings.length - 1].rate, units: this.state.data.Water_Demand.devices[2].rateUnits}]} chartClass='interiorTemperature' includeNavChart={false} includeBarChart={false} w='473' h='180'/>
            </Tile>
        </div>
    );
}
}


text:
Q: Intermittent #error on textbox with fairly simple IIF I've a Customer form with a tab control that holds the details for the specific items that a customer has: Ground Rent, Electricity and Garage. They may hold all 3, just Ground Rent and Electricity, or just a garage. If they don't have an item, the tab is hidden.
The issue only appears on the Garage tab: I intermittently get #ERROR in the amountdue text box. If I close down the customer and re-open them, sometimes it clears itself (with no action performed). Sometimes it doesn't. Sometimes it needs me to reopen a few times before the value shows.
The box concerned is: txtActualAmountDue and the source is the following:
=iif([tenant],[txtNet],[txtGarageCharge])

*

*Tenant is a form data source Boolean (that indicates whether the Ground Rent/Electricity tabs should be shown).

*txtNet = [txtGarageCharge]-[txtVAT]

*txtVAT = [txtGarageCharge]*([txtVatPercentage]/(1+[txtVatPercentage]))
The next two are locked textboxes to make life easier

*

*txtGarageCharge = DLookup("[GarageCharge]","Variables", criteria that returns the current row of variables for the current date)

*txtVatPercentage = DLookup("[GarageVat]","Variables", criteria that returns the current row of variables for the current date)

The only thing else I can think of to mention is that if the customer is not a tenant, then txtNet and txtVAT are hidden. I sometimes get #Type! in txtNet and txtVat too - and obviously I also get the #Error - but not always: sometimes they're valued okay and I still get the #Error. I've commented out the load/current method lines that hides those textboxes to see if it's that, but it's made no difference.
Like I say - it's not like it happens every time: Just occasionally. Could it be to do with the order in which things are being valued/populated on the form? And once it's been populated once (the values will be the same for every customer) then it's okay? And if it's this, how do I force it to value the text boxes in the right order?

A: It is probably a timing issue, so try avoiding the mid calculations:
txtNet = DLookup("[GarageCharge]/(1+[GarageVat])","Variables", criteria)
txtVat = DLookup("[GarageCharge]/(1+[GarageVat])*[GarageVat]","Variables", criteria)

or, ultimatively:
=IIf([tenant],DLookup("[GarageCharge]/(1+[GarageVat])","Variables", criteria),DLookup("[GarageCharge]","Variables", criteria))


text:
Q: FileNotFoundError: [Errno 2] No such file or directory, while the file does exist and it's in the same folder I'm coding something and I need to open a .txt file on the code. I have both the code and the text file in the same folder, yet I still get this error: FileNotFoundError: [Errno 2] No such file or directory: 'dis_rules.txt'. The code I wrote was directly taken from a different thread on this page, and obviouly the file name written in the code is identical. Here's the folder with both files on it.
Here's the code I've used too:
fp = open(r"dis_rules.txt", 'r')
print(fp.read())

What could be wrong on this? Thank you for your help!

A: Thanks to the comments you guys posted I got to solve the issue. As you all said, the problem was that the current directory of the file was different to the folder's directory. To solve this, I had to use the os.chdir() method to change the currently directory to the folder's directory, this way:
import os

path = "C:\\Users\\utente\\Desktop\\_rules2"
os.chdir(path)

After that I just added the code I posted on the question and it worked just fine.
Thank you everyone for your help!

A: I'm relatively new to python, and i've never seen this method of opening a text file... Try like this:
with open('dis_rules.txt','r') as f:
    print(f.readlines())

Also, not sure you need to use an r-string...
Tell me if that helps!


text:
Q: $lookup within the same collection is nesting docs instead of returning all docs Dealing with $lookup was fun until I thought of makeing a join withing the same collection.
Say I have the next collection:
{'_id': ObjectId('5a1a62026462db0032897179'),
'department': ObjectId('5a1982646462db032d58c3f9'),
'name': 'Standards and Quality Department',
'type': 'sub'}, {
'_id': ObjectId('5a1982646462db032d58c3f9'),
'department': false,
'desc': 'Operations Department',
'type': 'main'}

As clearly it says, there's backlinking within the same collection using the department key which could be false to indicate highest level department.
I'm using the next query (Python) to populate the results:
query = [{'$lookup': {'as': '__department',
              'foreignField': '_id',
              'from': 'departments',
              'localField': 'department'}},
 {'$unwind': '$__department'},
 {'$group': {'__department': {'$first': '$__department'},
             '_id': '$_id',
             'department': {'$first': '$department'},
             'name': {'$first': '$name'},
             'type': {'$first': '$type'}}}]
for doc in conn.db.departments.aggregate(query): pprint(doc)

What I'm expecting to get:
{'__department': None,
 '_id': ObjectId('5a1982646462db032d58c3f9'),
 'department': false,
 'name': 'Operations Department',
 'type': 'main'},
{'__department': {'_id': ObjectId('5a1982646462db032d58c3f9'),
                  'department': 'false',
                  'name': 'Operations Department',
                  'type': 'main'},
 '_id': ObjectId('5a1a62026462db0032897179'),
 'department': ObjectId('5a1982646462db032d58c3f9'),
 'name': 'Standards and Quality Department',
 'type': 'sub'}

What I'm actually getting is:
{'__department': {'_id': ObjectId('5a1982646462db032d58c3f9'),
                  'department': 'false',
                  'name': 'Operations Department',
                  'type': 'main'},
 '_id': ObjectId('5a1a62026462db0032897179'),
 'department': ObjectId('5a1982646462db032d58c3f9'),
 'name': 'Standards and Quality Department',
 'type': 'sub'}

I'm not sure why $unwind is grouping both the docs together although before applying $unwind I do get both of them separatly.
Any suggestions?

A: That is because you create an empty array __department in the document that didn't find a match in the $lookup. This is how your orphan document looks like:
{
    "_id" : ObjectId("5a1982646462db032d58c3f9"),
    "department" : false,
    "desc" : "Operations Department",
    "type" : "main",
    "__department" : []
}

When you are unwinding there is nothing to $unwind in this document, so it gets lost in the process. If you want to keep it you have to "normalize" your array. So you'd have to add this after your $lookup and before your $unwind:
{
        $project: {
            _id: 1,
            department: 1,
            name: 1,
            type: 1,
            __department: {
                $cond: [{
                        $eq: ["$__department", []]
                    },
                    [{
                        _id: 0,
                        department: "None",
                        desc: "None",
                        type: "None"
                    }], '$__department'
                ]
            }
        }
    }

So all together it should look like that:
[{
        '$lookup': {
            'as': '__department',
            'foreignField': '_id',
            'from': 'depart',
            'localField': 'department'
        }
    },
    {
        '$project': {
            _id: 1,
            department: 1,
            name: 1,
            type: 1,
            __department: {
                $cond: [{
                        $eq: ["$__department", []]
                    },
                    [{
                        _id: 0,
                        department: "None",
                        desc: "None",
                        type: "None"
                    }], '$__department'
                ]
            }
        }
    },
    {'$unwind': "$__department"},
    {'$group': {'__department': {'$first': '$__department'},
             '_id': '$_id',
             'department': {'$first': '$department'},
             'name': {'$first': '$name'},
             'type': {'$first': '$type'}}}]


text:
Q: Multivariate repeated measures without between subject factors (Manova vs Anova) I'm trying to run an analysis in SPSS on some EEG data, obtained with the following design:

*

*1 within subject factor,

*6 dependent outcome variables.

First, I was thinking about a repeated measures ANOVA, however that wouldn't take into account the dependency of the outcome variables.
So, MANOVA? However, all documentation on MANOVA seems to include a between subjects factor (which I don't have).


text:
Q: Как сделать такую же ветку gh-pages? Возможно я выражусь неправильно, но я попытаюсь обьяснить. У меня есть репозиторий в котором у меня лежат домашние задания в папка по такому пути:
homeworks/homework_1/index.html
homeworks/homework_2/index.html

Я хочу создать отдельную ветку (gh-pages) как в этом профиле https://github.com/SvetlanaSharkunova/vanilla-js-miniprojects-FCC/tree/gh-pages
и в основной веткее (main) в readme.md указать ссылки на домашние работы. Подскажите пожалуйста, как реализовать?


text:
Q: Daterange validation for multiple from-to dates in jQuery I have done the date range validation of a start date and end date.
html
  StartDate

    <input type="text" id="startdate" class="form-control" />

 EndDate

    <input type="text" id="enddate" class="form-control" />

jquery
       $(function () {

        $('#startdate,#enddate').datetimepicker({
            useCurrent: false,
            minDate: moment()
        });
        $('#startdate').datetimepicker().on('dp.change', function (e) {
            var incrementDay = moment(new Date(e.date));
            incrementDay.add(1, 'days');
            $('#enddate').data('DateTimePicker').minDate(incrementDay);
            $(this).data("DateTimePicker").hide();
        });

        $('#enddate').datetimepicker().on('dp.change', function (e) {
            var decrementDay = moment(new Date(e.date));
            decrementDay.subtract(1, 'days');
            $('#startdate').data('DateTimePicker').maxDate(decrementDay);
             $(this).data("DateTimePicker").hide();
        });

    });

This code is working properly. But I need to set another start date and end date dynamically.
The validation for this is like the first end date less than the second start date and the second end date less than the third start date.

A: ** html **

     Start Date

        <input type='text' class="form-control" name='startdate_1' id='startdate_1' placeholder='Start Date' value=""/>

      End Date

        <input type='text' class="form-control" name='priceend_1' id='priceend_1' placeholder='End Date' value="" />

<button type="button" class="add_field_button btn btn-info " id="add-field">Add Price</button>

** jquery **
  $( document ).ready(function() {
  var counter = 1;

        $('#startdate_1,#priceend_1').datetimepicker({
          format: 'YYYY-MM-DD',
          useCurrent: false
     });

     $('#startdate_1').datetimepicker().on('dp.change', function (e) {
         var incrementDay = moment(new Date(e.date));
         incrementDay.add(1, 'days');
         $('#priceend_1').data('DateTimePicker').minDate(incrementDay);
         $(this).data("DateTimePicker").hide();
     });

     $('#priceend_1').datetimepicker().on('dp.change', function (e) {
         var decrementDay = moment(new Date(e.date));
         decrementDay.subtract(1, 'days');
         $('#startdate_1').data('DateTimePicker').maxDate(decrementDay);
          $(this).data("DateTimePicker").hide();
     });

    var incre=2;
    $('#add-field').click(function(){
    counter += 1;
    incre += 1;
    //alert(counter)
  $('.multi-field').append('
Start Date
<input type="text" class="form-control" name="startdate_' + counter + '" id="startdate_' + counter + '" placeholder="Check-in date" value=""/>

End Date
<input type="text" class="form-control" name="priceend_' + counter + '" id="priceend_' + counter + '" placeholder="priceend" value="" />

' );
    $('#startdate_'+counter +',#priceend_'+counter).datetimepicker({
       format: 'YYYY-MM-DD',
       useCurrent: false
   });

   var newdec= counter;
   newdec -=1;
    var decrementDay1 =  $('#priceend_'+newdec).val();
    var decrementDay1 = moment(new Date(decrementDay1));
       decrementDay1.add(1, 'days');
     $('#startdate_'+counter).data('DateTimePicker').minDate(decrementDay1);

      $('#startdate_'+counter).datetimepicker().on('dp.change', function (e) {
     var decrementDay1 =  $('#startdate_'+counter).val();
    var decrementDay1 = moment(new Date(decrementDay1));
       decrementDay1.add(1, 'days');
     $('#priceend_'+counter).data('DateTimePicker').minDate(decrementDay1);

     });
            $("#count_c").val(counter);
    });
 $("#count_c").val(counter);

});
please refer this js fiddle for further clarification,
 {{https://jsfiddle.net/1oLtoum2/2/}}


text:
Q: How to point my subdomain to a particular port with nginx I am trying to point my subdomain to a particular port of my server, but the issue is that when I go to that subdomain it shows:
This site can't be reached
What I need is like this:
When i go to https://auth.domain.com, to point me to my server on aws: https://ec2.domain.aws:8443, but its failing to do so
Here's my nginx.conf file:
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        server_name  localhost;

        root   /angularapp/dist;
        index  index.html index.htm;
        include /etc/nginx/mime.types;

        gzip on;
        gzip_min_length 1000;
        gzip_proxied expired no-cache no-store private auth;
        gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        location / {
            try_files $uri $uri/ /index.html;
        }
    }
    server {
        listen 80;
        server_name  auth.domain.com;

        location / {
            proxy_pass https://ec2.domain.aws:8443;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
}

What I was trying to do here is that in the first server when it access to localhost (domain.com) to just show the index.html file which is working perfectly, and on my second server when the user tries to access to auth.domain.com to point that to https://ec2.domain.aws:8443.
Am I missing something or this is just not the way that I should do it?
Also the second server solution I found it on:
https://www.digitalocean.com/community/questions/how-do-i-point-my-custom-domain-to-my-ip-port-41-111-20-36-8080
Thank You

A: please try using the config as below.
location auth.domain.com {
               proxy_pass https://ec2.domain.aws:8443;
               proxy_set_header Host $host;
               proxy_set_header X-Real-IP $remote_addr;
               proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
               proxy_set_header X-Forwarded-Proto $scheme;
        }

A: Set HTTP Host header equal to your AWS domain name:
proxy_set_header Host ec2.domain.aws;

If this does not help, try turning on SNI for proxied HTTPS requests with the proxy_ssl_server_name directive:
proxy_ssl_server_name on;


text:
Q: Playframework 2.0 in IntelliJ IDEA Routes File Association What's the right file type for IDEA to pick up the Play Framework Routes file?

A: Enable Play2 Framework 2 Support Plugin

* Make sure Play Framework support is not clicked(for Play Framework 1.0)
HTML routing support for Play 2 Framework

IDEA Routes Context Menu
Mark the routes file with "Play 2 routing"

A: Html routing support for play 2 framework:

A: The only thing that worked for me was to right click on the routes file, then associate it with the Plain Text file type. Without this, it would re-indent all lines in the file.


text:
Q: Let $f$ be a continuous and positive function on $\mathbb{R}_{+} $ such that $\lim_{x \to \infty} <1$ Let $f$ be a continuous and positive function on $\mathbb{R}_{+}$ such that $\displaystyle\underset{x \to \infty}{\lim} \frac{f(x)}{x} <1$.
Prove the equation $$f(x)=x$$ has at least one solution on $\mathbb{R}_{+}$.

A: If $f(0)=0$, done. If not $g(x)=f(x)-x, g(0)>0$ and there exists $x>0$ such that $f(x)/x<1$ which implies that $g(x)=f(x)-x<0$, applies IVT at $g$ in $[0,x]$.


text:
Q: Scanf not reading in double I am trying to read in a double value continuously from the user  using scanf.
Code:
printf("Enter A value: \n");
double input;
int result = scanf("%f", &input);
printf("INPUT: %f\n", input);

The output is
INPUT: 0.000

A: You lied to the compiler: when scanning, %f says you supply a pointer to float. But you provided a pointer to double.
To fix, either use %lf or declare input as float.
Note that there is an asymmetry with printf formats, which uses %f for both float and double arguments. This works because printf arguments are promoted to double (and are not pointers).

A:
I am trying to read in a double value continuously from the user using scanf.

To do so you need a loop, like the following:
while(scanf("%lf", &input) == 1) {
    //code goes here...
    printf("INPUT: %lf\n", input);
    //code goes here...
}

Note that, as the primitive type of input is double, you need to use %lf instead of %f (%fused for float).


text:
Q: How do you multiply a quanternion by a vector3 in unity? I have this code:
private Transform player;
// Start is called before the first frame update
void Start()
{
    player = Object.FindObjectOfType<PlayerIdentifier>().transform;
}

// Update is called once per frame
void Update()
{
    float newPosX = (Quaternion.AngleAxis(player.rotation.z, Vector2.up) * player.position).x;
    float newPosY = (Quaternion.AngleAxis(transform.rotation.z,Vector2.up)*transform.position).y;
    Vector3 newPos = new Vector3(newPosX, newPosY);
    newPos = newPos * Quaternion.AngleAxis(transform.rotation.z, Vector2.up);
    transform.position = newPos;
}

You see, I am getting an error on the 13th line saying that Quanternions cannot be multiplied by Vector3. Any way to multiply them without an error message?

A: Nevermind, you have to put the Quanternion before the Vector3 Like this Quaternion qua = Quanternion.Euler(0,0,90); Vector3 vect = new Vector3(0,1,0); Vector3 output=qua*vect;


text:
Q: link_to on an unsaved association in a loop causing path error I have a link_to inside of an each loop.  The object that's being looped does indeed contain a new record (sometimes).   The parent object is a book and the nested object is photo.
- @book.photos.each do |photo|
  = link_to image_tag(photo.pic.url), edit_book_photo_path(@book)

And the error is, rather predictably:
No route matches {:action=>"edit", :controller=>"photos", :id=>nil, :book_id=>147, :format=>nil} missing required keys: [:id]

I have tried checking for a new_record using:
- @book.photos.each do |photo|
  = link_to image_tag(photo.pic.url), edit_book_photo_path(@book) unless photo.new_record?

And
- @book.photos.each do |photo|
  - unless photo.new_record?
    = link_to image_tag(photo.pic.url), edit_book_photo_path(@book)

But get the same error.
That unless works fine if I'm not doing a link_to, for instance if I create a list
%ul
  - @book.photos.each do |photo|
    - unless photo.new_record?
      %li= "This is id #{photo.id}"

I see see that there are the correct number of child objects and removing the unless gives me one extra with no id.
So, clearly I'm making this overly complicated, because it should be simple or I've gone astray.  The GOAL::: Render a list of images (@book.photos.pic) on the book's form, each image is a link to edit the photo record.
Suggestion?

A: Try adding picture id:
- @book.photos.each do |photo|
  = link_to image_tag(photo.pic.url), edit_book_photo_path(@book, photo)

A: - @book.photos.select(&:persisted?).each do |photo|
  = link_to image_tag(photo.pic.url), edit_book_photo_path(@book, photo)


text:
Q: Equitable partitions in the undirected graph Let $G$ be an undirected simple graph with the adjacency matrix $A$. Let $P_{\pi}$ be the characteristic matrix for an equitable partition $\pi$, such that $A P_{\pi} = P_{\pi} B_{\pi}$, i.e., $B_{\pi}$ is the quotient matrix for the  partition $\pi$. We know that for any eigen-pair $(\lambda,v)$ of $B_{\pi}$ we have an eigen-pair $(\lambda, P_{\pi} v)$ for $A$. On the other hand $A$ is diagonalizable, since it is real symmetric.
Now, my intuition is that for any $\pi$,  $B_{\pi}$ is always diagonalizable, but, how to prove / disprove it?

A: Prove that the minimal polynomial of $B$ divides that of $A$ (which follows from $AP=PB$) and then use the fact that a matrix is diagonalizable if and only if its minimal polynomial has no repeated factors.


text:
Q: Line divides side of regular pentagon in Golden ratio
In the figure, construct an equilateral triangle inside regular pentagon. The line connecting orthocenter and the second Isodynamic point of green triangle divides the side of pentagon in red and blue segments.

My question. How to prove that $$\frac{\rm{\color{red}{red}}}{\rm{ \color{blue}{blue}}}=\frac{\sqrt{5}+1}{2}?$$

A: Here's a thoroughly-unsatisfying approach that makes absolutely no attempt to exploit the specific geometry of the situation. It's just an algebraic slog.

First, we define $\theta := 6^\circ$, $c:=\cos\theta$, $s := \sin\theta$, noting that the minimal polynomial for $s$ is
$$\mu(s) = 1- 8s-16s^2+8s^3+16s^4 \tag{1}$$
Now, consider an origin-centered pentagon of circumradius $r$, with vertices $A$, $B$, $U$, $V$ as shown:

Point $C$ is the apex of the equilateral triangle erected upon the side opposite $A$. A little angle-chasing gives the various measures as multiples of $\theta$. Note that
$$\frac{|OC|}{\sin\theta} = \frac{r}{\sin 5\theta} \quad\to\quad |OC| = 2 r \sin\theta = 2 r s \tag{2}$$
Abusing notation and writing $\operatorname{cis}\psi = (\cos\psi ,\sin\psi)$, we can coordinatize thusly:
$$A = r \operatorname{cis}0 \qquad B = r \operatorname{cis} 12\theta \qquad C = (2r s,0)$$
$$U= r\operatorname{cis}(-24\theta) \qquad V = r\operatorname{cis}(-12\theta) \tag{3}$$
With the help of a computer algebra system, we expand the various trig functions, re-write as much as possible in terms of $s=\sin\theta$, and reduce modulo $\mu(s)$ to get
$$\begin{align}
A &= r (1, 0) \\[4pt]
B &= r \left(\;s \left(3 - 4 s^2\right), c \left(1 - 4 s^2\right)\;\right) \\[4pt]
C &= r ( 2 s, 0 ) \\[8pt]
U &= r \left(\;\tfrac12\left(-1 - 6 s + 8 s^3\right), -c \left( 1 - 2 s\right) \left( 1 - 2 s - 4 s^2\right)\;\right) \\[4pt]
V &= r\left(\; s \left( 3 - 4 s^2 \right), -c \left( 1 - 4 s^2\right)\;\right)
\end{align}\tag{4}$$
Orthocenter $P$ has barycentric coordinates
$$\alpha:\beta:\gamma \;=\;\sin A \cos B \cos C : \cos A \sin B \cos C : \cos A \cos B \sin C \tag{5}$$
so that, after the same kind of reduction as above, we get
$$P = \frac{\alpha A + \beta B + \gamma C}{\alpha+\beta+\gamma} = \left(\;
\frac{r ( 5 + 14 s - 4 s^2 - 16 s^3)}{
 2 (9 + 14 s - 8 s^2 - 16 s^3)}\;,\;
\frac{ c r (1-2s)^2 (1+2s)}{9 + 14 s - 8 s^2 - 16 s^3}\;\right) \tag{6}$$
Second-Isodynamic Point $Q$ has barycentric coordinates
$$\alpha:\beta:\gamma = \sin A \sin(A-60^\circ) : \sin B \sin(B-60^\circ) : \sin C \sin(C-60^\circ) \tag{7}$$
so that
$$Q = \left(\;-\frac{r ( 11 + 8 s - 12 s^2 - 8 s^3)}{
  2 (9 + 14 s - 8 s^2 - 16 s^3)}\;,\;
-\frac{2 c r (8 + 11 s - 8 s^2 - 12 s^3)}{ 9 + 14 s - 8 s^2 - 16 s^3}\;\right) \tag{8}$$
And, noting that we can write the Golden Ratio as $\phi = 2 \cos 6\theta$, and taking $W$ as the point that separates $\overline{UV}$ in that ratio, we have
$$W = \frac{U + \phi V}{1+\phi} = \left(\;
-\frac{r s (3 - 4 s^2)}{2 (1 - s) (1 + 2 s)^2}\;,\;
-\frac{c r (1 - 2 s)^2 (3 + 4 s)}{2 (1 - s) (1 + 2 s)^2}
\;\right) \tag{9}$$
Now, we "simply" determine the equation of the line through $P$ and $Q$, which "reduces" to
$$\begin{align}
2 c x &( 171 + 254 s - 180 s^2 - 264 s^3) \\
- \phantom{2x}y &( 163 + 254 s - 164 s^2 - 272 s^3) \\
= 2 c r &( 47 + 68 s - 48 s^2 - 72 s^3)
\end{align}\tag{10}$$
Finally, we substitute $W$ into this equation, reduce modulo $\mu(s)$, and find that everything vanishes, verifying the claim. $\square$

While this approach offers no hint as to what magic lurks in the result, knowing that the proposition is true assures us that the quest for a magic-revealing proof is not inherently doomed.

Addendum. As one might expect, a few sign changes in the above analysis would work themselves out to validate a related result. Specifically, if we take $C$ to be apex of an equilateral triangle erected on the outside of the pentagon, and we take $Q$ to be the first isodynamic point of $\triangle ABC$, then the line through $Q$ and orthocenter $P$ meets $\overline{UV}$ in the same $W$, dividing the segment in the golden ratio.

I'll forego rewriting all the equations here, as I'm still seeking an appropriately-magical approach to understanding this construction. However, I'll give the following unifying notes:
$$C = r \left(\; -2 \sin(9\theta \mp 10\theta), 0\;\right) = r\left(\;-2\sin(9\theta\mp 60^\circ), 0\;\right)$$
$$\angle B = 12\theta \mp 5\theta = 12\theta\mp 30^\circ \qquad \angle C = 9\theta \pm 5 \theta = 9\theta\pm 30^\circ$$
$$Q \;\stackrel{\text{bary}}{=}\; \sin A \sin(A\mp 60^\circ):\cdots$$
where, in each "$\pm$" and "$\mp$", the top sign corresponds to OP's construction, and the bottom corresponds to mine. Seeing that the angles vary by multiples of $60^\circ$ is nicely compatible with the change in the isodynamic point's coordinates.

Addendum 2. What works for pentagons often works for pentagrams, and that's the case here ... mostly. Curiously, the Second Isodynamic Point appears in both constructions; the First Isodynamic Point may also lead to another golden ratio somewhere, but I haven't looked very hard for it.

The figure shows a composite of two constructions with an equilateral triangle (apexes $C$ and $C'$) erected upon the edge of a pentagram (ie, a diagonal of the pentagon). Points $P$ (not shown) and $P'$ are the respective orthocenters, and $Q$ and $Q'$ the respective Second Isodynamic Points. Lines $\overleftrightarrow{PQ}$ and $\overleftrightarrow{P'Q'}$ concur with edge $\overleftrightarrow{UV}$ at $W$, such that $|VW|/|UW|=|UW|/|UV|=\phi$.
Interestingly, $\overleftrightarrow{UV}$ bisects $\angle QWQ'$, and $\overline{QW}\cong\overline{Q'W}$. This seems like it should be significant, but I don't know how.
For comparison, here's a composite image of the two pentagon constructions, showing the corresponding possibly-significant relations among $W$, $Q$, and $Q'$.

There's something going on here, but I just can't see it (yet).

A: Here's a much better argument than my previous attempt. I'm leaving out a few details due to time constraints, but will update later.

Let pentagon $ABCDE$ have side-length $s$, and let $F$ be the apex of an equilateral triangle erected internally upon $\overline{CD}$. The orthocenter of $\triangle ABF$ is the intersection of $\overline{BE}$ with the perpendicular $\overline{FF'}$ from $F$ to $\overline{AB}$. Let $X$ be the point that separates $\overline{DE}$ in the golden ratio: $|DX|/|XE|=\phi$. Here's the key insight (proof left to the reader for now):

The Second Isodynamic Point of $\triangle ABF$ is the apex ($Q$) of an equilateral triangle erected externally upon $\overline{DE}$.

We establish the result by showing the collinearity of $P$, $Q$, $X$ via Menelaus' Theorem applied to $\triangle BEM$, where $M$ is the midpoint of $\overline{DE}$. A little angle chasing gives the various angle measures; we also use the facts $|BE|=s\phi$ and $\phi-1=\phi^{-1}$. Calculating the appropriate signed ratios ...
$$\begin{align}
\frac{|EX|}{|XM|}&=\phantom{-}\frac{s/(1+\phi)}{s/2-s/(1+\phi)}=\frac{2}{\phi-1} = 2\phi  \\[4pt]
\frac{|MQ|}{|QB|}&= -\frac{s\sin 60^\circ}{|EB|\sin\angle BEQ/\sin\angle BQE}= -\frac{s\sin 60^\circ}{s\phi\sin 132^\circ/\sin 30^\circ}= -\frac{s\sin 60^\circ}{2\phi\sin 48^\circ} \\[8pt]
\frac{|BP|}{|PE|} &= \phantom{-}\frac{|BF|\sin 48^\circ/\sin\angle FPB}{|EF|\sin 120^\circ/\sin\angle FPE} = \frac{\sin 48^\circ}{\sin 60^\circ}
\end{align}$$
... we see that their product is $-1$. Thus, Menelaus holds, and collinearity is verified. $\square$
Note: When $F$ is the apex of the triangle erected externally on $\overline{CD}$, then the First Isodynamic Point of $\triangle ABF$ is the apex of the triangle erected internally on $\overline{DE}$, and a similar argument holds to give the companion construction I described in my previous answer. The pentagram constructions follow similarly.


text:
Q: Как "найти и заменить по ВПР" по списку, часть текста У меня есть в Гугл таблицах:

*

*Список файлов для переименования

*Список старых названий

*и параллельно ему список новых названий

Надо заменить старые названия на новые, сохранив при этом формат фалов suffix prefix.
Думаю надо найти "Старое название" в "Списке файлов" и заменить на "Новое название" по ВПР
Что пребывал:

*

*Удалить формат suffix prefix , потом по ВПР подобрать замену, но потом не понятно как вернуть такой же формат suffix prefix

=ARRAYFORMULA(ПОДСТАВИТЬ(ПОДСТАВИТЬ(ПОДСТАВИТЬ(ПОДСТАВИТЬ(ПОДСТАВИТЬ(ПОДСТАВИТЬ(ПОДСТАВИТЬ(C2:C;".JPG";"");".PDF";"");".AI";"");".SLDDRW";"");".SLDPRT";"");".jpg";"");".png";""))

2.Разделить по точке "." не получится так как в названии есть точки, да и проблемы с suffix/prefix
Пример таблицы
Уточнение 1: в некоторых названиях может быть несколько "." и "_"
Уточнение 2: строк примерно 800

A: Из-за названия, в котором нет нижнего подчеркивания, приходится обходить ошибку и рисовать формулу в два раза длиннее:
=ЕСЛИОШИБКА(
ВПР(ЛЕВБ(A3;ПОИСК("_";A3)-1);$B$3:$C$20;2;0)&ПСТР(A3;ПОИСК("_";A3);99);
ВПР(ЛЕВБ(A3;ПОИСК(".";A3)-1);$B$3:$C$20;2;0)&ПСТР(A3;ПОИСК(".";A3);99))

A: Предположим, что нужно заменить не "часть теста", а левую часть имени файла. Тогда справедливо:
для замены всех, ненайденные переименовываются сами в себя:
=INDEX(IFERROR(VLOOKUP(
  ROW(A2:A25);
  SPLIT(FLATTEN(IF(
    REGEXMATCH(A2:A25;TRANSPOSE(B2:B25));
    ROW(A2:A25) & "❤" & REGEXREPLACE(A2:A25;TRANSPOSE(B2:B25);TRANSPOSE(C2:C25));
  ));"❤");
  2;
);A2:A25))

для замены всех, ненайденные возвращают пустоту:
=INDEX(IFERROR(VLOOKUP(
  ROW(A2:A25);
  SPLIT(FLATTEN(IF(
    REGEXMATCH(A2:A25;TRANSPOSE(B2:B25));
    ROW(A2:A25) & "❤" & REGEXREPLACE(A2:A25;TRANSPOSE(B2:B25);TRANSPOSE(C2:C25));
  ));"❤");
  2;
);))

Следует обратить внимание, что сортировка диапазона B2:C25 может повлиять на результат работы формулы.
Для более сложной однопартийной замены нужно усложнять формулу REGEXREPLACE(A2:A25;TRANSPOSE(B2:B25);TRANSPOSE(C2:C25))
Пример в Таблице https://docs.google.com/spreadsheets/d/1cfF88hVRfMumLDPXdUU-R4dr3oDycDrBlSoCFLgy148/edit?usp=sharing