text:
Q: Runtime error 91: Variable not set Admittedly, a lot of this code is copy-pasted from other help threads.
The code is going through Sheets("programs") and looking at the value in Column H. Depending on that value, it will either look for another sheet with the corresponding name and put the entire row in it, or if the sheet does not exist, it will make the sheet and put the row in it.
Option Explicit

Sub Fr33M4cro()

    Dim sh33tname As String
    Dim custNameColumn As String
    Dim i As Long
    Dim stRow As Long
    Dim customer As String
    Dim ws As Worksheet
    Dim sheetExist As Boolean
    Dim sh As Worksheet
    Dim wsRow As Long
    Dim wsMASTER As Worksheet, wsTEMP As Worksheet, wasVISIBLE As Boolean
    Dim shNAMES As Range, Nm As Range, NmSTR As String

    sh33tname = "programs"
    custNameColumn = "H"
    stRow = 3

    Set wsTEMP = Sheets("Sheet3")
    Set sh = Sheets(sh33tname)
    Set ws = Sheets(Worksheets.Count)

    For i = stRow To sh.Range("H" & Rows.Count).End(xlUp).Row
        customer = sh.Range("H" & i).Value
        For Each ws In ThisWorkbook.Sheets
            If StrComp(ws.Name, customer, vbTextCompare) = 0 Then
                sheetExist = True
                Exit For
            End If
        Next
        If sheetExist Then
            CopyRow i, sh, ws, custNameColumn, wsRow
        Else
            wsTEMP.Copy After:=Sheets(Sheets.Count)
            ActiveSheet.Name = sh.Range(custNameColumn & i).Value
            CopyRow i, sh, ws, custNameColumn, wsRow
        End If
        Reset sheetExist
    Next i

End Sub

Private Sub CopyRow(i As Long, ByRef sh As Worksheet, ByRef ws As Worksheet, custNameColumn As String, wsRow As Long)
    wsRow = ws.Range("H" & Rows.Count).End(xlUp).Row + 1
    sh.Rows(i & ":" & i).Copy
    ws.Rows(wsRow & ":" & wsRow).PasteSpecial _
    Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    Application.CutCopyMode = False
End Sub

Private Sub Reset(ByRef x As Boolean)
    x = False
End Sub

Private Sub InsertSheet(shName As String)
    Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = shName
End Sub

Function FixStringForSheetName(shSTR As String) As String

'replace each forbidden character with something acceptable
    shSTR = Replace(shSTR, ":", "")
    shSTR = Replace(shSTR, "?", "")
    shSTR = Replace(shSTR, "*", "")
    shSTR = Replace(shSTR, "/", "-")
    shSTR = Replace(shSTR, "\", "-")
    shSTR = Replace(shSTR, "[", "(")
    shSTR = Replace(shSTR, "]", ")")

'sheet names can only be 31 characters
    FixStringForSheetName = Trim(Left(shSTR, 31))

End Function

The problem i'm having is that it will make a new sheet with the value of Column H, but then "run-time error 91: Object variable or With block variable not set at the line". If i end the macro and restart it without changing anything, it will populate all the rows for that first sheet that was made last time, make a new sheet for the next value of Column H, and Run-Time error 91 again.
It points to this line of code.
wsRow = ws.Range("H" & Rows.Count).End(xlUp).Row + 1

From what I gather, I've declared wsRow As Long in the first part, but I never set it as something. Because i'm a newbie, I'm not sure what to set it as that won't interfere with the rest of the script.

A: When you create a new worksheet, you do not have it associated with the ws worksheet var. You use ActiveSheet to assign the name; use ActiveSheet to provide a target for the CopyRow.
    ...
    If sheetExist Then
        CopyRow i, sh, ws, custNameColumn, wsRow
    Else
        wsTEMP.Copy After:=Sheets(Sheets.Count)
        ActiveSheet.Name = sh.Range(custNameColumn & i).Value
        CopyRow i, sh, ActiveSheet, custNameColumn, wsRow
    End If
    ...


text:
Q: Extending a Control when creating Custom Control in c++ I'm trying to create a custom control but with limited c++ knowledge I'm struggling a bit.
I've taken a look at the header file RadioGroup.h as I'm trying to build something with similar functionality.
Here are my 2 files:
CompanyRadioGroup.h
#ifndef COMPANYRADIOGROUP_H_
#define COMPANYRADIOGROUP_H_

#include <bb/cascades/Control>
#include <bb/cascades/Container>
#include <bb/cascades/Option>

using namespace bb::cascades;

class CompanyRadioGroup : public Control {
private:
Q_OBJECT
QDeclarativeListProperty<Option> options();

public:
CompanyRadioGroup(Container * parent = 0);
virtual ~CompanyRadioGroup();

template <typename BuilderType, typename BuiltType>
class TBuilder : public BaseClass::TBuilder<BuilderType, BuiltType>
        {
        protected:
            TBuilder(BuiltType* node) : BaseClass::TBuilder<BuilderType, BuiltType>(node)
            {
            }
        public:

            /*!
             * @copydoc bb::cascades::RadioGroup::setDividersVisible(bool)
             *
             * @since BlackBerry 10.0.0
             */
            BuilderType& dividers(bool dividersVisible)
            {
                this->instance().setDividersVisible(dividersVisible);
                return this->builder();
            }

            BuilderType& add(Option* option)
            {
                this->instance().add(option);
                return this->builder();
            }

            BuilderType& add(const QString &optionText, const QVariant &value = QVariant(), bool selected = false)
            {
                this->instance().add(Option::create().text(optionText).value(value).selected(selected));
                return this->builder();
            }
        };

        class Builder : public TBuilder<Builder, CompanyRadioGroup>
        {
        public:
            explicit Builder() : TBuilder<Builder, CompanyRadioGroup>(new CompanyRadioGroup())
            {
            }
        };

        static Builder create()
        {
            return Builder();
        }
};

#endif

CompanyRadioGroup.cpp
#include "CompanyRadioGroup.h"

#include <bb/cascades/Control>

CompanyRadioGroup::CompanyRadioGroup(Container * parent) : Control(parent){

}

CompanyRadioGroup::~CompanyRadioGroup() {
// TODO Auto-generated destructor stub
}

On compiling I am getting an error
CompanyRadioGroup.cpp:12:72: error: no matching function for call to 'bb::cascades::Control::Control(bb::cascades::Container*&)'

It appears that the contructor for Control requires 2 parameters, however I cannot find any documentation on the first parameter or an example.
According to the Control.h file it has the following:
Control(ControlPrivate &_d_ptr, Control* parent = 0);

Can anyone advise how I pass _d_ptr or how I can overcome this issue?

A: If you do not need the first parameter _d_ptr anywhere in your code create a dummy abject instance that indicates "no-object" and pass that as the first parameter. References can't be null in c++ so you can't pass a null argument. Just create a dummy contrilPrivate object and pass a reference to it to the constructor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP header() function not redirecting when button is clicked on I have 4 forms with a button in each. When the user clicks on the any button, they user gets redirected to differentPage.php
<form action="differentPage.php" method="GET">
   <button type="submit" name="food" value="PIZZA">Pizza</button>
</form>

<form action="differentPage.php" method="GET">
   <button type="submit" name="food" value="PASTA">Pasta</button>
</form>

<form action="differentPage.php" method="GET">
   <button type="submit" name="food" value="SANDWICH">Sandwich</button>
</form>

<form action="differentPage.php" method="GET">
   <button type="submit" name="food" value="CHIPS">Chips</button>
</form>

On the differentPage.php I have the following code:
<?php $foodCode = $_GET['food'];
  if ($foodCode == "PIZZA" || $foodCode == "PASTA" ||
    $foodCode == "SANDWICH" || $foodCode == "CHIPS") {

    header("Location: differentPage.php");

  } else {
    header("Location: thisPage.php");
  }
?>

So if I were to modify the value attribute for any of the buttons, it would immediately redirect back to the current page from differentPage.php
However my code doesn't seem to be working. Even though I modify the value so that it doesn't equal PIZZA, PASTA, SANDWICH or CHIPS, it still redirects to differentPage.php
What am I doing wrong? Any help would be appreciated!

A: what are you doing man?
All forms are sent to differentPage.php and after entering differentPage.php, they are immediately sent to the same differentPage.php. This is a vicious circle.


text: Q: What is the solid of revolution of an ellipsis around a general line through the origin? If one rotates an ellipsis around its major axis, one gets a prolate ellipsoid. Around the minor axis, ones gets an oblate ellipsoid. What about a general line through the origin?


text:
Q: How to get all value of invalid characters in a string in jquery? I have a jquery method that check special character as shown below:
function checkForSpecialChar(val) {

    if (val != 0 && /^[a-zA-Z0-9- ]*$/.test(val) == false) {

        return false;
    }

return true;
}

This is working fine as it validate the value correctly.
However now I need to get all invalid characters for the val string and show it to the user.
So for example if val is = 123gdf$£!
It should get only the invalid character which is $£!.
Any idea how i can do that please?
Thanks in advance for any help.

A: Just invert your regex by adding ^ inside []
[^a-zA-Z0-9- ] // match anything that is not alphanumerical, `-` or whitespace

alert(
  'Invalid characters of "123gdf$£!": '
  + (
    '123gdf$£!'.match(/[^a-zA-Z0-9- ]/g)
      .join('')
  )
);

A: Try this
var val = "123gdf$£!".replace(new RegExp("[0-9a-zA-Z]", "g"), "");

https://jsfiddle.net/wx38rz5L/1816/

A: Simply you can use string match() method of javascript.
Here it is:
var val= "123gdf$£!";
var result= str.match(/^[a-zA-Z0-9- ]*$/);

result will be an array with values.


text:
Q: How can I emulate internet explorer for multiple versions with c# selenium? I want to emulate internet explorer for multiple versions with c# selenium, is it even possible? How can I do that? I made some test cases and I want to run them on IE 8,9,10,11. Any ideas?

A: There are a few ways you can do this depending how you set up yours tests.
I believe the easiest way to do this is something along the lines of:
public void StartUpIE(string version){
    string path = @"..\..\..\Drivers\IE\32\" + version;
    //Rest of code to create an instance of IE as you would
}

Then in your test:
[Testmethod]
public void testIE (){
    StartUpIE("11");
    //Do some testing
    StartUpIE("11.1");
}


text:
Q: Got an error about getStaticProps() on Next.js Project I got this error on my Next.js project :
Error: page / getStaticProps can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member

just wanna load some fake data to my main page then handle a nested page which is included more details about the clicked link with a special title
index.tsx
import fs from "fs/promises";
import path from "path";
import Link from "next/link";

export interface Product {
  id: string;
  title: string;
  description: string;
}
export interface Products {
  products: Product[];
}

export const ProductById = (props: Products) => {
  return (

      {props.products.map((pro) => (

          <Link href={`/${pro.id}`}>
            {pro.title}
          </Link>

      ))}

  );
};

export const getStaticProps = async () => {
  console.log("Pre Genarate ");
  const filePath = path.join(process.cwd(), "data", "dummy-backend.json");
  const readFile = await fs.readFile(filePath);
  const { products } = JSON.parse(readFile.toString());

  return {
    props: {
      products,
    },
    // revalidate: 1,
  };
};

and [pid].tsx page which is for load more details about the product clicked on it's title in the Index.tsx page ,
import fs from "fs/promises";
import path from "path";
import { Fragment } from "react";
import { Products, Product } from ".";
import { GetStaticProps } from "next";

export default function ProductById(props: Product) {
  return (
    <Fragment>

{props.title}

{props.description}

    </Fragment>
  );
}

export const getStaticProps: GetStaticProps = async (context) => {
  console.log("Pre Genarate ");
  const { params } = context;
  const productId = params?.pid;
  const filePath = path.join(process.cwd(), "data", "dummy-backend.json");
  const readFile = await fs.readFile(filePath);
  const data = JSON.parse(readFile.toString());
  const product = data.products.find((pro: Product) => pro.id === productId);

  return {
    props: {
      product,
    },
  };
};

export const getStaticPaths = async () => {
  // const filePath = path.join(process.cwd(), "data", "dummy-backend.json");
  // const readFile = await fs.readFile(filePath);
  // const data = JSON.parse(readFile);
  return {
    paths: [
      { params: { pid: "p1" } },
      { params: { pid: "p2" } },
      { params: { pid: "p3" } },
      // data.map((product) => {
      //   params: {
      //     pid: `${product.id}`;
      //   }
      // }),
    ],
    fallback: false,
  };
};

but got the above error on localhost:3000

A: Your index.tsx has a missing default export component change this code
export const ProductById = (props: Products) => {
  return (

      {props.products.map((pro) => (

         <Link href={`/${pro.id}`}>
            {pro.title}
         </Link>

     ))}

 );
};

to:
export default function Index(props: Products) {
  return (

      {props.products.map((pro) => (

         <Link href={`/${pro.id}`}>
            {pro.title}
         </Link>

     ))}

 );
};


text:
Q: How to convert Java Object to Json and ignore ArrayList on Object? I need to convert java Object to json.  I do that with ObjectMapper , like this:
static final ObjectMapper mapper = new ObjectMapper(); .....
String newJsonStringEntity = mapper.writeValueAsString(bean);

Everything work  fine, but I want to ignore ArrayList to convert to json, without  @JsonIgnore . I want to config mapper if possible?
Is there any way to do this?

A: You can use two annotation for that:

*

*@JsonIgnore: This is user for member-level or method-level annotation, which expects that the properties to be excluded one by one.
You can put this annotation in your bean class.
Example:
@JsonIgnore
private ArrayList list;

*@JsonIgnoreProperties is an annotation at the class level and it expects that the properties to be excluded would be explicitly indicated in the form of a list of strings.
Example:
@JsonIgnoreProperties({"name list variable"})
class BeanClass {}

A: The fields you dont want to convert, dont populate them with values and then use gson. Gson ignores null values. That will solve your problem


text:
Q: Sudden approximation and the zero'th law of thermodynamics? If I have a quantum mechanical system (QMS) whose density matrix is at temperature $T$ and I put it in contact with another quantum mechanical system (QMS2) at temperature $T$ again.
However, if I try to model this dynamically I'd be tempted to use the sudden approximation.  Let the probability of QMS being in energy state $| E_i \rangle$ is $e^{- \beta E_i}$ and QMS2 being in energy $| E_j \rangle$ is $e^{- \beta E_j}$. Hence, the probability of the below outcome
$$ \Big (H_{QMS} \otimes 1+ 1 \otimes H_{QMS2} \Big ) |E_i ,E_j\rangle \to \Big (H_{QMS} \otimes 1 + 1 \otimes H_{QMS2} + H_{int}\Big )|\lambda_l ,\lambda_k \rangle$$
(where $H_{int}$ is the interaction Hamiltonian and $|\lambda_l ,\lambda_k \rangle$ are arbitrary states of the combined system) is given by:
$$ e^{-\beta(E_i +E_j)} |\langle E_i | \lambda_l  \rangle \langle E_j | \lambda_k  \rangle|^2 $$
However, by the zeroth law of thermodynamics I know that these systems should remain in thermal equilibrium as well. I'm uncertain as how to show that is the case here?

A: The argument here is that we are dealing with thermodynamicly large systems and that there are no long ranged interactions between the 2 systems. In this case $H_{int} $ scales with the surface area where the systems were brought into contact, whilst $H_{QMS1} $ and $H_{QMS2} $ scale with volume, so $H_{int} $ can be neglected and your final Hamilton is the same as your initial Hamilton, in which case clearly the zeroth law holds.
If the previous assumptions do not hold and $H_{int} $ is comparable to the system Hamiltonians, then bringing the 2 systems into contact will involve doing a non-negligible amount of work on the systems, in which case it is not surprising the zeroth law fails.

A: If one applies a sudden perturbation, like suddenly turning on the interaction between two systems at different temperature, we are definitely dealing with a non-equilibrium situation. As thermodynamics predicts, there will be transfer of energy from one system to another, however what exactly happens depends on the order in which one takes the limits of infinite time and the thermodynamic limit.
A situation frequently considered when studying non-equilibrium heat and electric transport is taking the thermodynamic limit first, which results in a steady-state flow of heat or current between the two systems (in the case of electric transport the systems are usually at the same temperature but different chemical potentials). This is definitely a non-equilibrium situation, although each of the two systems is treated, as if it were in equilibrium.


text:
Q: Why does the following web scraping code not work in R? I tried to scrape the table on this website: https://www.timeshighereducation.com/world-university-rankings/2021/world-ranking#!/page/0/length/100/sort_by/rank/sort_order/asc/cols/stats, using R. I have the following code:
url<-"https://www.timeshighereducation.com/world-university-rankings/2021/world-ranking#!/page/0/length/100/sort_by/rank/sort_order/asc/cols/stats"
table1=url%>%
    read_html()%>%
    html_nodes(xpath = '//*[@id="datatable-1"]')%>%
    html_table()%>%
    .[[1]]
table1

The output only includes the column names with 0 row of actual data. Did I do anything wrong?
I also try to scrape the the column of university names first, with the code:
url<-"https://www.timeshighereducation.com/world-university-rankings/2021/world-ranking#!/page/0/length/100/sort_by/rank/sort_order/asc/cols/stats"
name=url%>%
    read_html()%>%
    html_nodes('.ranking-institution-title')%>%
    html_text()
name

Again the output is empty, but I can't figure out why.
The CSS path is found using Chrome extension SelectorGadget, which works for other website.

A: The data is loaded on the page in the form of json.
data <- jsonlite::fromJSON('https://www.timeshighereducation.com/sites/default/files/the_data_rankings/world_university_rankings_2021_0__fa224219a267a5b9c4287386a97c70ea.json')
table1 <- data$data
head(table1[1:5])

#  rank_order rank                                  name scores_overall scores_overall_rank
#1         10    1                  University of Oxford           95.6                  10
#2         20    2                   Stanford University           94.9                  20
#3         30    3                    Harvard University           94.8                  30
#4         40    4    California Institute of Technology           94.5                  40
#5         50    5 Massachusetts Institute of Technology           94.4                  50
#6         60    6               University of Cambridge           94.0                  60

You can keep only the columns that you need from table1.


text:
Q: Show Navigation Bar in Child View Controller I am working on an app in which I have to display multiple view controllers side by side (split views). For this purpose I have added views as child view controller.
OBJECTIVE: I want to show navigation bar on one child view controller along with already shown separate navigation bar on parent view controller.
PROBLEM: Navigation bar doesn't get shown on child view controller.
EDIT: I have also set navigation bar of parent view controller as hidden but when child view controller get's called, the navigation bar gets appeared on parent view controller, not on child view controller.
Code to add child view controller is:
    MyChildViewController *childViewController = [[MyChildViewController alloc] initWithNibName:@"MyChildViewController" bundle:nil];

    [self addChildViewController:childViewController];
    [childViewController.view setFrame:CGRectMake(0.0f, 0.0f, self.rightContainerView.frame.size.width, self.rightContainerView.frame.size.height)];
    [self.rightContainerView addSubview:childViewController.view];
    [childViewController didMoveToParentViewController:self];

This code is working fine and child view controller gets add perfectly. I want to know is it possible or not?
Thanks in advance.

A: add Navigation bar like this

It will be appear in your all view controller
Another way to do:
Put this code into didFinishLaunchingWithOptions method in appdelegate.m file.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
ECViewController * ec = [[ECViewController alloc] initWithNibName:@"ECViewController" bundle:nil];
UINavigationController* navigationController = [[UINavigationController alloc] initWithRootViewController:ec];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
return YES;

Add a Nib file(ECViewController) by simply following these steps:
1: Right click in project root
2: Add new file
3: Go to user interface.
4: Select view
5: Give it name same as your view controller name i gave ECViewController in my case.
Click on newly created nib file
Click on file owner fist yellow box on left side. make an connection with view by simple dragging with control keyword.click on view when popup appear.
Now goto identity inspector (fourth section from staring in left side).
Write your class name in Class name textBox appeared.
By this you can able to open an xib in iOS7 if you don't want to use storyboard.
Now if you need view controller with navigation controller.
Then open your view controller by this way.
 ECViewController1 *v = [[ECViewController1 alloc]initWithNibName:@"ECViewController1" bundle:nil];

    [self.navigationController pushViewController:v animated:YES];

Its too late for this edited answer, Hope it will help someone other.

A: I solved this problem by myself through following way:
MyChildViewController *childViewController = [[MyChildViewController alloc] initWithNibName:@"MyChildViewController" bundle:nil];
[childViewController.view setFrame:CGRectMake(0.0f, 0.0f, self.rightContainerView.frame.size.width, self.rightContainerView.frame.size.height)];

UINavigationController *childNavController = [[UINavigationController alloc] initWithRootViewController:childViewController];
childNavController.view.frame = childViewController.view.frame;

[self addChildViewController:childNavController];
[self.rightContainerView addSubview:childNavController.view];
[childNavController didMoveToParentViewController:self];

Now when I add navigation bar in MyChildViewController, it gets added in child view controller and does not affect navigation bar of parent view controller. The navigationController property of child view controller is also different than navigationController property of parent view controller and both have their own navigation stacks.

A: Set the y position of child view correctly.
MyChildViewController *childViewController = [[MyChildViewController alloc] initWithNibName:@"MyChildViewController" bundle:nil];

    [self addChildViewController:childViewController];
    [childViewController.view setFrame:CGRectMake(0.0f, 44.0f, self.rightContainerView.frame.size.width, self.rightContainerView.frame.size.height)];
    [self.rightContainerView addSubview:childViewController.view];
    [childViewController didMoveToParentViewController:self];

A: I have found the link from stackoverflow we need to add navigation bar manually there is no alternate for this.


text:
Q: After parsing CSV as an array of objects can't access some property After parsing CSV:
id,x
1,0.358995018
2,0.196424349
3,0.882696509
4,0.765233761
5,0.25087529

with code
let lines = data.split('\n');
            let props = lines.shift().split(',');
            let objects = [];
            for (let line of lines) {
                let values = line.split(',');
                let obj = {};
                for (let i = 0; i < props.length; i++)
                    obj[props[i]] = isNaN(values[i]) ? values[i] : parseFloat(values[i]);
                objects.push(obj);
            }
            this.data = objects;

can't access last property of any object and for some reason it's double quoted in debugger...
What's going on?
can't access property "x"

A: When putting your code in a snippet I do not have this problem. Perhaps it is a problem with how your data is formatted or how you are accessing the object?
See the snippet below.

var data =
`id,x
1,0.358995018
2,0.196424349
3,0.882696509
4,0.765233761
5,0.25087529`;

var dataToObj = function(data) {
  let lines = data.split('\n');
  let props = lines.shift().split(',');
  let objects = [];
  for (let line of lines) {
      let values = line.split(',');
      let obj = {};
      for (let i = 0; i < props.length; i++)
          obj[props[i]] = isNaN(values[i]) ? values[i] : parseFloat(values[i]);
      objects.push(obj);
  }
  return objects;
}

console.log(dataToObj(data)[0].x);


text:
Q: Free Pascal IDE: Writeln and Readln don't work properly Using the Free Pascal IDE, I have some problems with console IO under Windows.
When I use Writeln the cursor doesn't move to the next line and is staying at the end of the written line. So if I press Enter instead of moving to the next line the cursor goes to the beginning of the current line. And if I use Readln after Writeln new characters that I enter are displayed instead of the characters that were written with Writeln.
When I use Readln to enter string I have next problem. If I enter some string, use backspace to delete characters and enter other characters after that, Readln return to program string that includes backspace symbols and deleted characters.
I guess this is Windows problem, but I have no ideas.

A: It looks as if you have run into a (known) problem with the Free Pascal IDE on Windows 10. This happens to console programs started from that IDE. There is no fix, and no workaround (well, there is one: use unit Crt). It has other issues as well.
Just try another IDE, e.g. Lazarus.
Note that your program will run fine if started standalone. But not when started from the FPC IDE.


text:
Q: Manim draws a wrong line on a plotted graph I'm working on a school project regarding derivatives and I've encountered a problem. I try to draw a secant line through points (2,4) and  (2+dx, f(2+dx)) for f(x)=x^2. For some reason, manim first draws the line tangent to (2,4) and in one frame autocorrects to draw a secant through (2,4) and (2+dx, f(2+x)), as in an example: https://youtu.be/CDa7MdDdIT0.
I've isolated the lines that are responsible for this, but I can't figure out what's wrong. The code:
class TestingField(Scene):
def construct(self):
######## Definitions
    dx=ValueTracker(0.001)

    axes_begin=Axes(x_range=[-8,8,1], y_range=[-12,30, 3], x_length=10, y_length=10, tips=False)
    graph_begin=axes_begin.plot(lambda x: x**2, x_range=[-6,6], color=GREEN)

    ####Tangents to x^2
    tangent_begin_x2_RED=always_redraw(
    lambda: axes_begin.get_secant_slope_group(
    x=2,
    graph=graph_begin,
    dx=dx.get_value(),
    secant_line_color=RED,
    secant_line_length=15,
    dx_line_color=BLACK,
    dy_line_color=BLACK)
    )

    tangent_begin_x2_RED_2=always_redraw(
    lambda: axes_begin.get_secant_slope_group(
    x=2,
    graph=graph_begin,
    dx=dx.get_value(),
    secant_line_color=RED,
    secant_line_length=15,
    dx_line_color=YELLOW,
    dy_line_color=PURPLE)
    )

    tangent_begin_point_x2_1=always_redraw(
    lambda: Dot()
    .move_to(axes_begin.c2p(2+dx.get_value(), graph_begin.underlying_function(2+dx.get_value())))
    )

    tangent_begin_point_x2_2=always_redraw(
    lambda: Dot()
    .move_to(axes_begin.c2p(2, graph_begin.underlying_function(2)))
    )

######## Animation
    self.add(axes_begin, graph_begin, tangent_begin_point_x2_1, tangent_begin_point_x2_2,tangent_begin_x2_RED)

    self.wait(1)

    self.play(Uncreate(tangent_begin_x2_RED))
    self.play(dx.animate.set_value(1))

    self.play(Create(tangent_begin_x2_RED_2), run_time=2)

    self.play(dx.animate.set_value(0.7))
    self.play(dx.animate.set_value(0.3))
    self.play(dx.animate.set_value(1))

And rendering:
manim -pqh wstep.py TestingField

Could someone point out what's causing the problem?

A: The problem that you run into is that always_redraw basically creates a mobject with an updater function attached. Mobjects with updaters that are not yet added to the scene (which in your case tangent_begin_x2_RED_2 is not until it is Created) are not updated.
You can fix the issue by adding
tangent_begin_x2_RED_2.update()

before the self.play-call where the secant group is created.


text:
Q: Unix socket filename error This is the first time I am programming with Unix sockets so forgive the stupid errors.  I wrote the following function to create a unix socket.
int create_server_unix_socket(const string& socket_path) {

    // STEP 1 : socket()
    int unix_socket = socket(AF_UNIX, SOCK_STREAM, 0);
    if (unix_socket == -1) {
        throw std::runtime_error {"Error occured in socket() call : "s +
            string(std::strerror(errno))};
    }

    // STEP 2 : bind(), setup the address structures for bind()
    sockaddr_un local_address;
    local_address.sun_family = AF_UNIX;
    std::strcpy(local_address.sun_path, socket_path.c_str());

    // unlink from before
    unlink(socket_path.c_str());

    // STEP 2 : bind()
    size_t length = socket_path.size() + sizeof(local_address.sun_family);
    if (::bind(unix_socket, reinterpret_cast<sockaddr*>(&local_address),
                length) == -1) {
        throw std::runtime_error {"Error occured in bind() call : "s +
            string(strerror(errno))};
    }

    // STEP 3 : listen()
    if (listen(unix_socket, 5) == -1) {
        throw std::runtime_error {"Error occured in listen() call : "s +
            string(strerror(errno))};
    }

    return unix_socket;
}

But whenever I try and create a socket like so
create_server_unix_socket("./unix_socket"s);

The file that is created in the current working directory is unix_socke instead of unix_socket and in fact this happens to any name that I try.  If I try unix_socket_longer_name, the file produced is unix_socket_longer_nam.  I am running this on a Mac OS X (version 10.11.4).
Any ideas on what I am doing wrong?  Also if you notice something horribly wrong in my code, please let me know!  I wrote this by consulting the man pages and I am not completely sure I did it right.  Thanks!
NOTE : I am compiling this with C++14, you would need to import the std::literals::string_literals namespace to make this work.  Add using namespace std::literals::string_literals to the top of your code.

A: Let's take a look at the man page of bind

int bind(int sockfd, const struct sockaddr *addr,
            socklen_t addrlen);

The third parameter is the addrlen

addrlen specifies the size, in bytes, of the address structure pointed to by addr.

So, what you should be passing, is sizeof local_address. Instead, you passed length which is socket_path.size() + sizeof(local_address.sun_family). That size is almost enough, but there is no room for the null terminator and it ignores the possibility that sockaddr_un may contain padding.
If you really want to pass a length that matches the path rather than the full size of local_address, you could use offsetof:
length = offsetof(sockaddr_un, sun_path) + socket_path.size() + 1;

But I don't see an advantage to it over simply passing sizeof local_address.


text:
Q: What are the penalties for being late for work? I'm trying to burn through career promotions for aspirations quicky. Part of this is getting the sim in a proper mood before leaving for work. I queue up finishing of the daily task and studying some object to make my sim focused before they leave for work.
By doing so, it often happens that my sim doesnt actually leave the house until 1 hour after they had to go to work. On one occasion it was even 2 hours.
Are there any penalties for getting late to work, like...

*

*The job performance meter only moves when you work? (and by being late it has less time in a day)

*Sims get paid by hour, not day?

*Fixed penalties like treating it as not coming in for work once a few hours pass?

A: If you don't go to work, after ~90 minutes you'll get a call from the boss letting you know that you're missing work.  It is ok to not answer the call, or answer the call and still not go.
Sims are paid hourly.  The more hours you miss, the less pay you get.  I tested this with two sims at level 1 business career.  One sim earned $128 ($16 * 8), while the other earned $98 ($16 * ~6).
Work performance does suffer while you are not at work.  Work performance also does not accrue while you're not at work.
From a gameplay standpoint, it's probably worth being an hour late if you can enter a favorable mood.  Of course, if you could get the mood without being late that would be better.

A: So far, there is no penalty for beign late for work at any Sims game.
The penalty comes if you don't go to work.


text:
Q: Manage to unmanaged transition from second AppDomain is very slow The setup is as follows:

*

*Main app domain loads a number of unmanaged C++ libraries from a C++/CLI assembly.

*A second app domain loads those C++ libraries, but of course it is just getting hold of handles to the previously loaded libraries.

*I run exactly the same managed C# code in both app domains that makes use of the unmanaged C++ libraries.

*The C++/CLI assembly contains a mixture of managed and unmanged code.

When calling into the unmanaged C++ libraries from the main app domain the cost of the managed to unmanaged transition is fairly negligible compared to the overall cost of execution. However, from the second app domain that did not originally load the libraries the cost of the managed to unmanaged transition becomes substantial; orders of magnitude larger. I know this because I have run ANTS performance profiler and this is what it tell me.
There are some unmanaged static variables in the C++/CLI assembly, I've tried replacing them when a new app domain is created, but this doesn't change the performance. There would well be a bunch of hidden ones.
What could be going on here? Why should the transition in the other app domain be so slow? Is there anything obvious to try to improve things?
Some context: the code is running in a separate app domain for isolation and so that it can be torn down when things go wrong. It would be very good to keep it isolated from the main app domain. It would be possible to start a new process from which to run the unmanaged code, however this could be expensive as it may require a lot of data to be serialized and deserialized and the cost of bootstrapping everything in a new process is also fairly large. In the general case the cost of the serialization and the bootstrap will be much lower than the cost of the managed to unmanaged transition that I'm seeing, but there is a lot of messing around involved and it still slows things down a lot.


text:
Q: Difference between new and override Wondering what the difference is between the following:
Case 1: Base Class
public void DoIt();

Case 1: Inherited class
public new void DoIt();

Case 2: Base Class
public virtual void DoIt();

Case 2: Inherited class
public override void DoIt();

Both case 1 and 2 appear to have the same effect based on the tests I have run. Is there a difference, or a preferred way?

A: try following: (case1)
((BaseClass)(new InheritedClass())).DoIt()

Edit: virtual+override are resolved at runtime (so override really overrides virtual methods), while new just create new method with the same name, and hides the old, it is resolved at compile time -> your compiler will call the method it 'sees'

A:
All combinations of none, virtual, override, new and abstract:

A: The difference between the two cases is that in case 1, the base DoIt method does not get overridden, just hidden. What this means is that depending on the type of the variable depends on which method will get called. For example:
BaseClass instance1 = new SubClass();
instance1.DoIt(); // Calls base class DoIt method

SubClass instance2 = new SubClass();
instance2.DoIt(); // Calls sub class DoIt method

This can be really confusing and results in non expected behaviour and should be avoided if possible. So the preferred way would be case 2.

A: In case 1 if you used call the DoIt() method of the inherited class while the type is declared as the base class you will see the action of the base class even.
/* Results
Class1
Base1
Class2
Class2
*/
public abstract class Base1
{
    public void DoIt() { Console.WriteLine("Base1"); }
}
public  class Class1 : Base1
{
    public new void DoIt() { Console.WriteLine("Class1"); }
}
public abstract class Base2
{
    public virtual void DoIt() { Console.WriteLine("Base2"); }
}
public class Class2 : Base2
{
    public override void DoIt() { Console.WriteLine("Class2"); }
}
static void Main(string[] args)
{
    var c1 = new Class1();
    c1.DoIt();
    ((Base1)c1).DoIt();

    var c2 = new Class2();
    c2.DoIt();
    ((Base2)c2).DoIt();
    Console.Read();
}

A:
The override modifier may be used on
  virtual methods and must be used on
  abstract methods. This indicates for
  the compiler to use the last defined
  implementation of a method. Even if
  the method is called on a reference to
  the base class it will use the
  implementation overriding it.

public class Base
{
    public virtual void DoIt()
    {
    }
}

public class Derived : Base
{
    public override void DoIt()
    {
    }
}

Base b = new Derived();
b.DoIt();                      // Calls Derived.DoIt

will call Derived.DoIt if that overrides Base.DoIt.

The new modifier instructs the
  compiler to use your child class implementation
  instead of the parent class
  implementation. Any code that is not
  referencing your class but the parent
  class will use the parent class
  implementation.

public class Base
{
    public virtual void DoIt()
    {
    }
}

public class Derived : Base
{
    public new void DoIt()
    {
    }
}

Base b = new Derived();
Derived d = new Derived();

b.DoIt();                      // Calls Base.DoIt
d.DoIt();                      // Calls Derived.DoIt

Will first call Base.DoIt, then Derived.DoIt. They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.
Source: Microsoft blog

A: I had the same question and it's really confusing,
you should consider that override and new keywords working only with objects of type base class and value of derived class. In this case only you'll see the effect of override and new:
So if you have class A and B, B inherits from A, then you instantiate an object like this:
A a = new B();

Now on calling methods will take its state into consideration.
Override: means that it extends the function of the method, then it uses the method in the derived class, whereas new tell the compiler to hide the method in the derived class and use the method in the base class instead.
Here is a very good sight to that subject:
https://msdn.microsoft.com/EN-US/library/ms173153%28v=VS.140,d=hv.2%29.aspx?f=255&MSPPError=-2147217396

A: The article below is in vb.net but I think the explanation about new vs overrides is very easy to grasp.
https://www.codeproject.com/articles/17477/the-dark-shadow-of-overrides
At some point in the article, there is this sentence:

In general, Shadows assumes the function associated with the type is
  invoked, while Overrides assumes the object implementation is
  executed.

The accepted answer to this question is perfect but I think this article provide good examples to add better meaning about the differences between these two keywords.

A: In the first case you are hiding the definition in the parent class.  This means that it will only be invoked when you are dealing with the object as the child class.  If you cast the class to its parent type, the parent's method will be invoked.  In the second instance, the method is overridden and will be invoked regardless of whether the object is cast as the child or parent class.

A: virtual: indicates that a method may be overriden by an inheritor
override: overrides the functionality of a virtual method in a base class, providing different functionality.
new: hides the original method (which doesn't have to be virtual), providing different functionality. This should only be used where it is absolutely necessary.
When you hide a method, you can still access the original method by up casting to the base class. This is useful in some scenarios, but dangerous.

A:

*

*new means respect your REFERENCE type(left-hand side of =) , thereby running reference types's method. If redefined method doesn't have new keyword, it is behaved as it has. Moreover, it also known as non-polymorphic inheritance. That is,
  "I'm making a brand new method in the derived class that has
  absolutely nothing to do with any methods by the same name in the base
  class." - by said Whitaker

*override, which must be used with virtual keyword in its base class, means respect your OBJECT type(right-hand side of =), thereby
  running method overriden in regardless of reference type. Moreover, it also known as polymorphic inheritance.

My way to bear in mind both keywords that they are opposite of each other.
override: virtual keyword must be defined to override the method. The method using override keyword that regardless of reference type(reference of base class or derived class) if it is instantiated with base class, the method of base class runs. Otherwise, the method of derived class  runs.
new: if the keyword is used by a method, unlike override keyword, the reference type is important. If it is instantiated with derived class and the reference type is base class, the method of base class runs. If it is instantiated with derived class and the reference type is derived class, the method of derived class runs. Namely, it is contrast of override keyword. En passant, if you forget or omit to add new keyword to the method, the compiler behaves by default as new keyword is used.
class A
{
    public string Foo()
    {
        return "A";
    }

    public virtual string Test()
    {
        return "base test";
    }
}

class B: A
{
    public new string Foo()
    {
        return "B";
    }
}

class C: B
{
    public string Foo()
    {
        return "C";
    }

    public override string Test() {
        return "derived test";
    }
}

Call in main:
A AClass = new B();
Console.WriteLine(AClass.Foo());
B BClass = new B();
Console.WriteLine(BClass.Foo());
B BClassWithC = new C();
Console.WriteLine(BClassWithC.Foo());

Console.WriteLine(AClass.Test());
Console.WriteLine(BClassWithC.Test());

Output:
A
B
B
base test
derived test

New code example,
Play with code by commenting in one-by-one.
class X
{
    protected internal /*virtual*/ void Method()
    {
        WriteLine("X");
    }
}
class Y : X
{
    protected internal /*override*/ void Method()
    {
        base.Method();
        WriteLine("Y");
    }
}
class Z : Y
{
    protected internal /*override*/ void Method()
    {
        base.Method();
        WriteLine("Z");
    }
}

class Programxyz
{
    private static void Main(string[] args)
    {
        X v = new Z();
        //Y v = new Z();
        //Z v = new Z();
        v.Method();
}

A: If keyword override is used in derive class then its override the parent method.
If Keyword new is used in derive class then derive method hided by parent method.

A: Out of all those, new is the most confusing. Through experimenting, the new keyword is like giving developers the option to override the inheriting class implementation with the base class implementation by explicitly defining the type. It is like thinking the other way around.
In the example below, the result will return "Derived result" until the type is explicitly defined as BaseClass test, only then "Base result" will be returned.
class Program
{
    static void Main(string[] args)
    {
        var test = new DerivedClass();
        var result = test.DoSomething();
    }
}

class BaseClass
{
    public virtual string DoSomething()
    {
        return "Base result";
    }
}

class DerivedClass : BaseClass
{
    public new string DoSomething()
    {
        return "Derived result";
    }
}

A: The functional difference will not be show in these tests:
BaseClass bc = new BaseClass();

bc.DoIt();

DerivedClass dc = new DerivedClass();

dc.ShowIt();

In this exmample, the Doit that is called is the one you expect to be called.
In order to see the difference you have to do this:
BaseClass obj = new DerivedClass();

obj.DoIt();

You will see if you run that test that in the case 1 (as you defined it), the DoIt() in BaseClass is called, in case 2 (as you defined it), the DoIt() in DerivedClass is called.

A: new : It just hides the method of the base class, but you can access it if you want.
override: It's overriding the base class's method and you can't access it even if you want to.
Example
using System;

public class Program
{
    public static void Main()
    {
        BaseClass test = new DerivedClass();
        var result = test.DoSomething();

        Console.WriteLine(result);
    }

    class BaseClass
    {
        public string DoSomething()
        {
            return "Base result";
        }
    }

    class DerivedClass : BaseClass
    {
        public new string DoSomething()
        {
            return "Derived result";
        }
    }
}

Result: Base result
P.S. I copied and slightly changed the above example from the following link:
https://stackoverflow.com/a/45822233/10995103


text:
Q: Club Election Voting Permutation Question In a club election the number of contestants is one more than the number of maximum candidates for which a voter can vote. If the total number of ways is which a voter can vote be 62, then the number of candidates is:
My Approach!
Let's suppose we have m voters and n be the maximum candidate so total number of contestants becomes n+1.
Now each voter can vote in n+1 ways. So m voters can vote in m* (n+1) ways which is equal to 62.
That's it, I am not able to figure it out more.

A: It sounds like the only restrictions on who you can vote for are that you can't vote for everybody, and you can't vote for nobody. So you can vote for any subset of the $n$ candidates except those two. So you have $2^n-2$ different ways to vote, and so $2^n=64$.

A: Let there be $n$ candidates (contestants), and I assume that you have to vote for at least one of them, then
the number of ways of casting votes is $\binom{n}{1} + \binom{n}{2} + \dotsc + \binom{n}{n-1}$.
[ Remember, you can only vote for a maximum of n-1 ]
Now it is known that the sum of the binomial coefficients,
$$\binom{n}{0} + \binom{n}{1} + \dotsc + \binom{n}{n} = 2^n$$
subtracting $\binom{n}{0} + \binom{n}{n} = 1 + 1$,
the number of ways to vote is $2^n - 2 = 62$
\begin{gather}
2^n = 64 \\
2^n = 2^6 \\
n = 6
\end{gather}


text:
Q: redirect to domain without www [SSL] I want redirect to domain without www ,
I tried this codes at .htaccess file:
RewriteCond %{HTTP_HOST} ^(www\.example\.com)(:80)? [NC]
RewriteRule ^(.*) https://example.com/$1 [R=301,L]

and also
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

when I type www.mysite.com its work but when I type https:www.mysite.com I got this error:
An error occurred during a connection to www.example.com.
Peer reports it experienced an internal error. (Error code:
ssl_error_internal_error_alert)

what is my mistake?
Update: I already have a valid SSL certificate.
And I use this code for redirect to HTTPS :
At top of my .htaccess file:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

A: You can use the following code :
RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

This will redirect :

*

*http://www.example.com
or

*

*https://www.example.com
to

*

*http://example.com
Clear your browser's cache before testing this.


text:
Q: Use a Chernoff bound I've got a simple task: a share's price at day 0 is $Q$. Then each day it increases to $\frac{3}{2} \cdot q$ or decreases to $\frac{1}{2} \cdot q$ (where $q$ is its price the previous day), each with probability $\frac{1}{2}$. I am to show that the probability of the price being greater than $Q$ after $n$ days is $O(e^{-cn})$ for some constant $c > 0$. According to a hint, I should use the Chernoff bound and notice that $3^3 < 2^5$.
I've tried to use the Chernoff bound, but ended up with a useless result (and nowhere have I used that, yhm, magical inequality). Could you help me with this problem?
Here's how I've approached it:

*

*let $X_i$ be the price after the $i$-th day

*let $Y_i$ be a 0/1 variable denoting whether the price increases (1) or decreases (0) after the $i$-th day

*let $Z_i = Y_i + \frac{1}{2}$; then $X_n = Q \cdot Z_1 \cdot Z_2 \cdot \ldots \cdot Z_n$ (because $Z_i \in \{\frac{1}{2}, \frac{3}{2}\}$ and the price changes to $\frac{1}{2}$ or $\frac{3}{2}$ of its previous value with an equal probability)

*variables $Y_i$ are obviously independent, thus so are variables $Z_i$

*we try to use the Chernoff bound:
\begin{eqnarray}
  \mathbb{P}(X_n \geq Q)
    & =    & \mathbb{P}(Q \cdot Z_1 \cdot Z_2 \cdot \ldots \cdot Z_n \geq Q) \\
    & =    & \mathbb{P}(Z_1 \cdot Z_2 \cdot \ldots \cdot Z_n \geq 1) & \text{(because } Q > 0) \\
    & \leq & \min_{t > 0} \frac{\mathbb{E}(e^{t \cdot Z_1 \cdot Z_2 \cdot \ldots \cdot Z_n})}{e^t} & \text{(Chernoff bound)} \\
    & =    & \min_{t > 0} \frac{e^t \cdot \left( \mathbb{E}(e^Z) \right)^n}{e^t} & \text{(because all $Z_?$'s are independent and have the same distribution)} \\
    & =    & \left( \mathbb{E}(e^Z) \right)^n \\
    & =    & \left( e^\frac{1}{2} \cdot \frac{1}{2} + e^\frac{3}{2} \cdot \frac{1}{2} \right)^n & \text{(because $Z_i = 0/1 + \frac{1}{2}$, each with probability $\frac{1}{2}$)}
\end{eqnarray}

*but this is useless because $e^\frac{1}{2} \cdot \frac{1}{2} + e^\frac{3}{2} \cdot \frac{1}{2} > 1$
If I were to guess where I've gone astray, I see two sticky points:

*

*the very beginning of the inequality: $\mathbb{P}(X_n \geq Q)$ - the task asked us to for the probability of the strict inequality $X_n > Q$

*that pulling out of $e^t$ in $\min$ and reducing it in the enumerator and denominator seemed too easy

A: OK, I've solved it if anyone's interested. The problem is I've approached this far too abstractly and didn't look at the specific values given here. The solution is quite nice so I'll post it:
Let $X_i$ be the share's price after the $i$-th day. Because each day the price is multiplied by either $\frac{1}{2}$ or $\frac{3}{2}$, then $X_i = Q \cdot \frac{1}{2^n} \cdot 3^{\text{the number of days when the price was increased}}$.
Let $Y_i$ be a 0/1 variable denoting whether the price increased (1) or decreased (0) after the $i$-th day. Obviously, the variables $Y_i$ are independent. Finally, let $Y = Y_1 + \ldots + Y_n$ and notice that $\mathbb{E}(Y) = n \cdot \frac{1}{2} = \frac{n}{2}$.
We have:
\begin{eqnarray}
  \mathbb{P}(X_n > Q) & = & \mathbb{P}\left(Q \cdot \frac{3^Y}{2^n} > Q\right) \\
                      & = & \mathbb{P}\left(\frac{3^Y}{2^n} > 1\right) \\
                      & = & \mathbb{P}(3^Y > 2^n) \\
                      & = & \mathbb{P}\left(3^Y > (2^5)^\frac{n}{5}\right) \\
                      & < & \mathbb{P}\left(3^Y \geq (3^3)^\frac{n}{5}\right) \text{ (the magic inequality!)} \\
                      & = & \mathbb{P}\left(3^Y \geq 3^\frac{3n}{5}\right) \\
                      & = & \mathbb{P}\left(Y \geq \frac{3n}{5}\right) \\
                      & = & \mathbb{P}\left(Y \geq \left(1 + \frac{1}{5}\right) \cdot \underbrace{\frac{n}{2}}_\text{=$\mathbb{E}(Y)$}\right) \\
                      & \leq & \exp\left(-\frac{\left(\frac{1}{5}\right)^2 \cdot \frac{n}{2}}{3}\right) \text{ (a special case of the Chernoff bound)} \\
                      & = & \exp\left(-\frac{1}{150} \cdot n\right) \\
                      & = & O(e^{-cn}) \text{ for $c = \frac{1}{150}$}
\end{eqnarray}
That concludes the proof.


text:
Q: Simplifying and understanding inequalities in two variables given an equation: $$\frac{x-y}{x+y}\ge0$$
What are the steps to simplify this into an understandable group of inequalities which will yield a solution set as a group of areas? I already know that $x+y$ can't equal 0. I even know the shape of the solution areas, it's basically $$|x|\ge|y|$$ excepting points on the line x=-y. I figured this out through some deductive reasoning and testing some points, but I cannot figure out the operations required to arrive at this result in a legitimate (provable) manner.

A: We have
$$\frac{x-y}{x+y}\ge0\iff\left(x-y\ge0\land x+y>0\right)\lor \left(x-y\le0\land x+y<0\right)$$
so the first case gives $x\ge|y|$ but $x\ne-y$ and the second case gives $-x\ge |y|$ but $x\ne-y$ so we conclude that
$$|x|\ge|y|\quad\text{and}\; x\ne-y$$

A: Hint.  A fraction is positive if the numerator and denominator are both positive, or both negative.

A: One brute force approach is to split into three cases
C1: $x+y<0$, C2: $x+y=0$, C3: $x+y>0$.
You should draw a picture for each of the three cases.
Case C1: If $x+y<0$, then we can write the equation as $x-y \le 0(x+y) = 0$, so the solutions for this case are
$$\{ (x,y) | x \le y, x+y < 0  \} = \{ (x,y) | x \le y, x < -y  \}  = \{ (x,y) | x < -|y|  \} \cup \{ (x,y) | x = y, y < 0  \} $$
Case C2: The denominator is zero, hence there are no solutions satisfying $x+y = 0$.
Case C3: If $x+y>0$, then we can write the equation as $x-y \ge 0(x+y) = 0$,
so the solutions for this case are
$$\{ (x,y) | x \ge y, x+y > 0  \} = \{ (x,y) | x \ge y, x > -y  \} = \{ (x,y) | x > |y|  \} \cup \{ (x,y) | x = y, y > 0  \} $$
Now take the union of these solutions, a little work shows that it is equal
to
$$ \{ (x,y) | |x| > |y|  \} \cup \{ (x,y) | x = y, y \neq 0  \} $$


text:
Q: Ukraine (Cyrillic) characters not displaying in Jasper Report PDF I am trying to display ukranian character in jasper report as a pdf file. but it is not diaplaying in pdf format.
when I export report to all other format like html, csv..ukranian char is displaying.

A: First, make sure you have the right encoding:
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");

Then you should change the fonts to ones that support cyrillic. This is done via styles:
public void addPdfFontsToStyles(JRStyle[] styles) {
    if (styles != null) {
        for (JRStyle style : styles) {
            if (style.getName().equals("reportStyle")) {
                style.setPdfFontName("/com/yourcompany/fonts/times.ttf");
                style.setBlankWhenNull(true);
            }

            if (style.getName().equals("reportBoldStyle")) {
                style.setPdfFontName("/com/yourcompany/fonts/timesbd.ttf");
                style.setBlankWhenNull(true);
            }

        }
    }
}

And invoke this method with addPdfFontsToStyles(jasperReport.getStyles());
Of course, the prerequisites are:

*

*your text is using one of the above style names

*you have the ttf files on the classpath

That should do it (I'm taking the code from a working cyrilic application)

A: *

*register font in JVM
Font myFont = Font.createFont(Font.TRUETYPE_FONT, new File("pathToCyrillicFont"));
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(myFont);

*add to Cyrillic field this:
<textElement>
   <font
                  fontName="fontName"
                  pdfFontName="pathToCyrillicFont"
                  size="13"
                  isBold="false"
                  isItalic="false"
                  isUnderline="false"
                  isPdfEmbedded ="true"
                  pdfEncoding ="Cp1251"
                  isStrikeThrough="false"
   />
 </textElement>

Enjoy!

A: Since jasper report v5, v6 the correct way to display characters in pdf is to use font-extension
For more information see these question on stackoverflow:
Jasper Reports PDF doesn't export cyrillic values
How can I display "$£Ω€απ⅔" in Jasperserver PDF using iReport?

A: Set some text field properties at iReport. Use font DejaVu Sans. Set pdf encoding to Cp1251 and isPdfEmbedded to true.
Ex.: <font fontName="DejaVu Sans" isStrikeThrough="false" pdfEncoding="Cp1251" isPdfEmbedded="true" />
jasperreports fonts as maven dependency:
<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports-fonts</artifactId>
</dependency>

A: just stumbled over this, the solution for me was to add the font-resource on the server. Go to you report -> edit -> add Resources


text:
Q: python matplotlib for loop plot with function and labels I am trying to plot multiple functions from a array, with labels.
So I found some help from here: https://stackoverflow.com/a/11493343/4055341 and tried to modify the code as it can be seen below. But I get an error with this. SO the error I get is ValueError, but how can I make them the same size?
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)

y = [[5*x], [1*x], [2*x]]

labels = ['foo', 'bar', 'baz']

for y_arr, label in zip(y, labels):
    plt.plot(x, y_arr, label=label)

plt.legend()
plt.show()

A: Replacing y = [[5*x], [1*x], [2*x]] by y = [5*x, 1*x, 2*x] should be enough to solve your problem.
Reasoning:
When you did x = np.linspace(0, 10, 100), x became a Numpy array similar to x = [0, 0.1010, 0.2020, 0.3030, ..., 9.7979, 9.8989, 10]. Multiplying x by a scalar generates a new Numpy array with the same size, such as 5*x = [0, 0.505, 1.01, 1.515, ..., 48.989, 49.494, 50]. Hence, y = [5*x, 1*x, 2*x] will be a list with each element being a proper Numpy array.
Visually, it is like this:
y = [
    [0, 0.1010, 0.2020, 0.3030, 9.7979, 9.8989, 10],
    [0, 0.505, 1.01, 1.515, 48.9895, 49.4945, 50],
    [0, 0.202, 0.404, 0.606, 19.5958, 19.7978, 20]
]

On the other hand, y = [[5*x], [1*x], [2*x]] is a list containing 3 lists, each containing only a single object: the Numpy array resulting from the multiplication. This is the result:
y = [
    [
        [0, 0.1010, 0.2020, 0.3030, 9.7979, 9.8989, 10]
    ],
    [
        [0, 0.505, 1.01, 1.515, 48.9895, 49.4945, 50]
    ],
    [
        [0, 0.202, 0.404, 0.606, 19.5958, 19.7978, 20]
    ]
]

That's why plot breaks: it was expecting an array as long as x but, instead, y_arr is assigned to [[0, 0.1010, 0.2020, 0.3030, 9.7979, 9.8989, 10]] for instance: a list with only one object (which happens to be a Numpy array).


text:
Q: Power BI Report Builder is importing fields with the wrong data type First off, I apologize if this is the wrong place to post this.
I want to create paginated reports off of a SharePoint list. To do this I created a dashboard in Power BI Desktop and Published it to a workspace, like mentioned in this question (Power BI Report Builder - SharePoint as data source). I am then using that data source in Power BI Report Builder. All seems to be good, except that it is importing all fields as text. I have verified that the fields in question are listed as number fields in SharePoint and in the query in Power BI Desktop. Everything that I can tell has been published properly. I've tried everything that I can think of so any ideas would be appreciated.


text:
Q: Maximum subarray problem - min value solution? Have you ever felt like your head wasn't meant for an algorithm?
I tried solving the maximum subarray problem and I came across this solution on Codewars:

var maxSequence = function(arr){
  var min = 0, ans = 0, i, sum = 0;
  for (i = 0; i < arr.length; ++i) {
    sum += arr[i];
    min = Math.min(sum, min);
    ans = Math.max(ans, sum - min);
  }
  return ans;
}

console.log(maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, -4]));

I understand how to solve this problem with a linear time complexity using Kadane's algorithm:

var maxSequence = function(arr){
  let max = 0;
  let localMax = 0;

  for (let i = 0; i < arr.length; i++) {
    localMax = Math.max(localMax + arr[i], arr[i]);
    max = Math.max(localMax, max);
  }

  return max;
}

console.log(maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, -4]));

But I can't make sense of why the first solution works. I simply can't grasp the idea behind it. I feel like a need a little help getting over the hump.
Edit: Here's a Codepen with some examples

A: The algorithm you provided is doing the same thing, in a more complex manner though. In order to explain it properly, I will compare the Codewars algorithm you provided with the Kadanes algorithm in various steps of their execution.

Let us consider the array:
[2 -4 3 2 6 -10 -12 20]

Here is the Codewars algorithm you provided:
var maxSequence = function(arr){
    var min = 0, ans = 0, i, sum = 0;
    for (i = 0; i < arr.length; ++i) {
        sum += arr[i];
        min = Math.min(sum, min);
        ans = Math.max(ans, sum - min);
    }
    return ans;
}

Here is the implementation of Kadanes algorithm mentioned in Wikipedia:
def max_subarray(numbers):
"""Find the largest sum of any contiguous subarray."""
best_sum = 0  # or: float('-inf')
current_sum = 0
for x in numbers:
    current_sum = max(0, current_sum + x)
    best_sum = max(best_sum, current_sum)
return best_sum

First step:-
sum changes to 2 and min remains the same. The ans changes to 2.
Second step:-
sum changes to -2 and min changes to -2. The ans is still 2. An interesting thing to notice here, according the implementation of Kadanes algorithm by Wikipedia, there in the second stage the value of current_sum will change to 0 which is the correct way to proceed.
However in the codewars implementation, the value of sum is still -2. If you notice a little more carefully though, you will observe that the value of sum-min is 0 in the codewars implementation. This is a really important point to notice. Instead of changing sum to 0 when its value reaches less than 0. We store the minimum number that must be substracted from sum to make the net sum 0. This value is stored in min and which also explains why it is named so.
Here is a record of the value of variables so far:
 sum    min    ans
  2      0      2     //ans = max(0, 2-0)
 -2     -2      2     //ans = max(2, -2+2)

Third step:-
The sum changes to 1. min still remains the same. The ans changes to 3 which is the correct. How did this happen though?
In the Kadanes algorithm, you change the value of current_sum to 3 at this stage. In the codewars implementation, instead of changing sum to 3, what they have done is used a min variable which I repeat again stores the number that should be substracted from answer so that we obtain the same value as we do in current_sum. This is more clear from this part of the algorithm.
ans = Math.max(ans, sum - min);   //sum-min is current_max

Here when we substract the min from your sum. It neutralizes that extra negative in your answer. In this array A, the extra negative is 2 + (-4) = -2. In each of the following steps, we will observe that here sum is not containing the maximum continuous subarray sum. Maximum continuous subarray sum there is stored in sum - min. This is the key of this algorithm. sum-min is the current_sum here. Here are the following steps:
sum    min    ans
 1     -2      3      //ans = max(2, 1+2)
 3     -2      5      //ans = max(3, 3+2)
 9     -2      11     //ans = max(5, 9+2)
-1     -2      11     //ans = max(11, -1+2)

It is interesting to observe that even though the value of sum is negative in the last step, the value of min does not change. Why is that? The answer is it does not need to. If you look at sum-min is this case, it is 1 and not less than 0. Hence there is a possibility that if sufficient positive numbers follow after the current index in A, the value of sum-min might exceed the current value of ans. If you dry run Kadanes algorithm till this step, you will notice that even there the value of current_sum will not change to 0 at this stage, it will be 1.
Remaining steps:-
sum    min    ans
-1     -2      11     //ans = max(11, -1+2)
-13    -13     11     //ans = max(11, -13+13)
 7     -13     20     //ans = max(11,  7+13)

The most important point in this implementation, sum-min here is analogous to current_sum of Kadanes algorithm.

I should also mention that the Kadanes algorithm and codewars algorithm you provided will not work if the input array consists of all negative numbers. Both are not meant for it. There is a small implementation difference in the Kadanes algorithm if you want it to work for array consisting of all negative numbers (initialize current_sum to A[0]).
Do comment if you face any problems in understanding my explanation.

A: I don't think the the Codewars algorithm will work for every test case.
Following are the test cases where this algorithm will fail:
Test Case 1: arr = [-1]
Test Case 2: arr = [-1, -2]
For both the test cases, the algorithm under test gives an output equal to 0, which is not the correct answer.
PS: I have checked the Codewars problem. The test cases for the problem are not yet comprehensive and this problem has issues.
So for the time being, Kadane's algorithm is a good choice to solve the problem in linear time complexity.


text:
Q: Finding complex roots of a polynomial I'm having trouble figuring out to find the complex roots of polynomials with degree greater than 2.
I particular, how would I find the (complex) roots of the following: $$x^4 + 5x^2 +4?$$ I know the roots are $\pm i$, $\pm2i$, but for the life of me I cannot figure out how I would determine this if I didn't already know.
Your help would be greatly appreciated!

A: Hint: Subsitute $w=x^2$ and observe that you get a quadratic equation in $w$. Now you can solve it for $w$, substitute back for $x^2$, and solve for $x$.


text:
Q: OutOfMemoryError: bitmap size exceeds VM budget (not an image size issue) I know this error occurred many times on stackoverflow, but usually it was bitmap size problem. Mine is diffrent. I have a ListView with custom adapter. Here's my getView method:
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.cell, null);
    }
    if (position % 2 == 0) {
        convertView.setBackgroundResource(R.drawable.cell_even_bg);
    } else {
        convertView.setBackgroundResource(R.drawable.cell_odd_bg);
    }
}

Now, when I have for ex. 100 cells in my listView and I scroll this list for some time, finally I always get an error OutOfMemoryError: bitmap size exceeds VM budget - and in DDMS I can see that it happens while convertView.setBackgroundResource(...) is called. My drawables are 1x10px and repeated in Y-axis.

A: I write a test application with 100 cells to verify your issue and found it works fine (scroll for many times), without OOM error.
There must be other memory leaks in your code.


text:
Q: Xcode 7.3.1 Debug Bar only has two buttons I'm just working with Xcode 7.3.1 for the first time, and in the debug bar at the bottom of the screeen there is only two buttons shown.  (A downwards facing arrow/close area button and the breakpoint button/right-facing arrow).
How can I get the full range of buttons that are usually on this bar?

A: You won't get full range of buttons which you are expecting unless you execute the app or rather the project which you are working on.
Hope this helps.
Adding a screenshot to confirm:-


text:
Q: How can I align text to the left of my image that is centered? This is what I have so far for the code...
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link href="style.css" rel="stylesheet" type="text/css">

  <title>name of website</title>

Home

About

Work

Contact

 Resume

this is where the text wold be going

enter image description here
I would like the text to be aligned where the yellow bordered box is, and would appreciate some help.

A: You can use the css flex property like, put the image and text inside a div and add use display:flex property to the div and then you can use can use the order property if you want image and text in different order.

A: You can do that by putting your  and your
 tag together inside one div and by using display:flex on that div element.

A: Place the p tag before the img and do as follows:
HTML

this is where the text wold be going

CSS
#portraid {
   display:flex;
   flex-direction:row;
   align-items:center;
   justify-content:center;
}


text:
Q: Mac address pattern angular4 input I am trying Mac address pattern in an angular4 input
pattern="/\w/,/\w/,'\:',/\w/,/\w/,'\:',/\w/, /\w/,'\:',/\w/,/\w/,'\:',/\w/,/\w/,'\:',/\w/,/\w/"

I need mac addresses in the format MM:MM:MM:SS:SS:SS, where M/S should be alphanumeric.
Please help


text:
Q: How does speechify progressively create audio chunks and display it as one audio file? I am unable to figure out the method in which Speechify is turning their text chunks into audio, and then playing it on my phone as if it is one large mp3 file. I am able to play each audio chunk separately and have it play while my ios app is in the background. But somehow Speechify is chunking these audio bits together and offering lock screen controls with an estimated time duration. Any ideas on how they are doing this? Are they streaming from the device to a local url?
Just for some background, Speechify takes text and turns it into mp3 audio. It does this by sending individual sentences as the reader progresses and getting back the base64 encoded mp3 audio chunk. It preloads about 2-3 sentences ahead.
I am using react-native for my frontend and Node + Express for backend. I am using amazon polly to generate the individual audio chunks for sentences. I am trying to mesh these audio chunks together so from the lockscreen it says there is one long file playing, not keep skipping to the next audio track/chunk.


text:
Q: How to provide dynamic pointcut in AspectJ? I am trying to build a custom performance measuring library, which an user can use to measure the performance of any method in an application. My goal is to achieve this thing without changing the existing Java code of the user's application.
The library will use a MethodInterceptor implementation as an advice to measure the performance. The only input from the user will be a pointcut expression of his/her choice, nothing else. And using the provided pointcut expression, my library will be able to intercept the matching method call to measure the performance.
In a nutshell user will only configure like below in spring xml:
<bean id="configBean" class="com.something.PointCutConfigBean">
    <property name="patterns">
        <list>
            <value>"execution(* com.company.CustomerDao.addCustomer(..))"</value>
        </list>
    </property>
</bean>

My question is how can I achieve this in my library? How do I implement the PointCutConfigBean class? I can use spring 2 and aspectj.
I know, same thing can be achieved if the user just write a normal <aop:config and use my advice. But I am just looking for something cooler if at all possible.

A: That's a good question !
Why don't you create an annotation, for tagging method or fields if you need, and write an aspect who can get annotations . Class.getAnnotations(), and if the your annotation is present, you run your code ?

A: After reviewing possible ways, I decided the comment of @M.Deinum has the most valuable points against my decision. Finally, I concluded to go with <aop:advisor advice-ref="..." pointcut="execution(.. route only.
If anybody has any other view, please share.


text:
Q: PEPS mail, smtp able to send email externally but not receiving I'm currently trying to setup PEPS on my server, and having a problem receiving email sent from an external address.
I'm able to send and receive email internally fine, and i'm also able to send email externally, but I never receive email sent from an external address.
I can telnet in to port 25, but I get
connection to host lost

at the end of
HELO example.co.uk
MAIL FROM: address@other.co.uk
RCPT TO: aname@example.co.uk
DATA
Subject: Test
<ENTER>
test Message
.

After i've typed the '.' I instantly get the connection to host lost message

My servers setup using nginx, with multiple sub-domains, i've got PEPS running on mail.example.co.uk via a reverse proxy, and that bit works fine.


text:
Q: Visualization of 3-dimensional grid from X_Y_Z(seperate datasets) on Paraview without using xdmf Reading netcdf files with Paraview using xdmf
I used to parse netcdf files with an xdmf script in order  to create 3DSMesh on paraview. On top of it, I was adding scalar or vector fields.  (So 3DSMesh provides physical coordinates).

I never though if it is best way to do that actually. It works, so I was OK. Please let me know if there is more convenient way.

I am able to create a 3-dimensional grid with the following script.
<?xml version="1.0" ?>
<!DOCTYPE Xdmf SYSTEM "Xdmf.dtd" []>
<Xdmf xmlns:xi="http://www.w3.org/2001/XInclude" Version="2.0">
   <Domain>
      <Grid Name="gridxyz">
        <Topology TopologyType="3DSMesh" NumberOfElements="0032 0032 0063">
        </Topology>
<!-- Read Coordinates -->
        <Geometry GeometryType="X_Y_Z">
           <DataItem Name="X" Format="HDF" NumberType="Float" Precision="8" Dimensions="0032 0032 0063">
                       grid_x.nc:/gridx
           </DataItem>
           <DataItem Name="Y" Format="HDF" NumberType="Float" Precision="8" Dimensions="0032 0032 0063">
                       grid_y.nc:/gridy
           </DataItem>
           <DataItem Name="Z" Format="HDF" NumberType="Float" Precision="8" Dimensions="0032 0032 0063">
                       grid_z.nc:/gridz
           </DataItem>
        </Geometry>
<!-- Read Scalar -->
<!-- Here I have bunch of scalars stored in different netcdf files -->
     </Grid>
   </Domain>
</Xdmf>

Pros

*

*xdmf scripts are great when someone needs repetitive tasks.

Cons

*

*this script(s) needs to be generated somehow, or typed by hand. And required to be updated, when the dimensions or variable names are changed

*if I want to read another scalar, I need to add a line

*grid can be uniform in 2 directions and not uniform on the third one, no need to create 3D grid files, but geometry type dx_dy_dz is not enough to achieve that.
What I am looking for
Recently I realize, I can open netcdf files with paraview just by clicking open(Paraview4.3). So, I do not need these xdmf scripts anymore (few years ago I was not able to open netcdf files on Paraview).

How can I create 3DSMesh via Paraview GUI. Is that possible? Or is there any other simple/faster way (instead of writing a python script) ?
Is there any way read 1D coordinates and create 3D geometry using them ?

A: That's how I manage to do that. Certainly it's not the fastest way, but it works for me.
When you open a NetCDF file, paraview asks you to choose a reader, I always use NetCDF files generic and CF conventions .
After that, before hitting "Apply" button you have to select the appropriate "Dimensions" in the dropdown menu.
Your data now must be displayed as a UniformGrid, with your data(X,Y,Z) as scalars fields so you must transform to a grid to be more specific a StructuredGrid. In order to do that, apply the "ImageDataToPointSet" filter.
After that, apply a "Calculator" filter check "Coordinate Results" field and do the following:
If your data appears as X, Y , Z colummns put in the calculator field the expression
(X * iHat) + (Y * jHat) + (Z * kHat)
if your data appears with other names, substitute x, y, z with those names
The expression means that x is in the direction of the î vector, y is in the direction of the j vector and so on
Hope it helped!


text:
Q: sqlcmd not available after installing mssql-tools I'm trying to access sql server database so i need sqlcmd but after following microsoft docs here and here. Running sqlcmd returns:
 sqlcmd: command not found

and I do have mssql-tools installed:
amir@amir-pc:~$ sudo apt-get install mssql-tools
Reading package lists... Done
Building dependency tree
Reading state information... Done
mssql-tools is already the newest version (14.0.2.0-1).

What am i missing? Also i'm on 16.10 and i had no problem installing it on 16.04

A: *

*Add the path either to ~/.bash_profile or ~/.profile if you don't have .bash_profile in your home directory.
export PATH="$PATH:/opt/mssql-tools/bin"

*Add the following path to your ~/.bashrc file
export PATH="$PATH:/opt/mssql-tools/bin"

*Don't forget to update the path configuration by issuing the following command in your terminal window:
source ~/.bashrc

A: Quoting the page you linked to:

Optional Step: Create symlinks to 'SQLCMD' and 'BCP' under /usr/bin/.
ln -sfn /opt/mssql-tools/bin/sqlcmd-13.0.1.0 /usr/bin/sqlcmd
ln -sfn /opt/mssql-tools/bin/bcp-13.0.1.0 /usr/bin/bcp


text:
Q: classic asp includes not working on IIS7.5 when parent paths is disabled I am migrating a classic asp website from a Windows server running an old IIS to a Windows2008-2 server with IIS7.5 and running classic asp.
This new server does not have parent paths enabled (and they won't turn it on, and I can't get access to IIS control panel - as I am sharing the server with others).
So I am left with trying to find a way to re-code the includes that used to use a relative path to get to a sister directory.
Here is my setup:
I use their free shared ssl and both these files need to be accessed securely (the secure path is: https://ssl5.ssllock.net/mysite.com/)
I have an an .asp file located at: /SMPSECR/my-inc.asp
I have a another .asp file located at: /PBB/my-test.asp
Inside of my-test.asp, I want to include my-inc.asp
I used to use this format: #include file="../smpsecr/my-inc.asp", but since IIS6 that doesn't work anymore (as I mentioned earlier parent paths are automatically disabled and my hosting company won't enabled it for security reasons as I am on a shared server).
I read somewhere that you can use virtual instead of file, but even that didn't work for me.
Here are the 11 different include tests I have tried from inside of my-test.asp and failed for each one:
<!--#include file="https://ssl5.ssllock.net/mysite.com/smpsecr/my-inc.asp"-->
<!--#include file="/smpsecr/my-inc.asp"-->
<!--#include file="smpsecr/my-inc.asp"-->
<!--#include virtual="/smpsecr/my-inc.asp"-->
<!--#include virtual="\smpsecr\my-inc.asp"-->
<!--#include virtual="smpsecr/my-inc.asp"-->
<!--#include virtual="smpsecr\my-inc.asp"-->
<!--#include file=\\n5200-2\iis7_www\f\s\mysite.com\www\smpsecr\my-inc.asp"-->
<!--#include virtual=\\n5200-2\iis7_www\f\s\mysite.com\www\smpsecr\my-inc.asp"-->
<!--#include file="//n5200-2/iis7_www/f/s/mysite.com/www/smpsecr/my-inc.asp"-->
<!--#include virtual="//n5200-2/iis7_www/f/s/mysite.com/www/smpsecr/my-inc.asp"-->

Can anyone give me another include format that could work with my setup.. ie: when trying to include from a different directory (up one level and then down one level - in other words accessing a 'sister' directory.  Going from /PBB to /smpsecr)?
Thanks,
SunnyOz

A: Use virtual paths instead. You have to specify the full path but it gets the job done. I also tried configuring the web site to enable parent paths but that didn't work either.


text:
Q: How to pass event and other arguments to click handler Hey I have a build a canvas using easelJS.
In my canvas, I have points which a click handler is define for them using the following syntax:
p.on("click", handleMouseClickEvent);

Now I want to pass arguments to the handler handleMouseClickEvent , I know that I get the event object for free without passing it, but when I try to pass one argument, lets say I write:
  p.on("click", handleMouseClickEvent(arg1));

Then the event object is undefined and not accessible at all.
How can I pass the event object and many more arguments using the above syntax.
p.on("click", handleMouseClickEvent(arg1,arg2,...,argN));

A: When using jQuery, Ravi's answer is perhaps the best way.
I'll try to provide another perspective to solve your question.
By using
p.on("click", handleMouseClickEvent(arg1));

you're not passing the function as event handler, you're executing it and passing its return value as event handler.
That perhaps already pointed you to the answer, right?
Try to define your event handler like this:
function handleMouseClickEvent(arg1)) {
    return function reallyHandleMouseClickEvent(event) {
        // all variables available here: arg1, event
    }
}

Of course, you can add as many argN parameters as you want.

A: Since you're not calling the handler function yourself (the browser is doing it for you), you don't get to specify further arguments to the handler. All you'll get is the event object.
However, because of how JavaScript's variable scoping works, you don't have to. Functions have access to variables outside themselves, so you can simply access variables without passing them in explicitly:
var foo = "bar";

var handleMouseClickEvent = function(e) {
    console.log(e.type); // 'click'
    console.log(foo); // 'bar'
};

p.on("click", handleMouseClickEvent);

A: You need to define your event handler, try this:
function handleMouseClickEvent(arg1)) {
    return function doSomething(event) {
        //logic here
    }
}

A: you can try this:
p.on("click", null, {arg1: "abc", arg2: "xyz"},handleMouseClickEvent);

//And in your function, you can get the event data like this

function handleMouseClickEvent()
{
    alert(event.data.arg1);
    alert(event.data.arg2);
}

According to official documenatation, on takes arguments like this:

.on( events [, selector ] [, data ], handler )
events Type: String
One or more space-separated event types and optional namespaces, such as
  "click" or "keydown.myPlugin".
selector Type: String
A selector string to filter the descendants of the selected elements that > > > trigger the event. If the selector is null or omitted, the event is always
  triggered when it reaches the selected element.
data Type: Anything
Data to be passed to the handler in event.data when an event is triggered.
handler Type: Function( Event eventObject [, Anything
  extraParameter ] [, ... ] )
A function to execute when the event is
  triggered. The value false is also allowed as a shorthand for a
  function that simply does return false.

For more information, see JQuery Documentation of on() event Handler

A: This should handle it. You can add more arguments.
(function(arg1, arg2) {
  p.on("click", function(event) { handleMouseClickEvent(event, arg1, arg2) })
})(arg1, arg2);

A: The arguments can be bound to a handler function with Function.prototype.bind
p.on("click", handleEventWithArg.bind(this,arg1));

function handleEventWithArg(arg1, event) {
    console.log(arg1);
    console.log(event);
});

The .bind method returns a new functon that the browser can invoke with the event object.

A: Just to throw a more context-specific answer into the mix. I believe this question was asked in reference to this codepen: http://codepen.io/Barak/pen/AXZxKN
From an architecture standpoint, injecting parameters into handlers is a workaround you don't need. Instead, use the event target to access what was clicked/interacted with, and determine the values you need.
For your example, you are looking for the original data properties used to plot the points in your graph. You can either inject those properties onto the display object, inject a reference to the original data object, or create a look-up table to associate the display object with its related data point.
for (...) {
    var point = data[i];
    var dot = new createjs.Shape();
    dot.x = point.x * GRAPH_WIDTH;

    // Inject property or reference
    dot.point = point;

    // Create lookup
    lookupTable[i] = dot;
}

Then when you click the object, look up the data.
dot.on("click", function(event) {
    var dot = event.target;

    // Use reference
    var point = dot.point;

    // Or use lookup
    var index = lookup.indexOf(dot);

    //...do stuff with it
}

There are lots of other ways to create this relationship, these are just some suggestions. Creating wrapper functions will work, but IMHO it is not a great approach for the long term or for a larger application. You can totally continue to use your approach, as it appears to be working for you -- but I wanted to offer some food for thought.
Cheers.


text:
Q: Issue: SwiftUI Button in Toolbar does not respond with empty array in a ForEach loop Issue: SwiftUI Button in Toolbar does not respond with empty array in a ForEach loop. (see attached code snippet)
The viewModel.fetchAllContainer() function in OnAppear() queries a DB and fills the viewModel.fmContainers array
When I start the app with an empty database, the plus.circle button in the toolbar does not respond. However, once a record is present in viewModel.fmContainers, the UI responds as expected.
....
    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.fmContainers, id: \.id) { fmContainer in
                    Button {
                        modal = .update_Container(fmContainer)
                    } label: {
                        FMContainerCellView(fmContainer: fmContainer)
                    }
                }
                .sheet(item: $modal) {
                    // Aufräumarbeiten z.B. nachladen
                    Task {
                        do {
                            try await viewModel.fetchAllContainer()
                        } catch {
                            print("ERROR: FMContainer not loaded")
                        }
                    }

                } content: { modal in
                    switch modal {
                    case .add:
                        // new Container
                        FMContainerDetailView(viewModel: FMContainerDetailViewModel() )
                    case .update_Container(let fmContainer):
                        // update Container
                        FMContainerDetailView(viewModel: FMContainerDetailViewModel(isUpdating: true, fmContainer: fmContainer))
                    default:
                        Text("Error")
                    }
                }
            }
            .listStyle(PlainListStyle())
            .navigationTitle("Objektliste")
            .toolbar {
                ToolbarItem {
                    Image(systemName: "plus.circle")
                        .onTapGesture {
                            modal = .add
                        }
                }
            }
            .onAppear() {
                Task {
                    do {
                        try await viewModel.fetchAllContainer()

                    } catch {
                        print("ERROR: FMContainer not loaded")
                    }
                }
            }

        }
    }
}


text:
Q: Can't check SMART data on SSD? I'm trying to check SMART data. I have Ubuntu 18.04 installed on Kingston A1000, M.2 - 480GB SSD.
I can check all other disks but this.

milano@milano-PC:~$ sudo hdparm -I /dev/nvme0n1p1

/dev/nvme0n1p1:
 HDIO_DRIVE_CMD(identify) failed: Inappropriate ioctl for device

Do you know how to check it?

A: Since SSD drives are designed to use completely different parameters than HDDs, most SMART utilities do not report SSD data correctly.  The smartmontools package for Linux contains a utility to scan for SSDs which will report drive health.
Install the smartmontools package from the command line:
sudo apt install smartmontools

Then use the smartctl tool with the following command where X is the letter of the SSD you want to test (in your case it would be /dev/nvme0n1p1 instead of /dev/sdX):
sudo smartctl -i /dev/sdX

You can a short test on the SSD with this command:
sudo smartctl -t short -a /dev/sdX

Or also a long test with this command:
sudo smartctl -t long -a /dev/sdX


text:
Q: select option in payment method instead of radion button in magento This is my methods.phtml file in onepagecheckout in magento,I want the dropdown(select option) button instead of radio button .........so that i could select the payment method to pay the payment.
<?php if (!$methods = $this->getMethods()) : ?>

<?php echo $this->helper('checkout')->__('Sorry, no quotes are available for this order at this time.') ?>

   <?php else : ?>

     <?php foreach ($this->getMethods() as $_method): $_code = $_method->getCode() ?>

         <?php if( sizeof($this->getMethods()) > 1 ): ?>

              <input  value="<?php echo $_code ?>" type="radio" name="payment[method]" title="<?php echo $this->htmlEscape($_method->getTitle()) ?>" onclick="payment.switchMethod('<?php echo $_code ?>')"<?php if($this->getSelectedMethodCode()==$_code): ?> checked="checked"<?php endif; ?> class="radio" />
              <?php else: ?>
              <input id="p_method_<?php echo $_code ?>" value="<?php echo $_code ?>" type="radio" name="payment[method]" checked="checked" class="radio" />
           <?php endif; ?>
              <label for="p_method_<?php echo $_code ?>"><?php echo $this->htmlEscape($_method->getTitle()) ?> <?php echo $this->getMethodLabelAfterHtml($_method) ?>

        <?php if ($html = $this->getPaymentMethodFormHtml($_method)): ?>

            <?php echo $html; ?>

          <?php endif; ?>
       <?php endforeach; ?>

      <?php endif; ?>

A: You can do the select option dropdown for payment method as setup below code in methods.phtml file.
Also you have to changes in opcheckout.js line no 715 to change "elements[i].checked" to "elements[i].value".
<?php
    $methods = $this->getMethods();
    $oneMethod = count($methods) <= 1;
?>
<?php if (empty($methods)): ?>

        <?php echo $this->__('No Payment Methods') ?>

<?php else:
    ?>

Select Payment Method:

    <select name="payment[method]" onchange="payment.switchMethod(this.value);">
    <?php
    foreach ($methods as $_method):
        $_code = $_method->getCode();
    ?>
        <option id="p_method_<?php echo $_code ?>" value="<?php echo $_code ?>" <?php if($this->getSelectedMethodCode()==$_code): ?> selected="selected"<?php endif; ?>>
            <?php echo $this->escapeHtml($this->getMethodTitle($_method)) ?> <?php echo $this->getMethodLabelAfterHtml($_method) ?>
        </option>
<?php endforeach; ?>
    </select>
    <?php
    foreach ($methods as $_method):
        $_code = $_method->getCode();
    ?>
    <?php if ($html = $this->getPaymentMethodFormHtml($_method)): ?>
    <dd id="dd_method_<?php echo $_code ?>">
        <?php echo $html; ?>

    <?php endif;
    endforeach;
    endif;
?>
<?php echo $this->getChildChildHtml('additional'); ?>

A: I used this one to get my select list if helpful
   <?php
  $ptId1=mysql_query(" some query here")
 echo"<select name=ptId>";
    while($ptId=mysql_fetch_array($ptId1))
        {
            echo '<option value="'.$ptId['id'].'">'.$ptId['id'].'</option>';
        }
    echo '</select>';?>
}


text:
Q: Is Extending Eclipse Package Explorer Impossible? Is it possible to extend the Package Explorer of Eclipse by binding a custom navigatorContent?
When I tested the Project Explorer with my custom navigatorContent, like the xml code below, my contentProvider and labelProvider worked fine with the Project Explorer.
But with the Package Explorer, which means that I substituted 'org.eclipse.ui.navigator.ProjectExplorer' with 'org.eclipse.jdt.ui.PackageExplorer' in the 'viewerId' attribute, it didn't.
So I want to confirm whether the Package Explorer can be extended by custom navigatorContent or not.
Here is the abstract of my plugin.xml.
<extension
    point="org.eclipse.ui.navigator.viewer">
    <viewer
        viewerId="org.eclipse.ui.navigator.ProjectExplorer">
    </viewer>
    <viewerContentBinding
        viewerId="org.eclipse.ui.navigator.ProjectExplorer">
        <includes>
            <contentExtension
                pattern="abc.pkg.explorer.navigator.propertiesContent">
            </contentExtension>
        </includes>
    </viewerContentBinding>
</extension>
<extension
    point="org.eclipse.ui.navigator.navigatorContent">
    <navigatorContent
        id="abc.pkg.explorer.navigator.propertiesContent"
    .. omitted below.

A: I found the answer.
It is not possible because 'Package Explorer' doesn't use the 'CommonNavigator'.
If you want to extend the 'Package Explorer', you should do the other way.
That is to say, you need to make a custom view extending 'CommonNavigator', and then bind 'Java Element' navigatorContent with your custom view.
You can find 'Java Element' navigatorContent in the 'org.eclipse.jdt.ui' plug-in which includes the 'Package Explorer'.


text:
Q: Extract certain values out of a correlation matrix Is there a way to distract the correlation coefficients out of a correlation matrix ?
Let's say I have a dataset with 3 variables (a, b, c) and I want to calculate the correlations among themselves.
with

df <- data.frame(a <- c(2, 3, 3, 5, 6, 9, 14, 15, 19, 21, 22, 23),
                 b <- c(23, 24, 24, 23, 17, 28, 38, 34, 35, 39, 41, 43),
                 c <- c(13, 14, 14, 14, 15, 17, 18, 19, 22, 20, 24, 26),
                 d <- c(6, 6, 7, 8, 8, 8, 7, 6, 5, 3, 3, 2))

and
cor(df[, c('a', 'b', 'c')])

I'll get a correlation matrix:
          a         b         c
 a 1.0000000 0.9279869 0.9604329
 b 0.9279869 1.0000000 0.8942139
 c 0.9604329 0.8942139 1.0000000

Is there a way to show the results in a manner like this:

*

*Correlation between a and b is: 0.9279869.

*Correlation between a and c is: 0.9604329.

*Correlation between b and c is: 0.8942139:

?
My correlation matrix is of obviously bigger (~300 entries) eand I need a way to distract only the values that are important for me.
Thanks.

A: You can do,
df1 = cor(df[, c('a', 'b', 'c')])
df1 = as.data.frame(as.table(df1))
df1$Freq = round(df1$Freq,2)
df2 = subset(df1, (as.character(df1$Var1) != as.character(df1$Var2)))
df2$res = paste('Correlation between', df2$Var1, 'and', df2$Var2, 'is', df2$Freq)

 Var1 Var2 Freq                                 res
2    b    a 0.93 Correlation between b and a is 0.93
3    c    a 0.96 Correlation between c and a is 0.96
4    a    b 0.93 Correlation between a and b is 0.93
6    c    b 0.89 Correlation between c and b is 0.89
7    a    c 0.96 Correlation between a and c is 0.96
8    b    c 0.89 Correlation between b and c is 0.89

A: Here is another idea with reshaping to long format, i.e.
tidyr::pivot_longer(tibble::rownames_to_column(as.data.frame(cor(df[, c('a', 'b', 'c')])), var = 'rn'), -1)

# A tibble: 9 x 3
  rn    name  value
  <chr> <chr> <dbl>
1 a     a     1
2 a     b     0.928
3 a     c     0.960
4 b     a     0.928
5 b     b     1
6 b     c     0.894
7 c     a     0.960
8 c     b     0.894
9 c     c     1

A: Using reshape2 and melt
df <- data.frame("a" = c(2, 3, 3, 5, 6, 9, 14, 15, 19, 21, 22, 23),
                 "b" = c(23, 24, 24, 23, 17, 28, 38, 34, 35, 39, 41, 43),
                 "c" = c(13, 14, 14, 14, 15, 17, 18, 19, 22, 20, 24, 26),
                 "d" = c(6, 6, 7, 8, 8, 8, 7, 6, 5, 3, 3, 2))

tmp=cor(df[, c('a', 'b', 'c')])
tmp[lower.tri(tmp)]=NA
diag(tmp)=NA

library(reshape2)
na.omit(melt(tmp))

resulting in
  Var1 Var2     value
4    a    b 0.9279869
7    a    c 0.9604329
8    b    c 0.8942139

A: Maybe you can try as.table + as.data.frame
> as.data.frame(as.table(cor(df[, c("a", "b", "c")])))
  Var1 Var2      Freq
1    a    a 1.0000000
2    b    a 0.9279869
3    c    a 0.9604329
4    a    b 0.9279869
5    b    b 1.0000000
6    c    b 0.8942139
7    a    c 0.9604329
8    b    c 0.8942139
9    c    c 1.0000000


text:
Q: Set node weight I have a CSV lists of nodes and edges, and load both accordingly in Gephi.
My node list looks like this:
Id          Date        weight
56079348    12.07.2009  141
77150491    25.09.2009  2161
612473      08.01.2007  94
621523      10.01.2007  128

I want to make node circles sized according weight column.
Is it possible, and if yes how to?

A: Yes it is possible, this is what the ranking panel is for.
Be sure to have imported your "weight" values as numerical values (Float, Integer, Long...), not textual (String). This can be checked in the import wizzard, at the step when you are asked to confirm / choose the type of each attribute.
Once you have made this check, visit the "ranking" panel in Gephi and select your weight attribute in the drop down menu. Then click on "Apply".
This tutorial has some slides on ranking, and more: http://www.slideshare.net/gephi/gephi-quick-start.


text:
Q: Can't Travel From Siwa To Alexandria - Install In Progress (Stuck at 28%) I recently bought a pre-owned disc of Assassin's Creed: Origins for the PS4. The game downloaded and installed fine; the console said everything had downloaded (nothing of concern in Downloads).
I played through the beginning of the game with no trouble, took time on side quests and whatever else, really liking the game. Once I got to the point where you confirm you wish to move on from Siwa to Alexandria with Hepzefa, I found myself stuck on the Animus loading screen (the one with the tips, etc.) with a note saying 'Install In Progress, 28% Completed' in the top right corner.
Checked for any download issues and/or console updates once waiting for a good while, and everything was up to par. Googled it, only found the same issue from a few years back (2017, etc. This is 2020), and thought it may be patched by now. Currently reinstalling the entire game, but if that doesn't work, I'm unsure of what else to do other than replace the disc and hope for the best. Any help is appreciated :))
Small Edit: Disc is completely clear of smudges and scratches, thankfully. After deleting and reinstalling, the note now says it is at 24% rather than 28%. Just seems to be going south at this point :')


text:
Q: Add image from website to Frame in Java I'm trying to make a Frame from which I want to add an image from a website.
Do I set the background as an image?
import java.awt.*;
import java.net.*;

class NewFrame extends Frame {

  // Constructor.
  public NewFrame (int width, int height)
  {
    // Set the title and other frame parameters.
    this.setTitle ("Exercise 9.5");
    this.setResizable (true);
    this.setBackground (Color.cyan);
    this.setSize (width, height);

    // Show the frame.
    this.setVisible (true);
  }

  // Override paint():
  public void paint (Graphics g)
  {

  }

} // End of class "NewFrame"

public class ex5 {

  public static void main (String[] argv)
  {
    NewFrame nf = new NewFrame (300, 250);
  }

}

A: You can use the following
 // load the image once
 BufferedImage bi = ImageIO.read(new URL(imageLocAsString));
 // now in paint(Graphics g) do
 g.drawImage(bi, 0, 0, null);

Look here for more information.