Find matrix $A$ such that $A^2=B$ and $A^3=C$

Question: Given
B=
  \begin{bmatrix}
    0 & 0 & 1 & 0 & 1 \\
    0 & 0 & 0 & 1 & 0 \\ 0 &0 &0& 0& 0\\ 0 &0 &0& 0& 0\\ 0 &0 &0& 0& 0\\
  \end{bmatrix}
and C=
  \begin{bmatrix}
    0 & 0 & 0 & 1 & 0 \\
    0 & 0 & 0 & 0 & 0 \\ 0 &0 &0& 0& 0\\ 0 &0 &0& 0& 0\\ 0 &0 &0& 0& 0\\
  \end{bmatrix}
Find matrice $A$ such that $A^2=B$ and $A^3=C$.
My attempt(seems correct) I was thinking of adjacency matrix of a directed graph on 5 vertices. Here $A^3=C$ means there is 1 path of length 3 from 1to 4 and $A^2=B$ means there is 1 path of length 2 from vertex 1 to 3, 1 to 5 and 2 to 4. From that I deduced that what the original graph look like and get that A=  \begin{bmatrix}
    0 & 1 & 0 & 0 & 0 \\
    0 & 0 & 1 & 0 & 1 \\ 0 &0 &0& 1& 0\\ 0 &0 &0& 0& 0\\ 0 &0 &0& 0& 0\\
  \end{bmatrix}
Comment: What have you tried? Please add your attempts in the question (not in the comments), that way it is easier for others to answer your question.
Comment: Hint: In $AB = C$ and $BA = C$, treat $A$ as a linear transformation on $B$.  You have two different interpretations of $L_A: B\mapsto C$.  Can you continue?
Comment: Note that in general there may not exist a matrix $A$ with $A^2=B$ and $A^3=C$. Take $B=0$ and $C=I_n$, for example.
Comment: I think your attempt is a very good one already.  TBH, I think it works better than the accepted answer (if you want to find just one matrix $A$, not all possible $A$, of course).  I was thinking about this approach right away when I saw the problem.
Answer: so we know $A^2=B$ and $A^3=C$. From this we get that $AB=C$
so:
$$\begin{bmatrix}
a_1&a_2&a_3&a_4&a_5\\
b_1&b_2&b_3&b_4&b_5\\
c_1&c_2&c_3&c_4&c_5\\
d_1&d_2&d_3&d_4&d_5\\
e_1&e_2&e_3&e_4&e_5
\end{bmatrix}
\begin{bmatrix}
    0 & 0 & 1 & 0 & 1 \\
    0 & 0 & 0 & 1 & 0 \\ 0 &0 &0& 0& 0\\ 0 &0 &0& 0& 0\\ 0 &0 &0& 0& 0\\
  \end{bmatrix}
=\begin{bmatrix}
    0 & 0 & 0 & 1 & 0 \\
    0 & 0 & 0 & 0 & 0 \\ 0 &0 &0& 0& 0\\ 0 &0 &0& 0& 0\\ 0 &0 &0& 0& 0\\
  \end{bmatrix}$$
now you could multiply this out and solve the simultaneous equations you get
Comment: The first two columns of $A$ can be found by inspection. Recall that right-multiplying by the $j$th column of the identity picks out the $j$th column of the matrix.


CheckListBox - como passar um checklisbox para um função no Delphi

Question: Preciso criar um função onde eu passo para a função um CheckListBox e esta função irá armazenar em uma variável os valores do checklistbox.
function PegaDescricao(checklistbox .......... ) : String;
var i, cont, descricao : Integer;
begin
  cont := 0;
  for i:=0 to checkListBox.Items.Count-1 do
  begin
    if cont = 0 then
    begin
      cont := contad +1;
      descricao:=copy(checkListBox.Items.Strings[i],1,Length(checkListBox.Items.Strings[i])-4);
    end
    else
      descricao:=descricao+', '+copy(checkListBox.Items.Strings[i],1,Length(checkListBox.Items.Strings[i])-4);
  end;
end;

Answer: Como qualquer parâmetro delphi, você precisa declarar o seu tipo. Todos os componentes delphi são objetos, logo basta passar o nome da classe referente ao objeto junto com o parâmetro.
function PegaDescricao(checklistbox: TCheckListBox): String;

Comment: Com esta dica o problema foi resolvida a questão, apenas corrigindo no lugar do tipo do parâmetro TCkeckListBox tive de utilizar o tipo TfrxCheckListBoxControl. Ficando assim o cabeçalho da função:

function PegaDescricao(checklistbox: TfrxCheckListBoxControl) : String;


Data can't be fetched in ReactJS from ASP.NET webService

Question: I'm using ReactJS with functional components for my front-end trying to fetch data from the ASP.NET WebService,
SomeComponent.jsx
 const URL = 'http://localhost:63579/WebService.asmx/ProductList'
 const productList = () => {
    fetch(URL)
      .then((response) => response.json())
      .then((data) => {
        settingResults(data);
      });
  };

The WebService webmethods are working - checked ✔ all data received from the SQL.
Edit this is the Error-

Error:

The output string from Webservice:
<string xmlns="http://tempuri.org/">[{"ProductID":1,"ProductName":"Vitamin C","CategoryName":"Vitamins","Price":10,"Stock":268,"ProductDescription":"","ProductOverview":"","ProductImage":"https://image.flaticon.com/icons/png/512/1052/1052788.png"}</string>
Comment: This is issue in the service side not in react. You should modify your config to allow cors..
Answer: You can add this to your web service web.config, and it should work
<system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type" />
          <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
         <add name="Access-Control-Allow-Credentials" value="true" />
        </customHeaders>
      </httpProtocol>
  </system.webServer>

Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/235751/discussion-between-extrasun-and-rabeeh-mohammed).


live Boot any linux distro to console

Question: Is there any .iso linux image distro that boots into console and not into x?
I just want to run some simple linux commands like ethtool
alternatively, I would like any boot cd that let me test the physical connection of a NIC.
Thanks.
Answer: http://www.sysresccd.org/Main_Page
Answer: Knoppix will do it with the knoppix-txt kernel boot label.  See Knoppix Cheat Codes.
Answer: Most Linux Live Distributions provide an option to boot into text mode.
Here is a good option for sysadmins.

live Boot any linux distro to console


Custom Condition on Query

Question: I'm trying to add a custom condition in a query:
<code> $today = new DrupalDateTime();
 $today = $today->format("m-d");
 $ids = Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition("date_format('field_birthday','%m - %d')", $today, '=')
  ->execute();
</code>
Error:

PHP message: Uncaught PHP Exception
  Drupal\Core\Entity\Query\QueryException:
  "'date_format('field_birthday','%m-%d')

Version Drupal 8.8.4
What is the best way to solve this?
Answer: You can try use hook_query_TAG_alter
<code>...
->addTag('my_module_birtday')

/**
 * Implements hook_query_TAG_alter().
 */
function my_module_query_my_module_birtday_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $today = new DrupalDateTime();
  $today = $today->format("m-d");
  $query->addJoin('LEFT', 'user__field_birthday', 'field_birthday', 'field_birthday.entity_id = base_table.uid');
  $expression = "DATE_FORMAT(field_birthday.field_birthday_value,'%m-%d')";
  $args = [
    ':birthday'=>$today
  ];
  $query->where($expression . '=:birthday', $args);

}
</code>

Custom Condition on Query


Adding bootstrap to Vue CLI project

Question: I'm new to Vue and webpack in general and I'm having a hard time figuring out how to import things.
I created a fresh Vue project through vue init I added bootstrap 4 with yarn add email@example.com
In main.js I try to import bootstrap and jquery:
import Vue from 'vue';
import jQuery from 'jquery';
import bootstrap from 'bootstrap';
import App from './App';
import router from './router';

But I get:

Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be
  included before Bootstrap's JavaScript.

window.jQuery = window.$ = $; does not work
Finally, where and how do I load the Sass such that it's available to the whole app?
Comment: This might help ~ http://stackoverflow.com/questions/34120250/error-using-bootstrap-jquery-packages-in-es6-with-browserify
Comment: Possible duplicate of [Error using Bootstrap & jQuery Packages in ES6 with Browserify](http://stackoverflow.com/questions/34120250/error-using-bootstrap-jquery-packages-in-es6-with-browserify)
Comment: "`window.jQuery = window.$ = $;` does not work" Well, no, because nowhere in your code is `$` being set. `window.jQuery = window.$ = require('jquery')` might work better.
Comment: This too ~ https://github.com/AngularClass/angular2-webpack-starter/issues/696
Comment: (window.$ = $; window.jQuery = $;) do not work for me.
Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.
Comment: Also if I add them before the bootstrap import I get a linter error, it wants all the imports at the top.
Comment: This Answer may help you. https://stackoverflow.com/questions/54755246/how-can-include-bootstrap-min-js-from-node-modules-in-vue-cli/68726801#68726801
Answer: I was having the same issue and this is what I ended up with however, I didn't use Bootstrap alpha since the beta has since been released.

Install Bootstrap along with its dependencies, jQuery and Popper.js:

npm install firstname.lastname@example.com popper.js jquery --save-dev

Edit your /build/webpack.dev.conf.js file to add a plugin for jQuery and Popper.js to deal with dependencies (you can read more about that  in the Bootstrap docs):

plugins: [
    // ...
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        Popper: ['popper.js', 'default'],
        // In case you imported plugins individually, you must also require them here:
        Util: "exports-loader?Util!bootstrap/js/dist/util",
        Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
        // ...
    })
    // ...
]

Edit /src/main.js to import Bootstrap into the app's entry point:

import Vue from 'vue'
import App from './App'
import router from './router'
import 'bootstrap' // ←

Edit the App.vue' file's

Run your Vue app from the CLI

npm start

I had to add the @import rule after the #app selector, otherwise the scoped styling
would be canceled out by the Bootstrap import. I think there is a better way to do this so I will update my answer once I figure it out.
Comment: Looks like you can, instead of importing into the css, in your main.js file just below

    `import 'bootstrap'`

you can add

    `import '../node_modules/bootstrap/dist/css/bootstrap.css';`
Comment: I think that these should be installed as regular dependencies not -dev dependencies
Answer: You don't want to do any kind of adjustment in webpack.config.js like adding jQuery global in plugin array.
Once you installed all bootstrap dependencies like jQuery and popper than just import them in app.vue or main.js (you can import separately in each component if you wish)
import 'bootstrap/dist/css/bootstrap.min.css'
import 'jquery/src/jquery.js'
import 'bootstrap/dist/js/bootstrap.min.js'

thats it ..
Comment: This should become the selected answer
Comment: This is it. What is that webpack haystack as accepted answer?
Answer: I will try to be as precise  as possible
1.Go the the Vue Cli project
 run :
npm i bootstrap jquery popper.js
2.Go to src/main.js
import like:
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
Answer: Only For Bootstrap 5
Follow the below in cmd

vue create project-name

Select Vue version

cd project-name

npm i bootstrap @popperjs/core (just bootstrap means latest available bootstrap version)
              (or)

i)npm i bootstrap (to install bootstrap)
ii)npm install --save @popperjs/core (to install popper.js)
Note: Try this if only point 4 emits error

Add the below to src/main.js
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

Done now bootstrap will work on Vue-Cli
Answer: With Vue CLI v3.x/v4.x, you can also use the @techiediaries/vue-cli-plugin-bootstrap to quickly add the latest Bootstrap 4 version in your Vue project without manually adding any files or settings.
Head over to a new command-line interface, navigate to your project's folder and run the following command:
$ vue add @techiediaries/bootstrap

The plugin will take care of adding any configuration options and install the dependencies into your project so you can start using Bootstrap classes right away without spending time figuring out what settings or dependencies you need to add.
Answer: For Gridsome users, the solution is exactly the same!
yarn add jquery bootstrap popper.js

import 'jquery/src/jquery.js';
import 'popper.js/dist/popper.min.js';
import 'bootstrap/dist/js/bootstrap.min.js';

You can also import the css here like this
import 'bootstrap/dist/css/bootstrap.min.css' however bootstrap provides a SCSS file which can be highly customisable, if you want this kind of customisation, import in the main.js file a new scss file
// Load core styling
import '~/assets/styles/core.scss';

and then import bootstrap like this
@import '~bootstrap/scss/bootstrap';
@import 'theme.scss';

The theme.scss follows this document https://getbootstrap.com/docs/4.0/getting-started/theming/
Answer: Brother, Greetings!
Simple way to install and configure Bootstrap in your Vue project is that

First install bootstrap using a command in the terminal of the IDE which is below:
npm i bootstrap

You need to configure this in your main.js file so that it is applied to the whole project. You need to import this from node_modules folder to use it in project.
import "../node_modules/bootstrap/dist/css/bootstrap.css";
import "../node_modules/bootstrap/dist/js/bootstrap.bundle";

Just paste these lines in your main.js file because this is the path where your
required bootstrap files will be if not then check the path and edit this path.
If you want to test whether it has worked or not, go to the app component and
create a button, provide it a bootstrap class and run the project to see whether
it is working or not.
Thanks, take care :)
Screenshot:
Answer: Depending on what packages you already have installed (such as Vuetify), you may not be able to use boostrap 4 + vue 3. Check your versions to confirm before following the directions in the thread!
Answer: As usual in JS ecosystem the answers get out of date very quick.. this is what is working for my right now:
$ yarn add jquery bootstrap @popperjs/core
├─ @email@example.com
├─ firstname.lastname@example.com
└─ firstname.lastname@example.com

// main.js
import '@popperjs/core/dist/umd/popper';
import 'bootstrap/dist/css/bootstrap.min.css'
import 'jquery/src/jquery.js'
import 'bootstrap/dist/js/bootstrap.min.js'

Answer: It is very simple.

Step 1: Install bootstrap

npm install bootstrap

Now inside the module, the bootstrap folder gets added which confirms that the installation is successful.

Step 2: Import bootstrap into main.js folder

import "../node_modules/bootstrap/dist/css/bootstrap.css";
import "../node_modules/bootstrap/dist/js/bootstrap.bundle";

Hey  now you can see that Bootstrap is added. And add some bootstrap colors for testing.
Answer: use Bootstrap CDN and include it as a  in your index.html
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

I never used Bootsrap with Vue.js, as I'm not a fan. But when I used Bulma's sass, first I did npm install for Bulma. Then I created a folder in src/assets/sass  and inside it created a main.scss and inside it I imported bulma by @import '~bulma/bulma';
Comment: This doesn't allow for usage of any of the jQuery functionality.
It should be installed the way specified in the accepted answer
Answer: jQuery is not required in current version (Right now: "bootstrap": "^4.4.1",
    "bootstrap-vue": "^2.5.0")

install bootstrap

npm install bootstrap-vue bootstrap --save

Then, register BootstrapVue in your app entry point (main.js)

import BootstrapVue from 'bootstrap-vue/dist/bootstrap-vue.esm';
Vue.use(BootstrapVue)

And import Bootstrap and BootstrapVue css files in main.js:

import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Comment: jQuery is required in bootstrap 4. However, the current bootstrap version 5.0.0.beta3 and future versions will not require jQuery. Your first sentence gave a false impression that jQuery is not a dependency for bootstrap 4.

Adding bootstrap to Vue CLI project


How to upload/publish products to Amazon via Amazon MWS API?

Question: I heard SubmitFeed API is for adding products. But i didn't find any example.
By the way, i need a Python solution.
Thanks a lot.
Answer: The general gist of it is you use SubmitFeed to send your product list. Then you must check the status of the submission. Once the submission is complete you can then get the results. You have to repeat these steps for images, pricing and availability.
It's a bit of a pain to get started with it, Amazon supply a LOT of useful information but it is everywhere and not particulary very easy to understand at first. Experiment with just adding products to your inventory and go from there. Make use of the scratchpad too, very handy tool indeed.
As for python I can't help you there I'm afraid but I think there is sample code within the python download available from Amazon.


Java: Trouble calling another class

Question: I am just beginning in Java and I am having a peculiar problem that I just cant seem to get to the root of. I have 2 programs and one is taking data from a text file and then calling it into a class to do some calculations and finally putting the output into another text document.
Everything works except this part here:
public class Paycheck
{
//Constants for the private class
private final String EMPLOYEE_NAME;           //Employee name
private final String SOC_SEC_NUM;             //Employee Social Security Number
private final double WAGE_RATE;               //Employee wage
private final double TAX_RATE;                //Employee tax withheld
private final double HOURS_WORKED;            //Employee's hours of work

//Variables for the private class
private double grossPay;                      //Employee Gross Pay
private double taxWithheld;                   //Employee Tax Withheld
private double netPay;                        //Employee Net Pay

//This is the constructor. It is called whenever an instance of the class is created
public Paycheck (String name, String ssn, double wage, double tax, double hours)
{
    EMPLOYEE_NAME = name;  //Instance employee name
    SOC_SEC_NUM = ssn;    //Instance employee SSN
    WAGE_RATE = wage;      //Instance employee wage rate
    TAX_RATE = tax;        //Instance employee tax rate
    HOURS_WORKED = hours;  //Instance employee hours worked
}

//This calculates the variables in the paycheck class
public void calcWages()
{
    grossPay = WAGE_RATE * HOURS_WORKED;    //Calculates Gross Pay
    taxWithheld = grossPay * TAX_RATE;      //Calculates Taxes Withheld
    netPay = grossPay - taxWithheld;        //Calculates net pay

}

//Returns the Paycheck objects Employee Name
public String getEmployeeName()
{
    return EMPLOYEE_NAME;
}

//Returns the employee SSN of the Paycheck object
public String getSocSecNum()
{
    return SOC_SEC_NUM;
}

//Reeturns a Paycheck object's employee Wage Rate
public double getWageRate()
{
    return WAGE_RATE;
}

//Returns a Paycheck object's employee tax rate
public double getTaxRate()
{
    return TAX_RATE;
}

//Returns an Paycheck object's employee hours worked
public double getHoursWorked()
{
    return HOURS_WORKED;
}

//Returns a Paycheck object's gross pay
public double getGrossPay()
{
    return grossPay;
}

//Returns a Paycheck object's Taxes Withheld
public double getTaxWithheld()
{
    return taxWithheld;
}

//Returns a paycheck object't net pay
public double getNetPay()
{
    return netPay;
}

The calcWages() does the necessary calculations and below this are a series of get statements to call them. However, my output does not return any values for the calcWages() arguments.
I added the getters here and my other program is grabbing them. However the final output on my other program is coming up as 0.
Where am I going wrong here?
This is the part of the main method that is calling them
  public static void main(String [] args) throws IOException //Throws clause
{
    //Declare constants
    final String INPUT_FILE = "Employee.txt";         //Input text file containing Employee information
    final String OUTPUT_FILE= "PayrollHistory.txt";   //Output text file that will receive the data

    //Declare Variables
    String payPeriodDate;       //Ending date of the pay period
    String employeeName;        //Employee Name in text file
    String employeeSocSecNum;   //Employee SSN in text file
    double employeeHours;       //Employee hours worked
    double employeeTax;         //Employee Tax rate
    double employeeWage;        //Employee Wage rate
    double totalGrossPay;       //Total employee Gross for pay period
    double totalTaxWithheld;    //Total Tax Withheld for pay period
    double totalNetPay;         //Total Net Payroll for pay period
    String input;               //String input for double conversion in JoptionPane

    DecimalFormat money = new DecimalFormat ("#0.00"); // Decimal Format to put money in the right format(USD)

    //This ensures that the input file actually exists in the program folder
    //And exits the program if it does not, along with the prompt.
    File file = new File(INPUT_FILE);
  if (!file.exists())
  {
     JOptionPane.showMessageDialog(null, "The " + INPUT_FILE + " file cannot be found." +
                        "Program terminated.");
     System.exit(0);
  }

    // Create Scanner object to enable reading data from input file
  Scanner inputFile = new Scanner(file);

  // Create FileWriter and PrintWriter objects to enable
  // writing (appending not overwriting) data to text file
  FileWriter fwriter = new FileWriter(OUTPUT_FILE, true);
  PrintWriter outputFile = new PrintWriter(fwriter);

    //Initialize accumulator values
  totalGrossPay = 0.0;
    totalTaxWithheld = 0.0;
    totalNetPay = 0.0;

    //Get the pay period for the employee
    payPeriodDate = JOptionPane.showInputDialog("Enter pay period ending date (mm/dd/yyyy):");
    outputFile.println("PAY PERIOD ENDING DATE: " + payPeriodDate);          //Inputs pay period date into the text file
    outputFile.println(); // Blank line
    outputFile.println(); // Blank line

    while (inputFile.hasNext()) // This will look through the input file and get the necessary variable input
  {
     // Read employee Name from Input File
     employeeName = inputFile.nextLine();
     // Read employee SSN from input file
     employeeSocSecNum = inputFile.nextLine();
     // Read employee Wage Rate from input file
        //Parses it into a double type
     input = inputFile.nextLine();
     employeeWage = Double.parseDouble(input);
        //Read employee tax rate from input file
        //Parses it into a double type
        input = inputFile.nextLine();
        employeeTax = Double.parseDouble(input);

        //Get number of hours worked
        input = JOptionPane.showInputDialog("Employee Name: " + employeeName +
                                                        "\nEnter number of hours worked:");
        employeeHours = Double.parseDouble(input);

        //This call the paycheck class to create a new Paycheck Object
        Paycheck employee = new Paycheck (employeeName, employeeSocSecNum, employeeWage, employeeTax, employeeHours);

        // Call Paycheck class methods into the output file
     outputFile.println("Employee Name: " + employeeName);                              //Employee Name
     outputFile.println("SSN: " + employeeSocSecNum);                                   //Employee SSN
     outputFile.println("Hours Worked: " + employeeHours);                              //Employee Hours Worked
     outputFile.println("Wage Rate: " +  money.format(employeeWage));                   //Employee Wage Rate
        outputFile.println("Gross Pay: " +  money.format(employee.getGrossPay()));         //Employee Gross Pay
        outputFile.println("Tax Rate: " +  money.format(employeeTax));                     //Employee Tax Rate
        outputFile.println("Tax Withheld: " +  money.format(employee.getTaxWithheld()));   //Employee Tax Withheld
        outputFile.println("Net Pay: " + employee.getNetPay());                            //Employee Net Pay
     outputFile.println(); // Blank line

Comment: Hi, can show the code that is actually calling this class, that isnt working? What output are you refering to?
Comment: post code where you are calling calcWages and where you are printing the output. You likely are referencing the wrong object
Comment: Where are you actually *calling* your getters? You didn't add that. We're looking for a main method here.
Comment: Still incomplete. How are you initializing employee?
Comment: I added the main method portion as well as the getters.
Comment: Paycheck employee = new Paycheck (employeeName, employeeSocSecNum, employeeWage, employeeTax, employeeHours);
Comment: 1. put that in the question, 2. ok, yes, see my answer.
Answer: You don't appear to be actually calling calcWages() before calling your getters, so  grossPay, taxWithheld, and netPay are still going to be 0, as that's Java's default value for uninitialized numbers.
You need to call employee.calcWages() before referencing those values for them to change.
Comment: To clarify a little for the OP, you need to actually _call_ `calcWages()` e.g., right after you create a new Paycheck, but before your print statements you need `employee.calcWages();`   --Also don't forget to accept @Colleen 's answer
Comment: didn't want to "steal" your answer...just seemed like he was missing the point a little :)
Answer: It is because calcWages() is declared void (public void calcWages()), meaning it is not supposed to return any value but just complete a series of steps (calc payroll particulars in this example).  After calling it, just proceed to reference the instance variables it processed.
Comment: where do you call calcWages? maybe what you're not getting is the function won't DO anything unless you call it somewhere
Comment: Yes, I know that but the get statement below should be able to actually get me the value yes?
Answer: You have declared your variables as final, meaning they can only be assigned once.
Comment: I don't understand. Where do I need to initialize?
Comment: @Colleen, looks like your answer is correct. The code he posted originally was somewhat incomplete.
Comment: On a side note, the way you're looping through the input file isn't correct - you should only call `nextLine()` once inside the loop body. Example:
`while (input.hasNext()) { line = input.nextLine(); }`

Java: Trouble calling another class


Set default value in PostgreSQL table column to a value from a query

Question: I want to do the following
ALTER TABLE runs ADD COLUMN userId bigint NOT NULL DEFAULT (SELECT id FROM users WHERE email = 'email@example.com');

but it keeps giving me syntax error. How could I do this guys?
Any help is highly appreciated. ;)
Comment: its wrong _you cannot use subquery in default expression_
Answer:
Create a function to get the id from the table users with email as an arg.
CREATE OR REPLACE FUNCTION id_in_users(iemail varchar)
RETURNS int LANGUAGE SQL AS $$
   SELECT id FROM users WHERE email = email;
$$;

And alter the table
ALTER TABLE runs ADD COLUMN userId bigint NOT NULL DEFAULT
id_in_users('firstname.lastname@example.com');

SQL FIDDLE(DEMO)
Comment: +1 I was curious to see if this worked so I created a SQL Fiddle and gave it a try and it looks like it works ok. Feel free to include the fiddle in your answer. http://www.sqlfiddle.com/#!15/fcc39/9
Comment: Thanks guys, you're the best. I am surprised at how fast I got the answer. Keep it up guys ;)
Answer: You can't do that on DEFAULT. However you could use a trigger before insert checking if there is a NULL value.
You can check the PostgreSQL Trigger Documentation here


Is there a good way to denote nested repeats?

Question: I'm arranging a song and I have a jam section in it that could be repeated an arbitrary amount of times. The problem is that the jam section itself contains repeats, so I have "nested repeats".
What I want to accomplish can be illustrated with this picture:

So the jam section is on the form AABC, and this whole form should be repeated until the conductor gives a cue.
There will be music both before and after this section. How do I handle nested repeats in a good way?
Comment: Just want to point out that, technically, a single start repeat is sufficient in this case, since they both go back to the same spot. That said, musicians will probably assume that the first :|| should be a :||: since that is an extremely common mistake. Hence the need to find a way to make it perfectly clear that you go back to the same place both times.
Comment: If this is supposed to be a Jazz piece, then it is assumed that the form will repeat.
Comment: Oh, those ledger lines!
Comment: Fiddle tunes (in old-time American music) can also be assumed to repeat.
Comment: I'm voting to close this question because the newer duplicate has the same and better answers. Merging the two might be helpful in this case. [Is there a way to notate the repeat of a larger section that itself has repeats in it?](https://music.stackexchange.com/questions/108182/is-there-a-way-to-notate-the-repeat-of-a-larger-section-that-itself-has-repeats)
Answer: Repeat barlines for the short repeat, DS for the big one.  Probably with some explanatory text.  Or just write the 8 bars out twice.
You'll find this sort of thing (picture) too, but with even more emphasised 'wings' on the outside repeat barlines.  Easy to do effectively handwritten, not so easy in a notation program.
Comment: Thanks. I should have mentioned that this was in Musescore, but this is a good answer the question I actually asked.
Comment: With DC or DS, it's [customary to skip repeats on the second run](http://learnmusictheory.net/PDFs/pdffiles/01-01-08-RepeatSigns.pdf), and it's unusual to repeat an indefinite number of times. This is going to require some explanatory text, perhaps as a footnote, to explain the composer's intention.
Comment: It was customary to skip repeats after a DS or DC in short 18th century dance-style movements.  Perhaps because a student pianist's early musical journey is dominated by such pieces, it became considered more of a 'rule' than it deserves to be.   It was baked into early versions of Sibelius, until it became an option.
Comment: Btw, Lilypond do have winged repeat signs :) It just won't be easy to place both the winged and unwinged ones next to each other. But heck, you might just use the winged one at the beginning of the repeats, as the other ones would be implied...
Comment: I'm sure every competent notation program has winged repeats.  My point was that this benefits from enhanced ones.  Heavy strokes and red ink!
Answer: In this case, especially since your A section is only eight measures long, it's an easy enough thing to just write out the A section a second time without using repeats. (I can think of several examples from Brahms, Schumann, Chopin, and the like where the composer decided to do just that.) This then removes any confusion about where the repeat at the end of C goes to. And remember: the Golden Rule of Notation is to make things as clear as possible to the performers!
I know that's answering your question with a bit of a non-answer, but I thought it was important enough to mention, especially since there is a clear historical precedent.
Comment: Ah, but performers are not compilers.  You have a relationship (through the written medium) with a real-life human being, and that human being is busy enough playing and jamming without using second-degree logic to interpret confusing notation.  (not to say that a nested notation is necessarily confusing... but that firm DRY is probably going to be frustrating eventually.)  Also, you aren't "debugging" your melody--- some of the benefits of DRY are lost in composition.
Comment: For reading, this is certainly the safest option. Unfortunately it violates the [DRY principle](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)... annoying when you've written out everything multiple times and then want to change something – even a digital score can't easily be tackled with regular expressions. —

In e.g. Lilypond, I would always write material only once and just bind it twice in the rendered parts.
Comment: @elliotsvensson And when creating the sheet, you can use clever programs to unfold a repeat for you. Heck, LilyPond even has a command for that, including the way to include different alternatives at the end of the repeat.
Answer: Write the following:

(segno sign) [: A :] B C (D.S. con rep.)

I would never use nested repeats. Better use this sort of navigation aids. The segno sign is traditional, the other way is to write a big [A] rehearsal mark at the beginning and write Repeat from [A] at the end.
Comment: Note that a DS in some traditions (I have seen it particularily in marches, personally) are automatically assumed to be without repetitions the second time around (although "D.S. senza rep." is common enough). So "D.S. con rep." may be necessary.
Comment: This is the right answer, exactly suited to OP's form.
Comment: @Arthur True; here it would be probably assumed, given it's basically jazz, but it's good to be on the safe side :-)
Answer: I came up with quite a hack to make it work with playback in Musescore.

I did not want the whole jam part repeat, even though the scores says so. I tried setting repeat count to 1, but then it did not continue to bar 75. I also tried adding D.S. and Segno to bypass that, but that did not work either.
However, it did work when I introduced an extra bar after 74 and put the D.S. before the extra added bar. So I just introduced the D.S. and Segno and made them invisible as can be seen. I also made the bar line invisible after bar 74.
To get the extra repeat in the beginning I had to introduce an extra bar, which I made only 1/64 long. This is short enough to be barely noticed during playback. If you want to make it even less noticeable, you can temporarily raise the tempo there. The reason I added one extra 1/64 before that was to trick Musescore to make page break work as intended.
If you get confused about these measure counts, I can mention that I used "exclude from measure counts" for these three extra bars.
Comment: I find the D.S. usage incomprehensible, and I'm also not a fan of the 1/64 rest hack.
Comment: @200_success May I ask what the problem is? No one will ever see it. It is a hack to fix the playback.
Comment: Is this question about [tag:notation] or about how to use MuseScore? Are those gray rests and noteheads invisible when printed? If so, then this isn't an answer to the notation question.
Comment: @200_success I know. I realized that when people already had started answering the question, and I did not want to edit the question then because that would have invalidated the existing answers.
Comment: To clarify: the AABC-form "Jam" section should be repeated in performance (AABC AABC ...), but played only once when playing back within MuseScore. Yes?
Comment: @Aaron Yes, that's correct
Answer: Clarity and readability are more important than cleverness and compactness.
There are plenty of pieces where the repetitive flow is not notated using any special tricks.  A few examples come to mind:

Maurice Ravel's Boléro.  The theme occurs 18 times, but varying slightly each time.
Frédéric Chopin's Nocturne in A♭ Major, Op. 32 No. 2.  A very long section is repeated, one semitone higher.  There's no standard repeat notation to accommodate that.
Edvard Grieg's Bryllupsdag på Troldhaugen, in A-B-A-Coda form.  Everything is written out, except for a short repeat within section B, even though the composer could have chosen to write it using a D.C. al Coda.

Your section A is just 8 measures, so don't bother using any fancy notation to indicate that it should be played twice.  It's much easier on everyone to copy and paste those 8 measures.
Once the nested repeat is eliminated, then it's a matter of notating the indefinite repeat.  You'll just have to write a footnote to indicate that it should be repeated at the conductor's discretion.


HP P420i SSD RAID Configuration

Question: I've been testing a HP DL380p with 16x SSDs in a RAID5 on the P420i controller with 2GB FBWC that is integrated on the board. Quite good performance, but not good enough.
When I simulate the IO footprint I expect on ESXi, the Average Device Latency goes through the roof - 150 ms. What could cause this?

Could the RAID controller be limiting the performance? If so, should I buy a second one?
Would it be a good idea to swap to RAID 10 instead? For lower write penalty.
Answer: 16 disks (especially SSDs) in RAID5 is a bad idea... The HP P420i Smart Array controller would have warned you about this when you created the Logical Drive.
There's some finesse needed to tuning the server you're describing. Can you provide specifics on the SSDs you're using, the current controller settings, the host's firmware levels and your testing methodology?
Also, what type of performance are you expecting versus what you're experiencing?
Comment: Yes, it did, in fact - telling me that best practice for RAID5 includes a maximum of 14 disks, I think. But that's more an issue of safety, I suppose?

I use Samsung EVO 500 GB for the drives. This has worked great for me in the past with fewer disks, though.
P420i firmware version 5.42.

No specific settings other then defaults. I would like to mention that SSD SmartPath is enabled.
Comment: @AndersN You haven't stated or helped quantify your problem. What is the actual issue?
Answer: By default, the SmartArray disables the disk's private DRAM cache, significantly lowering SSDs performance.
You can try to reenable it, but you had to be sure (by mean of testing) that this will not led to data corruption in case of power loss.
Answer: 16 disks in a RAID5 is really bad.  And you surely got a warning that you were above 14 disks when you created it?  You are using SSDs to get speed, why nullify this in some way by using a RAID5? You need space, buy bigger disks? Too expansive, maybe it is time to review your needs and solution.  Use RAID10 (8 pairs of RAID1 SSDs) to stay safe and be the fastest you could possible be with 16 SDDs.
Why is it bad to go over 14 disk in a RAID5 is because when one disk will fail (eventually), the rebuilding that will occur will be terrible. On regular HDDs, you are almost certain to fail another disk while the rebuild occurs and thus losing the entire array. With SSD, you're 'aging' faster and getting them nearer to their UBER (Unrecoverable Bit Error Read) and your array will simply crash there too.

HP P420i SSD RAID Configuration


Eigen: Comparing each element of vector with constant

Question: is there a way how to compare each element of a vector with a constant? So far, I am comparing 2D vector Eigen::Vector2d with a constant double tolerance like this:
    if (x(0) > tolerance && x(1) > tolerance)
    {
     ...
    }

I have found the function isApprox() but it did not worked somehow. Is there is a nicer or recommended way on how to do it?
Comment: Please provide [mcve] you can start with this: https://godbolt.org/z/K91zEGh6q
Comment: Does this help? https://stackoverflow.com/questions/50009258/how-to-do-element-wise-comparison-with-eigen
Comment: After last edit it smells like [XY problem](http://mywiki.wooledge.org/XyProblem). Please [edit] your question and start from explaining what you are calculating and why you think your approach of comparing each element to constant  is good approach.
Answer: One way to do this is to use the array method of the Vector class.  Like this:
#include <Eigen/Dense>
#include <iostream>

int main(int argc, char * argv[]) {
    Eigen::Vector2d A{ 7.5, 8.2 };
    std::cout << A << '\n';
    auto res = A.array() >= 8.0;
    std::cout << res << '\n';
    if (res.all()) {
        std::cout << "True" << '\n';
    }
    else {
        std::cout << "False" << '\n';
    }

    A(0) = 10.2;
    auto res2 = A.array() >= 8.0;
    std::cout << res2 << '\n';
    if (res2.all()) {
        std::cout << "True" << '\n';
    }
    else {
        std::cout << "False" << '\n';
    }

    return 0;
}

In this case res and res2 are CwiseBinaryOp which contains booleans for each element in A.  Use all to find when both are True.
Comment: improved version https://godbolt.org/z/xsTxGzPsM
Comment: @MarekR Thanks for the suggestions, there are many ways to improve this further.  You can turn it into a one liner with `if ((A.array() > 8.0).all()) { ...`
Answer: I feel like a good call on this one is to write a simple function:
bool is_componentwise_greater_than(
    Eigen::Ref<Eigen::VectorXd const> const &vector, double lower_bound) {
  for (auto value : vector) {
    if (value <= lower_bound)
      return false;
  }
  return true;
}

The drawback of this way compared to the solution by @Matt is, that for more complicated use cases, using an Eigen expression can be more performant (no idea, if this applies here).
The (in my opinion huge) advantage of such an solution is, that you
can see exactly what it does from its usage.
Of course you can also pack Matts solution in an aptly named function to get this advantage. Another advantage is, that with the function I provided you know exactly what it does and never have to wonder, whether using auto with an Eigen type could bite you. I guess it won't and Matt probably knows exactly why. But I (and you?) do not and therefore wouldn't want to rely on it.


How to put values over bars in barplot in R

Question: This question is related to my previous question. I would like to put values over bars in barplot. I am beginner in plotting in R.
Answer: To add text to a plot, just use the text command. From @chl's answer to your previous question:
##Create data
x = replicate(2, sample(letters[1:2], 100, rep=T))
apply(x, 2, table)

##Create plot
barplot(matrix(c(5, 3, 8, 9), nr=2), beside=TRUE,
        col=c("aquamarine3", "coral"),
        names.arg=LETTERS[1:2],
        ylim=range(0,12)))

##Add text at coordinates: x=2, y=6
##Use trial and error to place them
text(2, 6, "A label")
text(5, 10, "Another label")

Comment: I don't really understand why this option was added to `hist()` (`labels=T`) and not `barplot()`.
Answer: Another example of the use of text command
u <- c(3.2,6.6,11.7,16.3,16.6,15.4,14.6,12.7,11.4,10.2,9.8,9.1,9.1,9.0,8.8,8.4,7.7)
p <-c(3737,3761,3784,3802,3825,3839,3850,3862,3878,3890,3901,3909,3918,3926,3935,3948)
     -c(385,394,401,409,422,430,434,437,437,435,436,437,439,442,447,452)
e <- c(2504,2375,2206,2071,2054,2099,2127,2170,2222,2296,2335,2367,2372,2365,2365,2401)

par(mar=c(2,3,1,2),las=1,mgp=c(2.2,1,0))
x <- barplot(u,names.arg=1990:2006,col="palegreen4",space=.3,ylim=c(0,20),
              ylab="%",xaxs="r",xlim=c(.8,21.6))
text(x,u+.4,format(u,T))
lines(x[-17],100*e/p-55,lwd=2)
points(x[-17],100*e/p-55,lwd=2,cex=1.5,pch=1)
axis(4,seq(0,20,5),seq(55,75,5))
text(c(x[1]+1,x[5],x[16]+1),c(100*e/p-55)[c(1,5,16)]+c(0,-1,0),
      format(c(100*e/p)[c(1,5,16)],T,di=3))
box()

Comment: (+1) This is the hard way :) I like it.
Answer: If you're learning to plot in R you might look at the R graph gallery (original here).
All the graphs there are posted with the code used to build them. Its a good resource.


Baker–Campbell–Hausdorff formula for [exp(x),exp(y)]

Question: Can someone provide a explicit (the first priority with leading orders, then the secondary consider as complete as possible, or) expansion like Baker–Campbell–Hausdorff formula for the commutator:
$$[\exp(x),\exp(y)]=?$$
where the commutator $[x,y]\neq 0$.
I am expecting an answer in terms of $[x,y]$ and its commutator with $x$ and $y$ and go on: $[x,[x,y]]$, $[y,[x,y]]$, etc....
Thanks for reply.
Comment: sure, $[exp(x),exp(y)]=exp(x)exp(y)-exp(y)exp(x)$. But, I'm guessing you want an expansion in $x,y$.
Comment: I am expecting an answer in terms of $[x,y]$ and its commutator with $x$ and $y$ and go on: $[x,[x,y]]$, $[y,[x,y]]$. Thanks for reply.
Comment: Hi again, I forgot about this question when I came upon http://math.stackexchange.com/q/711308/36530 but, it seems to me, there may be a way of using the technique there to help out here, or at a minimum it's worth looking at.
Comment: You did not say why  you expect an answer in the Lie algebra (nested commutators). The commutator you are considering need not be in the group. The answer will only be in the universal Lie Algebra, by the looks of it.
Comment: When considering small perturbations, check out "Lyndon basis".
Answer: The set of x, y and their nested commutators comprise a Lie algebra. A product of group elements, $\exp x ~ \exp y$ is in the group, ($\exp x ~ \exp y =\exp z $), so its logarithm is in the Lie algebra: $z(x,y)$ is the CBH expansion, so linear combs of x, y and nested commutators.
Note the important symmetry $z(y,x)=-z(-x,-y)$.
However, the commutator of two group elements, such as the one you are interested in, is, in general, not in the group. It is in the universal Lie algebra, so not just nested commutators. In fact, expanding expz to cubic order, and discarding the x-y symmetric terms, by virtue of the above identity,  you readily get, to cubic order in x and y ,
$$
\exp z(x,y) -\exp z(y,x) = [x,y] + \tfrac{1}{2}\{ (x+y),[x,y]\}+...
$$
which is not reducible to nested commutators--it is not in the Lie algebra. The { } bracket is the anticommutator; note how cleverly the surviving cross term upgrades the antisymmetry of one of its constituent components to yield the cubic term.
Answer: Ok, so $exp(x)exp(y) = exp(x+y+ \frac{1}{2}[x,y] +\cdots )$ and $exp(y)exp(x) = exp(y+x+ \frac{1}{2}[y,x] +\cdots )$. Therefore, using $[y,x]=-[x,y]$,
$$ [exp(x),exp(y)] =  exp(x+y+ \frac{1}{2}[x,y] +\cdots ) - exp(x+y- \frac{1}{2}[x,y] +\cdots )$$
then,
$$ [exp(x),exp(y)] =  [x,y] +\cdots. $$
The answer would seem to fall out of the BCH relation for higher orders if you want higher orders.
An outline of how to continue: use BCH to expand as: (the right equality is meant to indicate $A$ is the terms in the argument of the exponential)
$$ exp(x)exp(y) = exp(x+y+\frac{1}{2}[x,y]+\frac{1}{12}[x,[x,y]]-\frac{1}{12}[y,[y,x]] + \cdots ) =exp(A)$$
Likewise
$$ exp(y)exp(x) = exp(x+y+\frac{1}{2}[y,x]+\frac{1}{12}[y,[y,x]]-\frac{1}{12}[x,[x,y]] + \cdots ) $$
Note, (the right equality is meant to indicate $B$ is the terms in the argument of the exponential)
$$ exp(y)exp(x) = exp(x+y-\frac{1}{2}[x,y]-\frac{1}{12}[x,[x,y]] + \frac{1}{12}[y,[y,x]]\cdots ) = exp(B) $$
We would like to simplify the quantity $exp(A)-exp(B)$ order by order in $x,y$. Recall $exp(A) = 1+A+\frac{1}{2}A^2 + \cdots$ and $exp(B) = 1+B+\frac{1}{2}B^2 + \cdots$. Clearly the constant and first order terms in $x,y$ cancel. I think at second order everything cancels except $[x,y]$. At third order, I'm not sure without a lot more calculation, however, I hope the path is partly clear now, granted it is tedious. There is probably a better way. Perhaps a program of successive differentiation and evaluation.
Comment: I liked to know higher order terms to the third order.
Comment: And whether there is an analytic expression for the coefficients for n-th order.
Comment: well, I'm still thinking about my answer as it stands, have I missed other second order terms from $(x+y+\frac{1}{2}[x,y])^2$ or do they all cancel against the $(x+y-\frac{1}{2}[x,y])^2$ as I implicitly claim?
Comment: I give you credit first +1, but please fill in a more satisfactory answer ASAP, which hopefully reveals more structure than I already knew...
Comment: http://en.wikipedia.org/wiki/Baker%E2%80%93Campbell%E2%80%93Hausdorff_formula gives the next terms with $1/12$. However, I need to sit and calculate a bit before I'm sure it is my knee-jerk conjecture of $\frac{1}{6}([x,[x,y]]-[y,[x,y]])$.


Executar aplicação através de serviço delphi com direitos de administrador

Question: Necessito executar uma aplicação através de serviço em delphi com direitos elevados de administrador.
Já tentei várias soluções encontradas aqui, tais como
RunAsAdminAndWaitForCompletion(filename,
  Parameters: string; wait: boolean): Boolean;

Contudo a aplicação quando é executada pelo serviço, fica sem direitos de administrador.
Uma simples impressão pela aplicação que foi chamada não é executada, porque a aplicação chamada fica sem acesso aos periféricos. Como é que posso fazer para que a aplicação que for executada através do serviço, seja executada com privilégios de administrador sobre a máquina.
O usuário que encontra-se logado na máquina já é administrador.
Answer: Cara, eu tava dando uma pesquisada rápida e encontrei isso aqui:
uses ShellApi;

ShellExecute(Handle, 'runas', 'regedit', nil, nil, SW_SHOWNORMAL);

Eu testei aqui no Delphi XE5 com um aplicação comum e funcionou certinho (coloquei um botão no form e no click dele eu coloquei esse comando), você pode ver que o comando que eu estou chamando é o Regedit e esse carinha só é aberto com permissão de admin.
Da um testada aí no seu caso pra ver se resolve seu problema, qualquer coisa comenta aí que a gente vai se falando.
Abraço.
Comment: Eu usei o Delphi XE5 em um projeto VCL - Forms Application, não sei qual é a versão do Delphi que você está usando aí.


Auto close Youtube Video when it's ended on an iPod Touch/iPhone

Question: I'm currently doing a mobile website. I have embedded Youtube videos in it.
Thing is, when you open a youtube video in an iPod, it does its thing where it goes full screen, and at the end you must manually close the video to continue browsing.
I was wondering if there is a command to auto-close the fullscreen on the end of the youtube video.
Answer: I don't know what code are you using but I saw this a while ago:
<code><object width="425" height="344" type="application/x-shockwave-flash" data="http://www.youtube.com/watch?v=hoA1MBRJ_BA&hl=de&fs=1&rel=0"><param name="movie"  value="http://www.youtube.com/watch?v=hoA1MBRJ_BA&hl=de&fs=1&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param></object>
</code>
That is supposed to work flawlessly, source:
Embedding youtube video in webpage for both desktop and iphone/ipad
Comment: I tried that code, and the video just didn't show up anymore... Well it looked promising thanks!
I use the new embed code BTW. My theory is that the ipod is doing his own stuff with the video, so I cant reach it.
Thanks anyway.


Redirect a wix website page to external URL

Question: I'm trying to create a wix page which will redirect all users that link to it to an external URL.
I tried adding the code below as a "html wix app" but it didn't worked.
<meta http-equiv="refresh" content="0; URL=http://www.my-new-url.com">

Answer: I had a similar use case and solved it using the wix-location module:
import wixLocation from 'wix-location';

$w.onReady(function () {
     wixLocation.to("http://www.my-new-url.com");
})

Comment: Great ,  this is works fine .It is based on the wixcode API . How to use it : open the page you`re editing . click on the code panel and paste the code .Just like that and publish it. Everything works as expected .
Comment: @optimus203 no , it doesnt yield 301 status code -  since its client-side redirection
Comment: any way to make a 301 redirect?
Comment: @DaggieBlanqx - does this method yield a 301 status code, or something different?
Comment: This waits for the page to load fully and then does a redirection. Is there a way to redirect without waiting for the whole page to load?
Comment: You can make a 301 redirect according to the support article here: https://support.wix.com/en/article/setting-up-a-301-redirect-for-a-page-on-your-site
Answer: When you insert an HTML "module" into Wix, it is actually inserted into an iframe on the page rather than the page itself.
Fortunately, the iframe is hosted at the same domain, so you don't have to deal with cross-domain issues. Therefore, this code, when inserted into an HTML module on a Wix page, successfully redirects the parent:

Comment: Unfortunately this didn't work even though it seems to make sense. What should I do?
Comment: @IchHabsDrauf It is currently working for me on a live site: http://www.baseballforall.com.
Comment: wow, love this site even though I don't know if you made it by yourself or using Wix. When I try your code into my Wix site it get's disabled for some reason. I don't have premium
Answer: You can use wix-location from Wix Code, for this. An example of using it to navigate to an external URL is:
import wixLocation from 'wix-location';

// ...

wixLocation.to("http://www.my-new-url.com");

Answer: Maybe try:
<meta http-equiv="refresh" content="0; URL=http://www.my-new-url.com/" />

You left out a " at the end.
I hope this helps!
Try:

Try this:

<meta http-equiv="refresh" content="0; URL=http://www.my-new-url.com/" />

Comment: chrome. What code exactly did you added to the wix html app? Did it redirected you to the the external link or just opened it in a frame ?
Comment: It just opens it in a frame inside the page. I want the page to be redirected to the given URL.

BTW, I'm trying to redirect it to a Google Play URL.
Comment: Do you want it to open the playstore app or...?
Comment: No. Just a Play Store link
eg. https://play.google.com/store/apps/details?id=com.whatsapp
Comment: Is it on mobile or pc?
Comment: Your new edit is not working for https://play.google.com/store/apps/details?id=com.whatsapp
Answer: The above code:

works on my wix site:
https://www.lemon-sin.com.au/
redirects to director's linkedin account


Python how to partially consume an iterable generator (without `next`)?

Question: I have a class acting as an iterable generator (as per Best way to receive the 'return' value from a python generator) and I want to consume it partially with for loops.
I can't use next (like Python -- consuming one generator inside various consumers) because the first partial consumption uses a library that only takes iterators. How can I continue using the generator starting from where the library function left off?
(Related: Pause Python Generator, Is there a way to 'pause' or partially consume a generator in Python, then resume consumption later where left off?)
class gen(): # https://stackoverflow.com/q/34073370
    def __iter__(self):
        for i in range(20):
            yield i

# I want to partially consume in the first loop and finish in the second
my_gen_2 = gen()
for i in my_gen_2:  # imagine this is the internal implementation of the library function
    print(i)
    if i > 10:      # the real break condition is when iterfzf recieves user input
        break

for i in my_gen_2:  # i'd like to process the remaining elements instead of starting over
    print('p2', i)

# the confusion boils down to this
my_gen = gen()
for i in my_gen:
    print(i)    # prints 1 through 20 as expected
for i in my_gen:
    print('part two', i)    # prints something, even though the generator should have been "consumed"?

Answer: Every time you iterable generator  in a loop, you get a new iterator.
For example:
class gen(): # https://stackoverflow.com/q/34073370
    def __init__(self):
        self.count = 0
    def __iter__(self):
        self.count += 1
        print("Hallo iter {0}".format(self.count))
        yield self.count

my_gen = gen()
>>> for i in my_gen:
...    pass
Hallo iter 1
>>> for i in my_gen:
...    pass
Hallo iter 2

If you want to use the old iterator, just work with gen().__iter__()
>>> my_gen = gen().__iter__()
>>> for i in my_gen:
...    pass
Hallo iter 1
>>> for i in my_gen:
...    pass

Comment: Oh haha I should have seen that. How would you recommend implementing this then?
Answer: As @napuzba pointed out, __iter__ returns a whole new generator every time it is used. Instead, store the state in self:
class gen():
    def __init__(self):
        self.count = 0
    def __iter__(self):
        while self.count < 20:
            self.count += 1
            yield self.count


Linear Regression Computation as $y = ax$

Question: I got a process which can be modelised as a Linear Regression matching an $y = ax$ equation.
I can find on the internet computations to match an $y = ax +b$ equation like this
$$
b = \frac{\sum y\sum x^{2}- \sum x\sum xy}{n(\sum x^{2})-(\sum x)^{2}}
$$
$$
a = \frac{n(\sum xy)- \sum x\sum y}{n(\sum x^{2})-(\sum x)^{2}}
$$
But I can't find any formula to match an $y = ax$ equation, any idea?
As a complement , the $\mathbb{R}^2$ is nice to evaluate consistency of the regression but what would be the best way to find the Linear equations which encompass all the set of datas (the minimal and maximal expectation) ?
Answer: It's not very difficult to derive these equations. I'll start with the original equation.
So we have a set of points, $(x,y)_i$ and we want to pair it up with a function $y_{\text{predicted}}=ax_i +b$. The coefficients $a$ and $b$ are chosen so that the error
$$
E = \sum_i (y_{\text{predicted},i}-y_i)^2 = \sum_i (ax_i +b-y_i)^2
$$
is minimised. Note that now $E$ is only a function of $a$ and $b$, $E=E(a,b)$. Opening the parentheses, we get
$$
\begin{split}
E &= \sum_i (ax_i +b-y_i)^2 \\ &= \sum_i \left[a^2 x_i ^2 + 2abx_i + b^2 - 2ax_i y_i - 2by_i + y_i^2 \right]\\
&=a^2 \sum x_i ^2 + 2ab\sum x_i + nb^2 - 2a\sum x_i y_i - 2b \sum y_i + \sum y_i^2
\end{split}
$$
where $n$ is the number of points. In order to minimise this, we set the partial derivatives to zero:
$$
\frac{\partial E}{\partial a} = 2a \sum x_i ^2 + 2b\sum x_i- 2\sum x_i y_i =0
$$
$$
\frac{\partial E}{\partial b} = 2a\sum x_i + 2nb - 2 \sum y_i =0
$$
So now you have the pair of equations
$$
\left\{
\begin{array}{lll}
a \sum x_i ^2 &+ b\sum x_i &= \sum x_i y_i \\
a\sum x_i &+ nb  &= \sum y_i \\
\end{array}
\right.
\qquad \text{or}\qquad
\left[
\begin{array}{cc}
\sum x_i ^2 & \sum x_i \\
\sum x_i & n
\end{array}
\right]
\left[
\begin{array}{c}
a \\b
\end{array}
\right]
=
\left[
\begin{array}{c}
\sum x_i y_i \\
\sum y_i
\end{array}
\right]
$$
Taking the matrix inverse (easy for a $2\times 2$ matrix) gives you the set of equations that you wrote in the beginning. So now you have the idea of how to derive these equations.
Now we can approach your actual question. We only need to set $b=0$ in the expression for $E$, resulting in
$$
E= a^2 \sum x_i ^2 - 2a\sum x_i y_i + \sum y_i^2
$$
Again, we set the partial derivative to zero:
$$
\frac{\partial E}{\partial a} = 2a \sum x_i ^2 - 2\sum x_i y_i =0
$$
Resulting in the simple expression for $a$:
$$
a  =\frac{ \sum x_i y_i }{  \sum x_i ^2 }
$$
Comment: Perfect ! Thank you so much
Answer: An alternative and simpler method (without differential calculus).
A regression line $y=ax$ must be fit to the data $(x_i,y_i)$. Write it in the matrix form:
$$\begin{pmatrix}y_1\\ y_2\\ \vdots\\ y_n\end{pmatrix}=\begin{pmatrix}x_1\\x_2\\ \vdots\\ x_n\end{pmatrix}\cdot a \Rightarrow \\
Y=Xa \Rightarrow \\
X^TY=X^TXa\Rightarrow \\
(X^TX)^{-1}X^TY=(X^TX)^{-1}(X^TX)a \Rightarrow \\
a=(X^TX)^{-1}X^TY=(\sum x_i^2)^{-1}(\sum x_iy_i)=\frac{\sum x_iy_i}{\sum x_i^2}.$$
Note: Similary, the slope and intercept formula for $y=ax+b$ can be derived.
Comment: Why can't we immediately multiply both sides by $X^{-1}$, so $Y = Xa \implies X^{-1}Y = X^{-1}Xa \implies a = X^{-1}Y$?


How to create RSS feed for particular content type in drupal 8?

Question: I have to create the RSS feed for particular content type and found some module and try to generate some RSS feed but I won't. If you have any idea or if anyone did this Please share with me.
Comment: http://getlevelten.com/blog/kristin-brinner/how-display-rss-feed-drupal-block
Comment: Thanks for your response. I already try this module but it won't work for me and I created RSS using view
Answer: Can create the views as well for generate the rss feed with following steps:

Enable Serializer and RESTful Web Services module, available in Drupal 8 core.
Create views for retrieving the contents of required content type.
Select the option Provide a REST export, present in the REST export settings (present at the bottom of views).
Configure the views as per the requirement.

Example:
Comment: I didn't enable any module actually. Simply I add the feed to view its work fine. Thanks for share your knowledge.
Comment: When following these instructions I get a "Undefined root element: response" error


Proof that measure space is complete

Question: This exercise is from Achim Klenke - "Probability Theory".
Let $\Omega$ be an uncountably infinite set and let $\omega_0\in\Omega$ be an arbitrary element. Let $\mathcal{A}=\sigma (\{w\}\colon \omega \in\Omega \setminus \{\omega_0\})$. Show that $(\Omega, \mathcal{A}, \delta_{\omega_0})$ is a complete measure space.
First a characterization of $\mathcal{A}$ has to be given analogue to the following $\sigma$-algebra: $\mathcal{A}' = \sigma (\{w\}\colon \omega \in\Omega)=\{A\subset \Omega\colon A\text{ is countable or }A^c\text{ is countable}\}$
I tried the obvious
$\mathcal{A} = \sigma (\{w\}\colon \omega \in\Omega\setminus \{\omega_0\})=\{A\subset \Omega\setminus \{\omega_0\}\colon A\text{ is countable or }A^c\text{ is countable}\}$
and could finish proving the equation if I could somehow prove that $\omega_0$ can only be in a non-finite set of $\sigma (\{w\}\colon \omega \in\Omega\setminus \{\omega_0\})$.
I am not sure if this is correct, am I on the right track?
Comment: @GabrielRomon I want to take my time to read it and since I am busy, this might take a few more days before I can do it. But I have not forgotten! Thanks for your answer, I will respond asap.
Comment: Any reaction to my answer ?
Comment: For the benefit of future visitors, this question is very similar to https://math.stackexchange.com/questions/2359142/proving-completeness-of-sigma-algebra.
Answer: Let us prove that $$\sigma(\{w\}/ w\neq w_0) = \{A\subset \Omega,   (w_0\in A \implies A^c \text{ is countable}) \text{ and } (w_0\notin A \implies A \text{ is countable})\}$$
Let $\mathcal A = \{A\subset \Omega,   (w_0\in A \implies A^c \text{ is countable}) \text{ and } (w_0\notin A \implies A \text{ is countable})\}$ and $\mathcal C=\sigma(\{w\}/ w\neq w_0)$.
Consider $A\in \mathcal A$.
If $w_0\in A$, then  $A^c=\bigcup_{w\in A^c} \{w\}$ is a countable union of elements of $\mathcal C$ (because $w_0\notin A^c$). Since $\mathcal C$ is a $\sigma$-algebra, this implies $A^c\in \mathcal C$, hence $A\in \mathcal C$.
If $w_0\notin A$, then $A=\bigcup_{w\in A} \{w\}$ is a countable union of elements of $\mathcal C$ (because $w_0\notin A$). Hence $A\in \mathcal C$.
This implies $\mathcal A \subset \mathcal C$.
To prove $\mathcal C \subset \mathcal A$, it suffices to show that $\mathcal A$ is a $\sigma$-algebra containing all the $\{w\}$ for $w\neq w_0$.
$\bullet$ If $w\neq w_0$, $\{w\}$ is countable, hence $\{w\}\in \mathcal A$.
$\bullet$ $\mathcal A$ is stable under complement. Consider $A\in \mathcal A$. If $w_0\in A$, then $A^c$ is countable and $w_0\notin A^c$, hence $A^c\in \mathcal A$. If $w_0\notin A$, then $w_0\in A^c$ and $(A^c)^c=A$ is countable, hence $A^c\in \mathcal A$.
$\bullet$ $\mathcal A$ is stable under countable union. Consider $(A_i)\in \mathcal A^{\mathbb N}$.
If no $A_i$ contains $w_0$, $w_0\notin \cup_i A_i$ and all the $A_i$ are countable, so $\cup_i A_i$ is countable. Hence  $\cup_i A_i\in \mathcal A$.
If WLOG $w_0\in A_1$, $w_0\in \cup_i A_i$. Note that $A_1^c$ is countable and $(\cup_i A_i)^c = \cap_i A_i^c\subset A_1^c$ is countable. Hence  $\cup_i A_i\in \mathcal A$.

The rest of the exercise if simple. Let $A\in \mathcal A$ be a $\delta_{w_0}$-null set. Then $w_0\notin A$. Given the previous characterization, $A$ is countable.
If $B\subset A$, then $w_0\notin B$ and $B$ is countable, hence $B\in \mathcal A$.
So all subsets of $\delta_{w_0}$-null sets are in $\mathcal A$, so the measure space is complete.
Comment: For the proof that $\mathcal{A}$ is a $\sigma$-algebra, why the emphasis on "containing all the $\{\omega\}$ for $\omega\ne \omega_0$"? This property follows immediately if we can show that $\mathcal{A}$ is a $\sigma$-algebra. What would be missing is to show that $\Omega\in\mathcal{A}$, but this follows since $\omega_0\in\Omega$ and $\Omega^C=\emptyset$. Am I missing something?
Comment: @EpsilonDelta In general, if $\mathcal A$ is a $\sigma$-algebra and $\mathcal F$ is a collection of sets, $\sigma(\mathcal F)\subset \mathcal A$ if and only if $\mathcal A$ is a sigma-algebra that contains $\mathcal F$. So what I wanted to show is that $\mathcal A$ is a sigma-algebra **and** that it contains all the $\{w\}$. Does that make more sense ? You're right about adding that $\Omega \in \mathcal A$ needs to be verified as well.
Comment: This is not necessary. We (you) have already shown that $\mathcal{A}\subset\mathcal{C}$ and hence for having $\mathcal{C}\subset\mathcal{A}$ it is enough to show that $\mathcal{A}$ is a $\sigma$-algebra. It will follow from this statement, that the $\{\omega\}$ are in $\mathcal{A}$ follows immediately. So no need to explicitly show that $\{\omega\}$ are in $\mathcal{A}$.
Comment: @EpsilonDelta Sorry, I don't get it. Can you explain why $\mathcal A \subset \mathcal C$ and $\mathcal A$ is a sigma-algebra directly implies that $\mathcal A$ contains all singletons except $\{w_0\}$ ?
Comment: If we have $\mathcal{A}=\mathcal{C}$ then we know that if $\omega_0$ were in a set $A$, it must follow that $A^c$ is countable, which implies that $A$ must be uncountable. Thus, no singleton $\{\omega_0\}$ can exist.
Answer: The characterisation
$\mathcal{A} =\{A\subset \Omega\setminus \{\omega_0\}\colon A\text{ is countable or }A^c\text{ is countable}\}$
isn't quite correct. Hint: Keep in mind that $ \sigma- $algebras are closed under complement.
Here is why the characterisation fails:

 Claim: $\mathcal{A}$ contains sets which contain $ \omega_0 $ while $\{A\subset \Omega\setminus \{\omega_0\}\colon A\text{ is countable or }A^c\text{ is countable}\}$ does not.
Proof: Since $ \mathcal{A} $ is a $ \sigma-$algebra, it is closed under complement (i.e. $ A \in \mathcal{A} $ implies $ A^C \in \mathcal{A} $). Now take any $ \omega \neq \omega_0 $. Then $ \{\omega\} \in \mathcal{A} $ (by definition of $ \mathcal{A} $) thus also $ \Omega\setminus\{\omega\} \in \mathcal{A}$. But $ \omega_0 \in \Omega\setminus \{\omega\} $.

A better description of $ \mathcal{A} $:

 $\mathcal{A} = \{ A \subset \Omega : (A \text{ is countable and }\omega_0 \notin A )\text{ or }( A^C \text{ is countable and } \omega_0 \in A)\}$.
Comment: 30 seconds apart lol
Comment: But you we're faster! And even typed out a complete solution
Comment: According to your last line: If $\omega_0\in B\subset \Omega$, there exist  uncountable subsets  $A_1,\,A_2$ of $\Omega$ such that $A_1\cap A_2=B. $  So if $\mathcal A$ is a $\sigma$-algebra then $B\in \mathcal A$ and $\Omega \setminus B\in  \mathcal A.$  So $\mathcal A$ contains every subset of $\Omega.$ This is incorrect. If $\omega_0\in A\subset \Omega$ and  $A$ is uncountable then for $A\in \mathcal A$ it is also necessary that $\Omega \setminus A$ is countable.
Comment: Thanks for pointing it out, it should be correct now.
Comment: @DavidH Your characterization is a bit clearer than the one of Gabriel. Also, good quick and easy demonstration that my previous characterization was wrong! Good Job!

Proof that measure space is complete


Sempre manter o mesmo nome de um arquivo PDF no upload

Question: Como posso manter o mesmo nome de um arquivo no momento do upload, por exemplo se a pessoa escolher um arquivo com o nome planilha.pdf eu possa sempre grava-lo com um nome fixo, como documento.pdf, hoje faço isso no meu script:
$arquivo = $_FILES["arquivo_pdf"];
$arquivo_nome = $arquivo["name"];

// Move o arquivo para o diretório especificado
set_time_limit(0);
$diretorio = "../diretorio/";
$arquivo_temporario = $_FILES['arquivo_pdf']["tmp_name"];
move_uploaded_file($arquivo_temporario, $diretorio.$arquivo_nome);

Sendo $arquivo_nome é o que pretendo sempre deixar com o mesmo nome.
Answer: Muito simples. Basta você definir $arquivo_nome como documento.pdf.
$arquivo = $_FILES["arquivo_pdf"];
$arquivo_nome = 'documento.pdf';

// Move o arquivo para o diretório especificado
set_time_limit(0);
$diretorio = "../diretorio/";
$arquivo_temporario = $_FILES['arquivo_pdf']["tmp_name"];
move_uploaded_file($arquivo_temporario, $diretorio.$arquivo_nome);

Comment: Obrigado pela ajuda @gpupo, valeu mesmo.


Canonical link for multidomain multisite

Question: I have different domains in a site in Drupal 7, which is multidomain and multilanguage, using modules Domain Access and i18n. I have duplicate content in some URLs accross domains, and I want to avoid Google penalization by following the recommendations of using
<link rel="canonical" href="CANONICAL_SOURCE_URL" />

I will use a custom module. For the nature of Drupal 7, I undestand that I can check each node, and using the node->id and database call, to check the domains in which the node is active. Following an order of preferred domains, I will know that URL to set as the canonical.
Is that a good aproach? I have tried module MetaTag with Canonical, but it uses a wildcard approach so it repeats the domain in which I am, so we can have www.example.com/link1 and www.example.us/link1 as canonicals, when only one of them should be used.
How can I override MetaTag with my own link rel tag ?
Comment: Maybe it is better to use Metatag module?
Comment: I added a clarification on my answer.
Answer: It is better to use Metatag module which has ability to override meta tags on each entity objects. Other tokens must be used.
Comment: Please read the question about using MetaTag with Canonical, and the wildcard approach problem. If you know how to override it, I could do it directly with no need of my own module.
Comment: You downvoted my response but it is the right one. I've already done this on my two domains. In this case I suppose that it is better to use MetaTag module and yes, it is possible to use ONLY ONE DOMAIN for both ones in the automated way, you have to choose the right tokens
Comment: Edit your answer and I will vote you positive. I will try your approach later.
Comment: I edited the answer.
Comment: I have been unable to making your approach work. Perhaps due to a different configuration. I voted you up to compensate, my first action was not strange, I mentioned a module not working for me and you insisted on the same module. I rectified my first decision and apologize.
Comment: You can download the latest version and choose the right tokens without domain and add it manually. It must work. It works on my two domains when I see the canonical link on one of them and I don't see it on another.
Comment: By the way, my response stays downvoted.
Comment: Please, refresh to see if it is updated now.
Comment: Thank you, it worked. If you have any questions or if you need some clarifications, you are welcome.


What's the best way to parse a map in clojure when using clj.http?

Question: I have a map like so

(client/post "http://localhost:5000" {:form-params {:new {:title "some-title" :description "some-description"}}})

In the server, I have the following:
(get-in request [:form-params "new"])

Which gives me the following:
"{:title \"some-title\", :description \"some-description\"}"

A string and not an actual map. Using the Cheshire library's parse-string gives the ": unexpected" error. How do I fix this?
Comment: You have not accepted a single answer since Nov '19.  May I be so bold and ask why?
Answer: Add :content-type :application/edn to your request map, to parse EDN.  Add :as :auto, :coerce :always to do the coercion automatically.
Comment: Doing ```(client/post "http://localhost:5000" {:form-params {:new {:title "some-title" :description "some-description"} :content-type :application/edn :as auto :coerce :always}})``` makes the params and form-params disappear when the request comes into the server.


Qual o peso de uma subquery para a consulta?

Question: Durante o desenvolvimento de algumas consultas no banco de dados, me deparo com a situação da necessidade de realizar uma nova consulta, mas outra solução em alguns casos pode ser a subquery.
Então qual é a melhor solução realizar uma segunda consulta ou utilizar subquery em situações assim? Qual o peso de uma subquery para minha consulta? É válido a ponto de não precisar fazer uma nova consulta no banco?
Comment: Depende também da existência de índices, estatíscas atualizadas etc. Em alguns casos o uso de um "outer join" é mais rápido.
Comment: Depende da situação, depende de como a subquery é construída. Não sei se existe alguma ferramenta para análise de estratégia de busca com mysql... De qualquer forma, uma subquery **é** uma nova consulta, e de acordo com a forma que é utilizada, pode gerar uma ou mais consultas ao banco **para cada registro da *query* principal**.
Comment: Em alguns casos uma "desnormalização" pode ajudar , imagine o seguinte cenário cliente x saldo devedor , em tese seria preciso uma subquery ou join para saber isto, mas se uma coluna em cliente for atualizada por triggers o peso desta consulta cai pois basta acessar cliente, a questão é pesar o custo de triggers x custo das consultas.
Comment: Eu tento ao máximo não fazer subquery pelo fator performático e aprendi a fazer SQL otimizadas que trazem o mesmo resultado e mais rápido. Tudo vai depender de como ta o seu banco pra mim sendo o ponto crucial (falta de indices, tabelas sem relacionamentos, bancos sem normalização, etc.).
Comment: A resposta exata você só vai obter dando um `EXPLAIN` na query e analisando o resultado. Depende muito do caso.
Comment: Tudo indexado, na maioria dessas situações o outer join não resolvem a situação, geralmente existe a necessidade da subquery ou segunda query.
Answer: Entre obter o resultado por meio de uma subquery ou realizar uma segunda consulta, a subquery em condições normais será menos custosa por que não redunda a execução dos algoritmos de comunicação entre o client e o server. No entanto, é preciso considerar que para cada linha da consulta principal, a subquery será executada; Portanto, você precisa pesar se de fato faria isoladamente a mesma quantidade de consultas.
O real peso de uma subquery depende dos algoritmos do seu SGDB e da modelagem do seu Banco. Essa é uma resposta impossível de se dar sem analisar a sua estrutura.
Meu conselho final é que, se possível, substitua as subquerys por Joins. Isso sim otimizará a performance e, em minha experiencia, isso quase sempre é possível (e não esqueça dos índices).


Spiral function with constantly increasing separation between its loops

Question: Spirals following the polar equation $r=a+bθ$ are known to have constant separation between each of its loops, I show this by transforming the polar equation into Cartesian equation by using the transformations $r=(x^2+y^2)^{0.5}$ and $ θ=tan^{-1}\left(\frac{y}{x}\right)$. For computing the separation between loops $n$ and $n+1$, I get the following formula
$x_{n+1}-x_{n}=b π [(n+1)-(n)]= b π$
As shown, the separation between the loops is a constant. When I use the equations $r=a+bθ^p$ or $r=a+bp^θ$, and then compute the separation between loops, for instance, $n$ and $n+1$, I get the following results;
$x_{n+1}-x_{n}=b 2π^p [(n+1)^p-(n)^p]$ for $r=a+bθ^p$
$x_{n+1}-x_{n}=b(p^{2π}-1)p^{n 2π }$ for $r=a+bp^θ$
As one would realize, the separation between loops of those two spirals increase, but not with a constant rate. I tried many more formulae, but I didn't get any spiral with constant increase rate between its loops, i.e., stratifying the formula;
$x_{n+1}-x_{n}=An$
Wherein $A$ is a constant. Does anyone here know which equation would give me the spiral shape I'm looking for? Thank you so much guys.
Answer: You can use $r = a + b\left(\left(\frac\theta\pi\right)^2 - \frac\theta\pi\right).$
This way,
$$\begin{equation}
\begin{split}
x_{n+1}-x_{n} &= b\left[\left(\frac{(n+1)\pi}{\pi}\right)^2 - \frac{(n+1)π}{\pi}-\left(\frac{nπ}\pi\right)^2 - \frac{nπ}{\pi} \right] \\
&=b[n^2 + 2n + 1 - n - 1 - n^2 + n] \\
&= b[2n]
\end{split}
\end{equation}$$
I think this was what you were looking for.
Answer: Placing $ \theta $ in position of exponent makes it a log spiral, making geometric progression of radial ray lengths.
Taking
$$ r= r_0 + \dfrac{ p \theta }{2 \pi}$$
we have  $p$ constant as radial increase or pitch for each revolution. It is in arithmetic progression.
Since $$ r =\sqrt {x^2+y^2}$$
$$ \sqrt{x^2+y^2} = \sqrt{x_0^2+y_0^2} + \dfrac{ p \theta }{2 \pi}$$
Setting $y=0$ we must have for x-axis start of Archimedean spiral
$$ x= x_0 + \dfrac{ p \theta }{2 \pi}$$
and setting $x=0$ we must have for y-axis start of the spiral
$$ y= y_0 + \dfrac{ p \theta }{2 \pi}$$
and the same holds good for any radial ray $ \theta = \alpha$.
So $p$ is radial pitch at any arbitrarily chosen $\alpha.$


como usar line-through dentro de um item do array

Question: estou criando uma lista de tarefas e estou tendo dificuldade para mostrar ela como concluída. O único ítem de array que é riscado com a função  line-through é o ultimo e meu objetivo é que todos possam ser marcados conforme seja necessário.
exemplo: 4 entrada e quero marca palavra ceneta e palavra caderno .
agenda
caneta
caderno
Borracha
mas dificuldade que estou tendo e que clico pra marca caderno ele só esta dando efeito da marca na ultima opção no caso exemplo borracha

const ul = document.getElementById("ul");
const input = document.getElementById("entrada");

const tarefas = [];

function validaEntrada() {
  console.log(input.value)
  if (input.value != "") {
    addTarefa();

  } else {
    alert("Digite uma Entrada!!!")
  }
}

function apresentarTarefa() {
  ul.innerHTML = ''

  for (texto of tarefas) {

    var novatarefa = document.createElement('li');
    novatarefa.appendChild(document.createTextNode(texto));
    console.log(novatarefa)

    ul.appendChild(novatarefa);

    const deleteBtn = document.createElement('button')
    const pos = tarefas.indexOf(texto)
    console.log(pos)

    deleteBtn.setAttribute('onclick', `removeTarefa(${pos})`);

    deleteBtn.appendChild(document.createTextNode("X"));
    novatarefa.appendChild(deleteBtn);

  }

  function risco() {
    novatarefa.classList.toggle("feito")
  }

  novatarefa.addEventListener("click", risco);

}

apresentarTarefa()

function addTarefa() {

  var tarefa = input.value;

  tarefas.push(tarefa);

  input.value = ''
  apresentarTarefa()

}

function removeTarefa(pos) {
  tarefas.splice(pos, 1)
  apresentarTarefa()

}
#ul {
  border: 2px solid black;
  list-style-type: none;
  cursor: pointer;
}

body {
  display: flex;
  width: 50vw;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
  gap: 15px;
}

.feito {
  text-decoration: line-through;
}

.cabecalho {
  text-align: center;
  margin-top: 50px;
}

.entrada-dados {
  text-align: center;
  display: flex;
  width: 100%;
}

#entrada {
  padding: 20px;
  display: inline-block;
  position: relative;
}
<!DOCTYPE html>

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

  <title>Lista</title>

Tarefa

      <input id="entrada" type="text" placeholder="Digite nova Tarefa">
      <button id="btn" onclick="validaEntrada()">enviar</button>

Comment: Pelo texto da pergunta não dá para entender o que quer fazer e o que precisa. Mas analisando o código parece que você tem que remover a linha `novatarefa.addEventListener("click", risco);` e a colocar embaixo da linha `novatarefa.appendChild(deleteBtn);`: Seu código vai ficar assim: https://replit.com/@Augusto-Vasques/line-through#index.html
Comment: e difícil explicar tipo digita 3 entrada e clica em cima de umas da entradas eu queria que o nome da entrada que clicasse ficasse riscado mas não acontece isso risca sempre o ultima entrada
Comment: Eu sei que é difícil explicar, mas edite a pergunta e de uma esclarecida, com o ultimo comentário eu já entendi o problema. Na pergunta pode ser colocado as imagens do problema acontecendo ou gif mostrando o problema. Leia com calma o [Checklist de perguntas do Stack Overflow](https://pt.meta.stackoverflow.com/q/8496/137387) que vai o ajudar a reformular a  pergunta. Depois do almoço eu dou uma passada aqui, talvez(sem compromissos) deixo uma resposta.
Answer: A forma que você esta criando a lista das tarefas é onde esta quebrando o seu código.
Você não precisa criar um array de tarefas para fazer o controle do que vai ser removido porque como você esta criando o botão delete dentro do li, você consegue através deste botão acessar o li e aplicar o estilo de line-through utilizando o EventListner click em seu botão.
E trabalhando com o EventListner você não precisa utilizar o onclick="validaEntrada()" que esta no seu html.
const ul = document.getElementById('list');
const btn = document.getElementById('btn');
const input = document.getElementById('entrada');

function apresentarTarefa(tarefa) {
  const novatarefa = document.createElement('li');
  const deleteBtn = document.createElement('button');
  novatarefa.innerText = tarefa;
  deleteBtn.innerText = 'X';
  novatarefa.appendChild(deleteBtn);
  deleteBtn.addEventListener('click', (event) => removeTarefa(event));
  ul.appendChild(novatarefa);
}

function addTarefa() {
  // A validação que estava no html com o onclick é adicionada nesse momento.
  input.value ? apresentarTarefa(input.value) : alert('Digite uma Entrada!!!');

  input.value = '';
}

function removeTarefa(event) {
  // O event.target vai capturar o elemnt do btn e o parentNode vai trazer o li que é o item da lista uqe vai ser removido. Por final nele é aplicado o estilo de line-through

  event.target.parentNode.style.textDecoration = 'line-through';
}

// Ao trablhar com arrow function impete que a função addTarefa() seja executada quando o arquivo carregar
btn.addEventListener('click', () => addTarefa());

https://stackblitz.com/edit/web-platform-9pzgmn?file=script.js


Find the max value from previous row

Question: I want to find in the below rows the maximum "book_type" value:

book_id
book_type
book_time
uniq_step
book_ordered

1

2022-10-13 00:00:00
800
0

1

2022-10-13 00:00:00
801
0

1
poetry
2022-10-13 00:00:00
802
1

1

2022-10-13 00:00:00
803
0

1

2022-10-13 01:00:00
804
0

1
poetry
2022-10-13 01:00:00
802
1

I want in the line with uniq_step = 804 to have as book_type = poetry but when I use the LAG window function I am getting ' ' (the space string).
So is there any way to take from the partition by book_time the max value as a lag?
Comment: Does your query have to work only for `uniq_step = 804`? Can you share your current query?
Comment: @lemon   Its not only for 804. It is an example.
Comment: have you tried using other window functions other than `LAG`?
Comment: No, only lag and lead I tried. Are you suggesting anything else?
Answer: You could try using the LAST_VALUE window function in place of the LAG one. Since your "book_type" values can't be NULL in your specific case, you can use a CASE statement inside the window function to make them NULL.
LAST_VALUE(CASE WHEN book_type <> "" THEN book_type END) OVER(
    PARTITION BY book_id
    ORDER     BY uniq_step
)

Side Note: Empty spaces/strings are still values in a DBMS. If you have the possibility of refactoring the empty values in your db to NULL values, that will make the DBMS handle your data better than how it does now.

Find the max value from previous row


Concurrency problem involving incircles of a triangle and sub-triangles

Question: The incircle of triangle $A_1 A_2 A_3$ touches the sides $A_2 A_3$, $A_3 A_1$, and $A_1 A_2$ at $S_1$, $S_2$, and $S_3$, respectively. Let $O_1$, $O_2$, and $O_3$ be the incenters of triangles $A_1 S_2 S_3$, $A_2 S_3 S_1$, and $A_3 S_1 S_2$, respectively. Prove that $O_1 S_1$, $O_2 S_2$, $O_3 S_3$ are concurrent.
I have tried drawing a big diagram, as accurate as possible, as a start, and saw that $O_1$, $O_2$, and $O_3$ seem to touch the incircle of triangle $A_1A_2A_3$. However, I am not sure of how to prove this, or how this helps with proving the concurrency. Can I have a little hint as to how to prove this and how it helps answer the question? Much appreciated.
Comment: Showing that, say, $O_3$ lies on the incircle can be done with a little angle chasing. Using the fact that $\triangle S_1 S_2 A_3$, etc, are isosceles, and that $\overline{O_3S_1}$ and $\overline{O_3S_2}$ are angle bisectors, verify that $\angle S_1 S_3 S_2 = (\angle A_1 + \angle A_2 )/2$ and that $\angle S_1 O_3 S_2$ is its supplement; this guarantees that $\square S_1 S_3 S_2 O_3$ is cyclic.
Comment: For the final proof, note that $O_3$ is on the perpendicular bisector of $\overline{S_1S_2}$ (why?), which, because all the $O_i$s and $S_i$s lie on the incircle, says something interesting about $\angle S_1 S_3 O_3$ and $\angle S_2 S_3 O_3$.
Comment: @Blue I like your last part. For the first part, I think it might be better not to think about $A_3$ too much.
Comment: @user208259: There's not a great deal of thinking to be done, about $A_3$ or anything else. The angle chase is over pretty quickly.
Comment: @Blue If you draw the bisector of $\angle S_2 S_1 A_3$, it subtends (with the ray $S_1 A_3$) an arc on the incircle that must be half as large as that subtended by $\angle S_2 S_1 A_3$. Hence it meets the circle at the midpoint of the arc $S_1 S_2$. Then do the same for $\angle S_1 S_2 A_3$.
Comment: @user208259: Indeed. (I read your answer. :) And, certainly, knowing right away that each $O_i$ bisects an arc simplifies the second part of my argument by removing the need for the perpendicular bisector comment.
Answer: You're correct about $O_1$, etc.
Here's a hint to prove it.
Take two points $S_2$ and $S_3$ on a circle. Draw the tangent line at $S_2$, and take a bisector between the tangent line and $S_2S_3$. Prove that the bisector meets the circle midway along the arc from $S_2$ to $S_3$. (You'll want to use the version of the inscribed angle theorem that works for tangent lines.)
Once you have that, the problem is simplified somewhat because you can forget about $A_1$, $A_2$ and $A_3$ and just focus on the points $S_i$ and $O_i$ on the circle, with the points $O_i$ placed on the circle at the midpoints. In this case, say $S_2 O_2$ and $S_3 O_3$ meet at $P_1$, and define $P_2$ analogously. Prove that $P_1O_3 = S_2 O_3 = S_1 O_3 = P_2 O_3$.
Comment: An earlier version of my answer had an error in it.


How can I get final URL of newly added node from hook_node_insert()?

Question: I have installed pathauto and implemented hook_node_insert in my module, the problem is when I use entity_uri to get new node's URL I will get node/xxx instead of pathauto url alias.
How can I get final URL of the node, after ALL other modules had their manipulations?
function HOOK_node_insert($node) {
    $uri = entity_uri('node', $node);
    $uri['path']; // this should be the final path
}

Answer: If you also implement hook_module_implements_alter then you can change when your insert hook fires, like this:
function mymodule_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'node_insert') {
    // Move my_module_node_insert() to the end of the list.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

So now when your insert code executes the path alias should be available.
Comment: You have to clear cache. It only gets called when the registry list of module hooks is built, not normally during a page request.
Comment: The advantage of this over changing module weight is that you can have different orderings per hook. So if for another hook you want to execute ahead of other modules, you can.
Comment: I tried to use `MYMODULE_module_implements_alter` but it seems its not being called at all.
Answer: The reason is that pathauto module is triggering hook after your module hook interaction. To resolve this you have to give a higher weight to your module.
To increase weight, Refer this link: How to update a module's weight
OR
hook_module_implements_alter

This hook is invoked during module_implements(). A module may
  implement this hook in order to reorder the implementing modules,
  which are otherwise ordered by the module's system weight.

And also you have to use drupal_get_path_alias function in node insert, Following is a working code when the module weight is set higher value.
function MODULENAME_node_insert($node) {
    $system_path = 'node/'.$node->nid;
    $current_path = drupal_get_path_alias($system_path);
    drupal_set_message($current_path);
}

Comment: I changed my module weight to 10000 but still getting node/xxx off of `drupal_get_path_alias`. Is this because the new node is not inserted into table yet or something like that?
Answer: There is a function in drupal which gives you the path_alias
For e.g.:
$path = node/$nid;
$url = drupal_get_path_alias($path);
print $url;

By this you will get desired drupal set path.
Comment: thnx @optimusprime


É possível que um script saiba por onde ele foi chamado?

Question: Tenho um script.sh e gostaria de saber se existe alguma forma dele saber por onde foi chamado.
ex:
comando=$(existe algum comando pra isso?)
variavel=$AlgumaVariavelDeAmbienteTalvez

if [[ $comando == "x" ]]; then
  echo "fui chamado pelo prompt do windows"

elseif [[ $variavel == "y" ]]; then
  echo "fui chamado pelo terminal do git bash"

elseif [[ $variavel == "z" ]]; then
  echo "fui chamado pelo ctrl + r (executar do windows)"

elseif [[ $comando == "teste" ]]; then
  echo "fui clicado!!<---"
fi

Como no exemplo, existe alguma variável ou comando que me permita identificar como ele foi chamado??
Comment: Talvez o máximo que dê pra saber é se o script foi executado em um terminal ou não: https://askubuntu.com/q/729904 - Mas saber se foi via menu executar ou double-click acho que não faz diferença (ambos caem no caso "sem terminal")
Answer: Você pode verificar as variaveis de ambiente $0 e $SHELL, veja só:
#!/bin/sh

printf "Linha de Comando: %s\n" $0
printf "Shell           : %s\n" $SHELL

Possível Saída:
Linha de Comando: ./script.sh
Shell           : /bin/bash


Alterar ordem de objetos no array arrastando linhas da tabela angular JS

Question: Tenho um tabela e utilizando jquery ( sortable ), gostaria que quando arrastasse a linha modificando o html da tabela, a ordem do array se modificasse
Exemplo:

CAMPO1
CAMPO2  /// ARRASTO ESSE PRA BAIXO
CAMPO3  /// LOGO ESSE VAI PARA CIMA
ARRAY ORIGINAL: [{id:1, campo:1},{id:2, campo:2},{id:3, campo:3}]
ARRAY DEPOIS : [{id:1, campo:1},{id:3, campo:3},{id:2, campo:3}]

Exemplo do código:

<met charset="UFT-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title ng-bind="apps"></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      ID
      NOME

    {{obj.id}}
      <input type="text" ng-model="obj.nome">

Answer: Utilize mais um javascript o ui.sortable, é responsável pelas mudanças na sua coleção inclusive alterando a indexação dos elementos conforme a nova posição.
Defina no seu modulo a diretiva ui.sortable, conforme exemplo:

angular.module("listagemIndex", ['ui.sortable'])

e na tag tbody inclua essas duas configurações:

Exemplo minimo:

angular.module("listagemIndex", ['ui.sortable'])
  .controller("listagemIndexControl",
    function($scope) {
      $scope.conjunto = [{
        id: 1,
        nome: "ana1"
      }, {
        id: 2,
        nome: "ana2"
      }, {
        id: 3,
        nome: "ana3"
      }, {
        id: 4,
        nome: "ana4"
      }];

    });

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        Index
        ID
        NOME

        {{$index}}
        {{obj.id}}

          <input type="text" ng-model="obj.nome">

Observação: dessa forma não precisa utilizar mais $("#sortable").sortable(); o angular ficar responsável.
Referencia: UI.Sortable directive
Comment: cara muito obrigado! perfeito! funcionou como eu queria! vivendo e aprendendo haha!
Comment: @Renan tem. Abra um questão sobre o assunto explicando suas dúvidas, referenciando essa como exemplo, mas explicando sua real dúvida com um exemplo
Comment: Boa tarde Virgilio, seriapossivel fazer isso sem o Angular? por exemplo só com jquery?


Linear model with different sample size

Question: I have a continuous dependent variable and one categorical independent variable (with three levels). For the three levels, I have 42, 33, and 45 observations respectively. So, in short, I have unequal sample sizes.
I want to run a linear model. But I am unsure how to account for the three levels' different sample sizes.
Is using weights in a linear model the right approach? If so, how to use assign them properly?
Comment: Welcome to Cross Validated! Is there a reason you believe you have to do something to account for the different sample sizes? There are advantages when it comes to experimental design in balancing the categories, and if what's the budget to get more observations, sure, it could be reasonable to allocate that to observing members of the smallest class instead of the largest, but equal sample size is not an inherent assumption of regression on categories.
Answer: There are advantages when it comes to experimental design in balancing the categories, and if there is a budget to get more observations, sure, it could be reasonable to allocate that to observing members of the smallest class instead of the largest, but equal sample size is not an inherent assumption of regression on categories.

Linear model with different sample size


C# Order List of Strings by value

Question: I have a List:
List<string> allValues = new List<string>();

It may contain values like this:

-3,003-m
2,086
-1, 006-mx
etc.

I sorted it with this:
allValues = allValues.OrderBy(q => q).ToList<string>();
allValues.Reverse();

The problem is, that it somehow does not differ between normal values and negative ones (I'd expect that to work even if they are strings).
So instead of:

3,001 | 3,003-m | 2,086 | 2,145-m | 1,004 | 0,033 | -1,008-m | -2,490

it looks like this:

3,001 | 3,003-m | 2,086 | -2,490 | 2,145-m | -1,008-m | 1,004 |  0,033

If now negative or positive, it seems to treat them as the same, resulting in a somewhat random sorted List.
I am aware that there might be better approaches to this, but I wanted to know if it is possible to resolve this in this specific scenario.
Comment: You want 3.001, 3.003-m then 2.086 ? what's the logic ?
Comment: String ordering and int/decimal ordering are two different things.
Comment: what is `-m` or `-mx`?
Comment: Do you want the result to be greater to smaller? then shouldn't the expected result be: 3,003-m | 3,001 | 2,145-m | 2,086 | 1,004 | 0,033 | -1,008-m | -2,490 ?
Comment: @Thomas It should sort by the first number, shouldn't it?
Comment: @HimBromBeere An abbreviation for something, but that's not important. only the number before the comma matters, the rest can be in a random order. (e.g. 3,006-mx | 3,085 | 3,143 can be 3,085 | 3,006-mx | 3,143 as well, it doesn't matter)
Comment: @mybirthname Thanks sherlock. But string ordering should still have a consistent rule, shouldn't it? I don't understand why "-" is treated as if it does not exist.
Comment: @Ian Yeah it should, but that doesn't work. HimBromBeere 's [answer](http://stackoverflow.com/questions/34990070/c-sharp-order-list-of-strings-by-value/34990166#34990166) provided me with the correct solution. Thank you, nonetheless :)
Answer: As allValues is a list of strings also the rules for sorting strings apply for sorting. As you need numerical rules of sorting you have to convert the elements to numbers before sorting, e.g. by calling Convert.ToInt32).
So your ordering looks like this:
var result = allValues.OrderBy(q =>
    Convert.ToInt32(q.SubString(0, q.IndexOf(","))))
    .ToList<string>();

Which will perform on only extracting the numeric part and order by it, however it retains the actual strings.
Comment: This is a comment ... Calling Convert.ToInt32 on  -1,008-m will throw an exception.
Comment: The problem is the -m / -mx part. I need them in my values, but because of that, I can't convert them to int.
Comment: I don't know if someone ever told you this, but you're a genius. Thanks alot!
Answer: This should do the job:
var result = (from s in allValues
             let val = s.Split(new string[] { "-m" }, StringSplitOptions.RemoveEmptyEntries)[0]
             let val2 = double.Parse(val)
             orderby val2
             select s).Reverse();

The idea is to get the first element divided by "-m", you can simply add the split option with something else ("-mx", "-p", etc) as per necessary.
Comment: There is string -mx too in the example, I will suppose there will be more from this.
Comment: Yeah, there are multiple possible endings (like -mx or -d), but nonetheless thank you for this idea.
Comment: @Ian I didn't say it didn't work. It does indeed work.^^

C# Order List of Strings by value


MKMapView - Convert users co-ordinate to a string?

Question: I'd like to grab the users location as a co-ordinate and convert it to a string -- any ideas? I've searched and can't find any solution.
Thank you,
Answer: do you mean string as in
NSString *latAsString = [NSString stringWithFormat:@"%f",newLocation.latitude];
or do you mean convert the lat/long into a street address? (reverse geocode)