text:
Q: Attempting to add searchable NoteID field to INItemXref Acumatica - Attempting to add INItemXRef AlternatID to universal search.
I did look at another question that seemed to possibly be a duplicate of my question, but Acumatica gave him a different approach and he has not gotten any responses, hoping to have better luck:
Adding INItemXRef to Global Search with Inventory Item
The goal is a universal search by customer item number. Acumatica advised to create a dummy INItemXRef maintenance screen and add a searchable NoteID to the DAC to reference this screen. Below is my first stab at adding the NoteID, but I'm getting compilation errors:
   public class INItemXRefExt : PXCacheExtension<PX.Objects.IN.INItemXRef>
   {
    #region NoteID
    [PXDBGuid]
    [PXUIField(DisplayName="NoteID")]
    [PXSearchable(SM.SearchCategory.IN,
        "{0}: {1}",
        new Type[] { typeof(INItemXRef.alternateType), typeof(INItemXRef.inventoryID)},
        new Type[] { typeof(INItemXRef.descr), typeof(INItemXRef.alternateID) }, // add fields you want to be searchable
        NumberFields = new Type[] { typeof(INItemXRef.inventoryID) },
        Line1Format = "{0}{1}", Line1Fields = new Type[] { typeof(INItemClass.itemClassCD), typeof(INItemXRef.alternateID)},
        Line2Format = "{0}", Line2Fields = new Type[] { typeof(INItemXRef.descr) },
        //WhereConstraint = typeof(Where<Current<InventoryItem.itemStatus>, NotEqual<InventoryItemStatus.unknown>>),
        SelectForFastIndexing = typeof(Select<INItemXRef>)  // this is required so that search knows how to index your fields
      )]
      //[PXNote(PopupTextEnabled = true)]
      //public Guid? NoteID { get; set; }
      public virtual Guid? NoteID { get; set; }
      public abstract class NoteID : IBqlField { }
    #endregion
   }

When compiling I get this validation error:
\App_RuntimeCode\INItemXRef.cs(28): error CS0102: The type 'PX.Objects.IN.INItemXRefExt' already contains a definition for 'NoteID'
I thought at first that the reason is because the field was already created in a previous run (I think it was), and the public abstract class NoteID : IBqlField { } was essentially trying to get it to duplicate the field. So I commented out the line and got this:
The base property is missed or IBqlField is not defined: NoteID in extension PX.Objects.IN.INItemXRefExt
I'm sure there are plenty of problems with my searchable attribute as well and will update the question as it evolves, but for the moment I'm stumped at the compilation step.
Update:
Thanks to the responses below I was able to re-write a bit and get everything to compile. Next step is to figure out why the results are a bit strange. interestingly, I cannot do a universal search and find any item unless it has a cross-reference, and then only displays base item info even though I'm trying to display the alternate code(s) and descriptions(s). New code:
#region NoteID
    public abstract class noteID : PX.Data.IBqlField
    {
    }
    protected Guid? _NoteID;
    [PXSearchable(SM.SearchCategory.IN,
        "{0}: {1}",
        new Type[] { typeof(INItemXRef.alternateType), typeof(INItemXRef.inventoryID)},
        new Type[] { typeof(INItemXRef.descr), typeof(INItemXRef.alternateID) }, // add fields you want to be searchable
        NumberFields = new Type[] { typeof(INItemXRef.inventoryID) },
        Line1Format = "{0}{1}", Line1Fields = new Type[] { typeof(INItemClass.itemClassCD), typeof(INItemXRef.alternateID)},
        Line2Format = "{0}", Line2Fields = new Type[] { typeof(INItemXRef.descr) },
        //WhereConstraint = typeof(Where<Current<InventoryItem.itemStatus>, NotEqual<InventoryItemStatus.unknown>>),
        SelectForFastIndexing = typeof(Select<INItemXRef>)  // this is required so that search knows how to index your fields
    )]
    [PXNote(DescriptionField = typeof(INItemXRef.inventoryID),
        Selector = typeof(INItemXRef.inventoryID))]
    public virtual Guid? NoteID
    {
        get
        {
            return this._NoteID;
        }
        set
        {
            this._NoteID = value;
        }
    }
    #endregion

A: You can review one of the out-of-the-box DAC that contains NoteID field and review it for guidance. For example, take a look at the INRegister.NoteID field definition:
#region NoteID
    public abstract class noteID : PX.Data.IBqlField
    {
    }
    protected Guid? _NoteID;
    [PXSearchable(SM.SearchCategory.IN, "{0}: {1}", new Type[] { typeof(INRegister.docType), typeof(INRegister.refNbr) },
        new Type[] { typeof(INRegister.tranDesc), typeof(INRegister.extRefNbr), typeof(INRegister.transferNbr) },
        NumberFields = new Type[] { typeof(INRegister.refNbr) },
        Line1Format = "{0}{1:d}{2}{3}{4}", Line1Fields = new Type[] { typeof(INRegister.extRefNbr), typeof(INRegister.tranDate), typeof(INRegister.transferType), typeof(INRegister.transferNbr), typeof(INRegister.status) },
        Line2Format = "{0}", Line2Fields = new Type[] { typeof(INRegister.tranDesc) },
        WhereConstraint = typeof(Where<INRegister.docType, NotEqual<INDocType.production>, And<INRegister.docType, NotEqual<INDocType.disassembly>>>)
    )]
    [PXNote(DescriptionField = typeof(INRegister.refNbr),
        Selector = typeof(INRegister.refNbr))]
    public virtual Guid? NoteID
    {
        get
        {
            return this._NoteID;
        }
        set
        {
            this._NoteID = value;
        }
    }
    #endregion

Notice the use of PXNote attribute(and no use of PXDBGuid attribute).
You can try similar approach and only with PXNote first, to confirm it compiles properly. Then you could add PXSearcheable and start working on it.

A: This particular question has been answered, but in order to get the search to work the way I need will have to go a different direction creating a brand-new DAC, BLC, and maintenance screen. Thanks for the help!


text:
Q: How does swift library hide its implementation At certain point of time we might have tried to see the code for packages/library provided by apple for ios development. For example : UIViewController, SFSafariViewController, and so on.. When we move into file of these package/library we find something like this.
extension UIViewController {

    @available(iOS 5.0, *)
    open var children: [UIViewController] { get }

    @available(iOS 5.0, *)
    open func addChild(_ childController: UIViewController)

    @available(iOS 5.0, *)
    open func removeFromParent()

    @available(iOS 5.0, *)
    open func transition(from fromViewController: UIViewController, to toViewController: UIViewController, duration: TimeInterval, options: UIView.AnimationOptions = [], animations: (() -> Void)?, completion: ((Bool) -> Void)? = nil)

    @available(iOS 7.0, *)
    open var childForStatusBarStyle: UIViewController? { get }

    @available(iOS 7.0, *)
    open var childForStatusBarHidden: UIViewController? { get }

}

It is just part of what that file contains. But this is merely a method signature and these method has lot more in its implementation which is hidden from user access.
My question is

How does this is possible? How can we hide or provide user only the
  function signature to use and rest thing is hidden from user's eye?

A: UIKit is a framework so it has Access Control
From docs.swift.org

Access control restricts access to parts of your code from code in
  other source files and modules. This feature enables you to hide the
  implementation details of your code, and to specify a preferred
  interface through which that code can be accessed and used.

You can add framework to your project with Access Control
Access Control document
Swift standard library
In Swift Access Controls from docs.swift.org:

Open access and public access enable entities to be used within any source file from their defining module, and also in a source file
  from another module that imports the defining module. You typically
  use open or public access when specifying the public interface to a
  framework. The difference between open and public access is described
  below.
Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that
  module. You typically use internal access when defining an app's or a
  framework's internal structure.
File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the
  implementation details of a specific piece of functionality when those
  details are used within an entire file.
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the
  same file. Use private access to hide the implementation details of a
  specific piece of functionality when those details are used only
  within a single declaration.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Arguments for MongoDB backup with OpsManager or mongodump? I have a replica set of two MongoDB nodes running (with an arbiter) and I am now wondering about the best backup and recovery solution. I am aware of the official documentation, but it does not provide me enough pro and con's for each solution. In particular, our team wants to decide between either a OpsManager-solution or a mongodump. I am not experienced with either of them, so could you be so kind and please help me out with more arguments and experiences? The following arguments I collected so far, feel free to edit them if they are not correct:
Arguments for mongodump and against OpsManager

*

*simpler, just a command line for a snapshot and another one for the recovery

*no additional servers and/or licenses required which is the suggested solution for OpsManager

Arguments for OpsManager and against mongodump

*

*tested solution, provided directly by the team who developed MongoDB

*cleaner and sustainable, since it could be configured via GUI and does not require command line access

*easy logging of each backup run possible, which contrasts to mongodump requiring a custom (power?) shell script wrapped around

Related questions on Stackexchange which did not solve my issue:

*

*https://stackoverflow.com/questions/22555280/best-way-to-make-hot-backup-mongodbtokumx-database-instance

*https://stackoverflow.com/questions/31502601/how-should-i-backup-mongodb-on-digitalocean

*https://stackoverflow.com/questions/39169209/backup-mongodb-data

*https://stackoverflow.com/questions/17458124/how-to-get-a-consistent-mongodb-backup-for-a-single-node-setup

*Backup with mongoexport or mongodump?

A: It might not be a full answer (as others will have valid opinion) but I am ok with not getting credit.
Argument in favor of OpsManager:

*

*Continuous backup, you can recover up to the last committed transaction.

*You can set your retention one time and do not have to worry about it.

*You can automatically make multiple copy of your backup for redundancy.

*Restoring non production environment (DEV/QA/INT) in matter on minutes.

*mongodump excludes the content of the local database in its output which is problematic for sharded cluster and replica set.

*mongodump only captures the documents in the database in its backup data and does not include index data. mongorestore or mongod must then rebuild the indexes after restoring data.

*mongodump can adversely affect performance of the mongod. If your
data is larger than system memory, the mongodump will push the
working set out of memory.

*Mongodump is not suitable for large databases. This is from official documentation.

The mongodump and mongorestore utilities work with BSON data dumps,
  and are useful for creating backups of small deployments. For
  resilient and non-disruptive backups, use a file system or block-level
  disk snapshot function, such as the methods described in the MongoDB
  Backup Methods document.
Because mongodump and mongorestore operate by interacting with a
  running mongod instance, they can impact the performance of your
  running database. Not only do the tools create traffic for a running
  database instance, they also force the database to read all data
  through memory. When MongoDB reads infrequently used data, it can
  evict more frequently accessed data, causing a deterioration in
  performance for the database's regular workload.


text:
Q: Unable to fetch list of Azure Resources via Postman I am trying to fetch the list of resources present in my Azure Resource Group.
To do that, I got an access token by registering one app in Azure AD using the client_credentials flow.
But when I am using that token to query like below, I'm getting 401 Unauthorized - Authentication failed error.
Query that I used:
GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/resources?api-version=2021-04-01

I have owner access to all my resources but why am I getting 401 Unauthorized error. Is there any step that I missed?
Can anyone point me in a right path?

A: I came to know I have to give API permissions for Azure Service Management.
After giving user_impersonation, I changed the scope to https://management.azure.com/.default and got access token.
Using this token, I successfully got the list of resources without any errors.


text:
Q: c# confirm each combobox has a unique value selected I have a winform with a group of comboboxes, all of the comboboxes with the same list items in them.
I need a way to confirm that when the user is done selecting a value in each box that they only selected each list value once.
Ex:
cbox1     cbox2     cbox 3
Item A    Item B    Item A (this needs to flag an error since Item A is already selected in cbox1)
I was thinking trying to use the selectedvaluecommited action (as after i populate the list I change the selected index to -1  so they all show "empty" to start) but the loop to make it work seems to be eluding me.
background: this is choosing fields to build a spreadsheet and the user needs to choose the field order.

A: You can do it like this (quick and dirty):
Add SelectedIndexChanged handler for all three comboboxes (in Form_Load in example)
comboBox1.SelectedIndexChanged += CheckComboBoxes;
comboBox2.SelectedIndexChanged += CheckComboBoxes;
comboBox3.SelectedIndexChanged += CheckComboBoxes;

in CheckComboBoxes method do your checking:
 private void CheckComboBoxes(object sender, EventArgs e)
 {
     if (comboBox1.SelectedIndex == comboBox2.SelectedIndex ||
         comboBox1.SelectedIndex == comboBox3.SelectedIndex ||
         comboBox2.SelectedIndex == comboBox3.SelectedIndex)
             MessageBox.Show("comboboxes are not unique");
 }

EDIT:
this is approach when having n comboboxes. Put all items into list, select distinct values and compare that distinct count with items count... Something like this:
private void CheckComboBoxes(object sender, EventArgs e)
{
    List<string> comboValues = new List<string>();
    foreach (Control c in this.Controls)
    {
        if (c is ComboBox && !string.IsNullOrEmpty((c as ComboBox).SelectedItem.ToString()))
        comboValues.Add((c as ComboBox).SelectedItem.ToString());
    }
    if (comboValues.Distinct().ToList().Count < comboValues.Count)
        MessageBox.Show("not all combos are unique");
}

A: Here's an approach you can take.

*

*To make the affected comboboxes easy to distinguish, put them all in a GroupBox container.

*Write a validation method for your group box.

*Subscribe to the group box Validating event by attaching it to your validation method.

*In your validation method, loop through all the ComboBox controls in the group box and check if there are any duplicates, and issue an error if so.

For example, assuming the group box is called groupBox1:
private void GroupBox1_Validating(object sender, CancelEventArgs e)
{
    base.OnValidating(e);
    var selectedIndices = groupBox1.Controls.OfType<ComboBox>().Select(item => item.SelectedIndex);
    var anyDuplicates = selectedIndices.GroupBy(x => x).Any(x => x.Count() > 1);

    if (!anyDuplicates)
        return;

    MessageBox.Show("There are duplicates!");
    e.Cancel = true;
}

And subscribe to the group box Validating event in the Form1 constructor:
public Form1()
{
    InitializeComponent();
    groupBox1.Validating += GroupBox1_Validating;
}

Sometimes when validating like this, you need to prevent the validation logic from executing if the user clicks the Cancel button. You're supposed to be able to set the CausesValidation property of the Cancel button to false to prevent this, but I find that it doesn't work for me.
Instead, I just use a bool cancelling field which I set to true in the Cancel button handler:
private void cancelButton_Click(object sender, EventArgs e)
{
    cancelling = true;
    this.Close();
}

bool cancelling;

And then add the following to the start of GroupBox1_Validating():
if (cancelling)
    return;

A: If it is possible to have different UI design then my suggestion goes as under:
Alternative UI Design - A

*

*Create One ListBox ListFieldsOriginal and populate

*Create Second ListBox ListUserSelection, keep it empty initially

*Provide buttons as under:
Button '>' means add currently selected item from ListFieldsOrginial to ListUserSelection at end; and remove that item from ListFieldsOriginal
Button '<' means remove currenly selected item from lstUserSelection; and add that item back to ListFieldsOriginal (of course at end)
NOTE: If adding item back to ListFieldsOriginal is your requirement then extra coding is required to find its appropriate index in the ListFieldsOriginal.
Alternative UI Design - B

*

*Create One CheckedListBox ListFieldsOriginal and populate

*Create one ListBox ListUserSelection, keep it empty initially

*Define ItemCheck event handler for ListFieldsOriginal to add/remove items to/from ListUserSelected.
if (e.CurrentValue==CheckState.Unchecked)
{
   string item = ListFieldsOriginal.Items[item];
   ListUserSelection.Items.Add(item);
}
else
{
   string item = ListFieldsOriginal.Items[item];
   ListUserSelection.Items.Remove(item);
}


text:
Q: Concentration inequalities for product of gaussians Are there any concentration inequalities (i.e. probability bounds on how a random variable deviates from its expectation) for the product of $n$ independent gaussian random variables with zero means and equal variances? What about different means and variances?

A: This paper computes the desired probability explicitly in Theorem 3 (page 4).
The theorem states that for independent standard normal Gaussians random variables $g_i$ one has
$$
\mathbb{P}(X \le t) = \mathbb{P}(X \ge -t) = f_{0.5, 1}\bigg(\frac{2^n} t\bigg),
$$
where
$$
f_{\nu, \xi}(u) = \nu + \frac 1 {2^{\xi}} \cdot \frac 1 {\pi^{n/2}} \sum_{k=0}^\infty u^{-0.5 - k} \sum_{j=0}^{n-1} H_{kj} \cdot [\log u]^j,
$$
for details and definition of $H_{kj}$ see the paper itself.
The expression seems to be complicate enough to argue to the concentration bound immediately from here, but I believe this is a good starting point.


text:
Q: Get string value of array cell containing a numeric-like value I have an array like the following:
    var dimensions = [
        ["0.250", "1/4 0.250" ],
        ["0.375", "3/8 0.375" ],
        ["0.500", "1/2 0.500" ]
    ];

The first element is specified as a string, but could be interpreted as a number. In some situations I want to treat it as a number, in others like a string:
    var string_value = dimensions[ 0 ][ 0 ];
    var numeric_value = dimensions[ 0 ][ 0 ];

How do I control which interpretation is used?

A:
How do I control which interpretation is used?

You can use explicitly transform them into one by using String and Number constructors
var string_value = String( dimensions[ 0 ][ 0 ] );
var numeric_value = Number( dimensions[ 0 ][ 0 ] );

A: Assuming if it can be a valid number, and you want it to be, you can simply use isNaN for a conditional parsing.
var string_value;
var numeric_value;

if (isNaN(dimensions[0][0])) {
    string_value = dimensions[0][0];
} else {
    numeric_value = parseFloat(dimensions[0][0]);
}

A: You have already a string, just assign and for numer, you could use an unary + for casting to Number.
var string_value = dimensions[0][0];
var numeric_value = +dimensions[0][0];

A: Use "parseFloat" on the one you want to use as an integer, and leave the other one as is for string (as it's defined within quotes it should read as a string anyway).
Eg:
var numberic_value = parseFloat(dimensions[0][0]);


text:
Q: C# WPF AvalonDock Устанавливаю AvalonDock через NuGet и все нормально работает, но я бы хотел использовать source code в проекте. Копирую классы и все остальное и VS 2017 видит xmlns но бросает ошибки на сами теги. Пишет что не видит DockingManager в namespace и подобное. Изменял на "clr-namespace: ..." все находит но не рендерит, проект запускается и ничего не видно.

A: Как подключать сторонние проекты в свой:

*

*Скачиваем исходный код.

*Распаковываем в директорию рядом с нашим проектом (либо в любом другом месте). В вашем случае там две папки, одна из которых заканчивается на "_35" - это версия .NET 3.5.

*В основном проекте жмём правой кнопкой мыши по нашему решению - Добавить - Существующий проект.

*Выбираем файл .csproj нужного компонента (у вас это ExtendedWPFToolkitSolution\Src\Xceed.Wpf.AvalonDock\Xceed.Wpf.AvalonDock.csproj).

*Пересоберите все решение, должно собраться без ошибок. Если они есть - ищем виновника, может проект на что то ссылается. В  итоге в консоле должны увидеть:

========== Перестроение всех проектов: успешно: 2, с ошибками: 0, пропущено: 0 ==========

6. Если ошибок нет, то двигаемся дальше, а именно, добавление в основном проекте ссылки на сторонний. Жмём у нашего проекта ПКМ по "Ссылки" - "Добавить ссылку".
7. В появившемся окне сбоку выбираем "Проекты", там увидим сторонний проект. Выбираем его "галкой" и жмём ок.

*Желательно ещё раз пересобрать решение. Далее мы можем работать с этим компонентом. Я возьму код из документации, уберу только из него все лишнее.

*Я не знаю как лично у вас, но у меня при написание XAML кода сама студия предлагает добавить недостающие пути на ту или иную сборку, если у вас не так, то не забываем добавить вручную:

xmlns:xcad="http://schemas.xceed.com/wpf/xaml/avalondock"

Ура, можно запускать!


text:
Q: Equivalence of three asymptotic statements Question 22 of chapter 4 in Apostol's "Introduction to Analytic Number Theory" asks to show that the following three statements are equivalent:
$$\psi(x) \log(x) + \sum_{n \le x} \Lambda(n) \psi\left(\frac{x}{n}\right) = 2x \log(x) + O(x) \tag{1}$$
$$\psi(x) \log(x) + \sum_{p \le x} \log(p) \psi\left(\frac{x}{p}\right) = 2x \log(x) + O(x) \tag{2}$$
$$\vartheta(x) \log(x) + \sum_{p \le x} \log(p) \vartheta\left(\frac{x}{p}\right) = 2x \log(x) + O(x) \tag{3}$$
where the latter two sums are extended over those prime numbers $p$ which are less than or equal to $x$. $\Lambda$ is the Mangoldt function and $\psi$ and $\vartheta$ are the Chebyshev functions; $\psi(x) = \sum_{n \le x} \Lambda(n)$ and $\vartheta(x) = \sum_{p \le x} \log(p)$, where again the latter sum is over those primes $p$ less than or equal to $x$. My plan of attack is to show that $(1)\Rightarrow(2),(2)\Rightarrow(3)$ and $(3)\Rightarrow(1)$. I show that $(1)\Rightarrow(2)$ by using the fact that
$$\sum_{p \le x} \Lambda(p) \psi\left(\frac{x}{p}\right) \le \sum_{n \le x} \Lambda(n) \psi\left(\frac{x}{n}\right)$$
I show that $(2)\Rightarrow(3)$ by using the fact that
$$\vartheta(x) \le \psi(x)$$
Therefore I need only show that $(3)\Rightarrow(1)$. To give myself ideas on how to do this I'm first attempting to show that $(2)\Rightarrow(1)$ in the hopes that the method for doing that can be used for $(3)\Rightarrow(1)$. What I have tried so far is writing the sum in $(1)$ to look like the sum in $(2)$:
\begin{eqnarray}
\sum_{n \le x} \Lambda(n) \psi\left(\frac{x}{n}\right) &=& \sum_{p \le x} \sum_{m \le \log_p(x)} \Lambda(p^m) \psi\left(\frac{x}{p^m}\right) \\
&=& \sum_{p \le x} \sum_{m \le \log_p(x)} \log(p) \psi\left(\frac{x}{p^m}\right) \\
&=& \sum_{p \le x} \log(p) \psi\left(\frac{x}{p}\right) + \sum_{p \le x} \sum_{2 \le m \le \log_p(x)} \log(p) \psi\left(\frac{x}{p^m}\right)
\end{eqnarray}
and try to bound the right sum by taking the maximal summand values and using $\pi(x) < 6 \frac{x}{\log(x)}$ (I'm only using results of this kind that are proved in the chapter, working on the assumption that these results are all I will need). However, this gives a bound that is greater than $O(x)$, and so this technique will not yield the desired result. Any answers or hints would be appreciated (for continuing on my approach, or using another approach).


text:
Q: Set font size and color in the second line of string in shiny app In the shiny app below I want to change the font size and color of only the word "world" in the second line of my text. How is this possible?
require(shiny)
runApp(
  list(
    ui = pageWithSidebar(
      headerPanel("multi-line test"),
      sidebarPanel(
        p("Demo Page.")
      ),
      mainPanel(
        htmlOutput("text2")
      )
    ),
    server = function(input, output){

      output$text2 <- renderUI({
        HTML(paste("hello", "world", sep="
"))
      })

    }
  )
)

A: Replace "world" with
"world"

A: You can solve this using HTML tags inside the renderUI element:
output$text2 <- renderUI({
HTML(paste("hello", "world", sep="
"))
})


text:
Q: How to create a custom UnitTest report in Python? I'm having some difficulty understanding how I would go about changing a unittest report similar to:
======================================================================
FAIL: test_equal (__main__.InequalityTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_notequal.py", line 7, in test_equal
    self.assertNotEqual(1, 3-2, "My Custom Message")
AssertionError: 1 == 1

to a report resembling:
Line 7: My Custom Message

How could I parse these reports?

A: After further research, my problem can be solved by overriding the default TestResult class as seen here: Turn some print off in python unittest
or by using some third-party customization such as  nose, an HTMLTestRunner.

A: In case you need to create a custom report based on the success/failure of individual test cases, you can create a custom TestRunner, which uses custom TestResult, and in TestResult class, override success and failure methods. This will provide the callback for processing as per requirement.
class CustomTestRunner(TextTestRunner):
        def _makeResult(self):
            return CustomTestResult(TestResult)
        def run(self, test) -> unittest.result.TestResult:
            # add implementation as per TextTestRunner run method here

class CustomTestResult:
       def addSuccess(self, test):
           super(CustomTestResult, self).addSuccess(test)
           # your logic to log success cases

       def addFailure(self, test):
           super(CustomTestResult, self).addFailure(test)
           # your logic to log failure cases

For reference, please check python unittest module.


text:
Q: Redisplaying form data with errors I use a form to collect data, edit it and then use cURL to re-display the form with error messages. The problem is the input data as originally entered is wiped. out.
I tried to re-display the data using the the POSTFIELDS option with an array containing the post data. But that is not working.
Here's the cURL code.
errors:
$data = array (book => $book, begchap => $begchap, begverse => $begverse, endchap => $endchap, endverse => $endverse);
//foreach($data as $x => $x_value) {
//    echo "Key=" . $x . ", Value=" . $x_value;
//    echo "
";
//}
// Get cURL resource
$url="http://www.seekinghimdaily.org/php_snippets/read_any_passage_new.snippet.php/?e1=".$e1."&e2=".$e2."&e3=".$e3."&e4=".$e4."&e5=".$e5."&e6=".$e6;
//Step 1 - initialize cURL session
$cSession = curl_init();
//step2 - set cURL options
curl_setopt($cSession,CURLOPT_URL,$url);
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
//curl_setopt($cSession,CURLOPT_POST,true);
//curl_setopt($cSession,CURLOPT_POSTFIELDS,$data);
curl_setopt($cSession,CURLOPT_HEADER, false);
//step3 - Execute cURL session
$result=curl_exec($cSession);
if(curl_errno($cSession))
{
    echo 'error:' . curl_error($cSession);
}
//step4 - Close cURL session
//step5
echo $result;
end:
?>

Here's a line of the code I am trying to use to re-display the data keyed plus error messages.

Beginning Verse <input type="text" id="begverse" name="begverse" size="2" maxlength="2" value="<?php echo $_POST['begverse']?>"/>'
<?php
if ($e5=='y')
  {
   echo ' Not in book. ';
  }
?>

Thanks again for your patience and assistance.


text:
Q: Selecting algorithm for Hamiltonian paths There is a series of complete undirected graphs $\Gamma$ with fixed starting points. Hamiltonian paths $c_\Gamma$ were obtained by a traveler who walked on $\Gamma$ and visited every vertex once. One needs to decide if the traveler's intention was more likely to minimize the total path length (TSP path) or visit the nearest unvisited vertex (NN algorithm).
My idea is

*

*Introduce two "metrics" on the Hamiltonian paths $a=A_0A_1\ldots A_n$:
$$
\rho_T(a) = \sum_{i=0}^{n-1}|A_iA_{i+1}|,\quad
\rho_N(a) =\sum_{i=0}^{n-1}\frac{|A_iA_{i+1}|}{\min\{|A_iA_j|, i+1\le j\le n\}}.
$$
Clearly $\rho_T(a)$ is minimal if and only if $a$ is the shortest path, $\rho_N(a)$ is minimal if and only if $a$ is the NN path (one can assume that both are unique).

*For a given graph $\Gamma$ change the edge lengths L' <- rnorm (1,mean=L,sd=rL), $0<r<1$

*Find the shortest path and the NN path in the modified graph

*Calculate in the original graph $\rho_T$ of the shortest path and $\rho_N$ of the NN path from step 3.

*Repeat 2-4 and get two samples

*Calculate $p$-value of $t$-statistics for $\rho_T(c_\Gamma)$ and the first sample and $p$-value of $t$-statistics for $\rho_N(c_\Gamma)$ and the second sample. Denote them by $P_\Gamma$ and $P'_\Gamma$ respectively.

*Сompare the percentage of the graphs with $P_\Gamma<0.05, P'_\Gamma>0.05$ and the percentage of the graphs $\Gamma$ with $P_\Gamma'<0.05, P_\Gamma>0.05$. If the latter is greater than the former then the observed paths are more likely to be NN, i.e. the traveler's intention was local rather than global minimization.

*Adjust the deviation multiplier $r$ from step 2 so that the relation between the perсentages becomes clearer.

Is it a legitimate way to answer the question?


text:
Q: LINQ; forcing a new {} to return Iqueryable? I written a small query and in Linqpad its working well but (see below) Tariffs is not returned as Iqueryable, does anyone know how to fix this ?
Basically see Tariffs = new ....,
from v in House
join gvt in
    (from t in MyTariffs where t.Id == 3 select t)
on v.IdTariff equals gvt.Id
select new
{
   Id = v.Id,
   Tariffs = new
   {
     Deposit = gvt.CurrentDeposit
   }
}

I did try this but its invalid because gvt isn't a table or something?
from v in House
join gvt in
    (from t in MyTariffs where t.Id == 3 select t)
on v.IdTariff equals gvt.Id
select new
{
   Id = v.Id,
   Tariffs = from x in gvt   // NOTICE i am doing from x in gvt... But it fails..
   select new
   {
     Deposit = gvt.CurrentDeposit
   }
}

Of course gvt contains just the values i want because it has the inner join...
I could do just pull directly from my MyTariffs (which works it returns Iqueryable)  but then i have too much info as its not taking into consideration the join which i did in gvt?
from v in House
join gvt in
    (from t in MyTariffs where t.Id == 3 select t)
on v.IdTariff equals gvt.Id
select new
{
   Id = v.Id,
   Tariffs = from x in MyTariffs // THIS has nothing to do with my join
   select new
   {
     Deposit = gvt.CurrentDeposit
   }
}

A: Select the data in a subquery -- are you sure that Id == 3 and Id == v.IdTariff?  If that's really the case, then you could add a where clause to the outer query to select only v when v.IdTariff == 3.  I'm assuming, though, that you want them all.
var q = from v in House
        select new {
            Id = v.Id,
            Tariffs = (from g in MyTariffs
                       where g.Id == v.IdTariff
                       select g.CurrentDeposit)
        };

Grouped example (uncompiled/untested), in response to your comments.
var q = from v in House
        join g in (from t in MyTariffs where t.Id == 3 select t)
        group by v.Id into gvt
        select new {
            Id = gvt.Key,
            Tariffs = gvt.g
        };


text:
Q: database choice to record museum object I am working in a museum and I would like to create a database that record each object belonging to the collection. I have already created a database with Filemaker pro but I find this software far too expensive and I am would like to use an open source software.
There are so many possibilities and I don't really know which software would suit the best to my project. I am therefore seeking for advices.
I am searching an open source database that meets the 2 following criteria:
1°) Easy display of image in the final layout of the database
2°) Possibility to organizes the final layout. I don't really find the use of a table easy to read. For example, with Filemaker Pro, I can organize each field (artist, date, title, etc...) allowing me to display them as I want.
Thank you

A: There is a number of open-source, web-based projects on GitHub, including Providence by CollectiveAccess and Ennigaldi. The former is feature-rich but less flexible, while the latter is still in early development, but can be more easily customized since it is built on top of Django.
That said, this sort of question --- "best practices" and so on --- is generally frowned upon in StackOverflow and will probably be locked down.


text:
Q: Error: "You have been creating or deleting too many calendars or calendar events in a short time." first time asking a question here.
I've built a Google App Script that takes event info from Google Sheets and creates events on Google Calendar, based on @Mogsdad's answer here. (I couldn't post a question on that thread because of my nonexistent reputation)
The "exportEvents" function worked beautifully the first time. But once the spreadsheet had more rows of information, it didn't finish the script and instead said "You have been creating or deleting too many calendars or calendar events in a short time. Please try again later."
This is not due to the daily quota that Google set because I'm not creating anything close to 10,000 events a day. I searched for a solution, and found this on Google Product Forum by @JEvans-GSA, who is basing his script on @Mogsdad's script like me.
I adapted his solution and separated the "updateEvents" function from "exportEvents" (and also created "deleteEvents" function). Now the "exportEvents" do not run into the "You have been creating or deleting too many calendars or calendar events in a short time. Please try again later" problem. But the "updateEvents" still get the same warning, half way through execution!

*

*For example, I created 83 events titled "1" to "83" and exported the
events to calendar successfully.

*Then I changed the event titles to "100" to "182" and tried to update the events.

*It only updated "1"~"15" to "101"~"114", and everything else remained the same. - I made the function update the "status" column as "Updated (today's
date)", which also didn't execute.

So the function started but didn't finish, which makes me think that the error must be somewhere in setting the recurrence. Is there a workaround to make "updateEvents" work, or as @Mogsdad suggested in the original answer, is the only other way to delete and recreate events?
Thank you in advance for any help. Here are links to my spreadsheet (I'm not allowed to use more than 2 links, due to my low rep): - https://docs.google.com/spreadsheets/d/1V6eioCo4QDPO2DdCyW93sLRWT_xtzKM-drDPVI1Gd8s/edit?usp=sharing
And my current script:
//Global settings
var calId = 'n02m72vanqabnt1gcjluk2vosk@group.calendar.google.com';
var moderatorEmail = 'EMAIL_ADDRESS';

var idId = 0;
var startTimeId = 1;
var endTimeId = 2;
var titleId = 3;
var organizerId = 4;
var locId = 5;
var descId = 6;
var urlId = 7;
var topicId = 8;
var typeId = 9;
var contactId = 10;
var contactEmailId = 11;
var actionId = 12;
var statusId = 13;

//Add a custom menu
function onOpen() {
  var ss = SpreadsheetApp.getActive();
  var items = [
    {name: 'Export Events', functionName: 'exportEvents'},
    {name: 'Update Events', functionName: 'updateEvents'},
    {name: 'Delete Events', functionName: 'deleteEvents'}
  ];
  ss.addMenu('Calendar', items);
}

//Actual functions
function exportEvents() {
  var spreadsheet = SpreadsheetApp.getActiveSheet();
  var headerRows = 2; //Number of rows of header info to skip
  var range = spreadsheet.getDataRange();
  var data = range.getValues();
  var cal = CalendarApp.getCalendarById(calId);
  for (i in data) {
    if (i < headerRows) continue; //Skip header rows
    var row = data[i];
    var title = row[titleId];
    var tstart = new Date(row[startTimeId]);
      tstart.setDate(tstart.getDate());
      tstart.setMonth(tstart.getMonth());
      tstart.setYear(tstart.getYear());
      tstart.setTime(tstart.getTime());
    var tstop = new Date(row[endTimeId]);
      tstop.setDate(tstop.getDate());
      tstop.setMonth(tstop.getMonth());
      tstop.setYear(tstop.getYear());
      tstop.setTime(tstart.getTime());
    var loc = row[locId];
    var contact = row[contactId];
    var organizer = row[organizerId];
    var topic = row[topicId];
    var type = row[typeId];
    var contactEmail = row[contactEmailId];
    var url = row[urlId];
    var status = row[statusId];
    var desc = (row[descId]
        +"\n\n-Organizer: "+organizer
        +"\n-Event URL: "+url
        +"\n-Event Type: "+type
        +"\n-Event Contact: "+contact+" ("+contactEmail+")")
    var id = row[idId];
    // Check if the event already exists, update it if it does
    try {
      var event = cal.getEventSeriesById(id);
    }
    catch (e) {
    // Do nothing - we just want to avoid the exception when event doesn't exist
    }

    if (!event) {
      //cal.createEvent(title, new Date("Month D, YYYY 00:00:00"), new Date("Month D, YYYY 00:00:00), {description:desc,location:loc});
      var newEvent = cal.createEvent(title, tstart, tstop, {description:desc,location:loc}).getId();
      row[idId] = newEvent; // Update the data array with event ID

      var d = new Date();
      var time = d.getMonth()+1 + "/" + d.getDate() + "/" + d.getFullYear()
      row[statusId] = "Exported " + time
      }
    debugger;
  }
  range.setValues(data);
}

function updateEvents() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var headerRows = 2; //Number of rows to skip
  var range = sheet.getDataRange();
  var data = range.getValues();
  var cal = CalendarApp.getCalendarById(calId);
  for (i in data) {
    if (i < headerRows) continue;
    var row = data[i];
    var title = row[titleId]; //Second column
    var tstart = new Date(row[startTimeId]);
      tstart.setDate(tstart.getDate());
      tstart.setMonth(tstart.getMonth());
      tstart.setYear(tstart.getYear());
      tstart.setTime(tstart.getTime());
    var tstop = new Date(row[endTimeId]);
      tstop.setDate(tstop.getDate());
      tstop.setMonth(tstop.getMonth());
      tstop.setYear(tstop.getYear());
      tstop.setTime(tstart.getTime());
    var loc = row[locId];
    var contact = row[contactId];
    var organizer = row[organizerId];
    var topic = row[topicId];
    var type = row[typeId];
    var contactEmail = row[contactEmailId];
    var url = row[urlId];
    var action = row[actionId];
    var status = row[statusId];
    var desc = (row[descId]
        +"\n\n-Organizer: "+organizer
        +"\n-Event URL: "+url
        +"\n-Type: "+type
        +"\n-Event Contact: "+contact+" ("+contactEmail+")")
    var id = row[idId];
    try {
      var event = cal.getEventSeriesById(id);
    }
    catch (e) {
      // do nothing
    }
    if (event) {
      if (action === "Update") {
        event.setTitle(title);
        event.setDescription(desc);
        event.setLocation(loc);
      // eventSetTime(tstart, tstop); // cannot setTime on eventSeries.
      // ... but we Can set recurrence!
        var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
        event.setRecurrence(recurrence, tstart, tstop);

        var d = new Date();
        var time = d.getMonth()+1 + "/" + d.getDate() + "/" + d.getFullYear()
        row[statusId] = "Updated " + time
      }
    }
  }
  debugger;
  range.setValues(data);
}

function deleteEvents() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var headerRows = 2; //Number of rows to skip
  var range = sheet.getDataRange();
  var data = range.getValues();
  var cal = CalendarApp.getCalendarById(calId);
  for (i in data) {
    if (i < headerRows) continue;
    var row = data[i];
    var action = row[actionId];
    var status = row[statusId];
    var id = row[idId];
    try {
      var event = cal.getEventSeriesById(id);
    }
    catch (e) {
    }
    if (event) {
      if (action === "Delete") {
        event.deleteEventSeries();

        var d = new Date();
        var time = d.getMonth()+1 + "/" + d.getDate() + "/" + d.getFullYear()
        row[idId] = "Deleted";
        row[statusId] = "Deleted " + time;
      }
    }
  }
  debugger;
  range.setValues(data);
}

A: Had a similar problem with a script that creates calendar event blocks on week-days, only using nested while-loops. I inserted Utilities.sleep(3000) so that the script would pause after every 10 iterations. I tested it for a 20 week period creating 20 events per week (400 events) and no error message. I'm going to play around with the timing of this to see whether I can reduce the sleep time. Here's the the Google Developer reference info:
https://developers.google.com/apps-script/reference/utilities/utilities#sleep(Integer)

A: I had the same error, and searching on Google let me here, so I'll leave my solution. In my case, I was added email reminders to events, which caused the "You have been creating or deleting too many calendars or calendar events in a short time. Please try again later." error after created only 10s of events. Removing the call to Event.addEmailReminder() fixed my problem.


text:
Q: Why is the partial derivative of strain energy function with respect to strain equal to stress In Elasticity, we have a strain energy function , $W$, that is a function of strain tensor, $E$.
Then the cauchy stress tensor, $T$ can be determined by:
$$T_{ij}=\frac{\partial W}{\partial E_{ij}} \tag{$\star$}$$
First Question, does this equation hold for all elastic bodies? Or just linear elasticity?
Second, I am having trouble finding the intuition behind this relation. Could someone please help explain why the partial derivative of the strain energy with respect to strain components gives the stress components?
My attempt at deriving ($\star$)
The strain energy is the energy stored in a body due to deformation. And since we are considering elastic bodies, its equal to work done in order to deform it.
In 1D, for a beam of cross sectional area $A$ being stretched by a length of $u_0$ we can write an integral for work as :
$$ Work = \int_{0}^{u_0}{\sigma(u)*A(u)*du} $$
where $\sigma$ is just the stress normal to the cross sectional area in this 1D case.
So, I can see how the stress tensor definitely plays a role in the strain energy, but I just can't figure out how to properly derive ($\star$). Can someone walk me through the derivation?

A: 1. Yes, the relation $$\mathrm{stress}=d(\mathrm{strain\,energy\,density})/d(\mathrm{strain})$$ holds for all elastic bodies, not just linearly elastic bodies. This equation implies that all differential work goes into elastic strain energy, which holds even for nonlinearly  elastic materials  (e.g., hyperelastic materials). However, the equation wouldn't apply to plastic deformation, for example, in which substantial amounts of work are converted to heat and expended through the formation of crystal defects.
2. Regarding the intuition behind this equation, we can say that any way to add energy to a system involves two parameters (called thermodynamic conjugate variables): a generalized force and a generalized displacement. The first term is intensive; i.e., if you doubled the system size, then the generalized force would stay the same. The second term is extensive; if you doubled the system size, then this term would also double.
The simplest example of a generalized force and displacement is an actual force $F$ and displacement $x$ and the familiar equations $w=\boldsymbol{F\cdot x}$ and $dw=F\,dx$ for the work $w$. Another example is the pressure $P$ and volume $V$: $dw=-P\,dV$, with the minus sign appearing because pressure is compressive. Note how a gradient in pressure, the intensive variable, drives a shift in volume, the extensive variable. This effect is common for all of these pairs, whose units invariably multiply to give units of energy.
(This framework applies even to heating: the system energy $U$ increases with $T\,dS$, where gradients in temperature $T$ drive shifts in the entropy $S$. Here again, the units multiply to give units of energy.)
Yet another example of a conjugate pair is the stress and strain. Well actually, this isn't entirely true. If you look at the units, you'll see that the product of stress and strain has units of volumetric energy. So we can work with the elastic strain energy density or what you call above the strain energy function $W$, or we can work in terms of energy by multiplying by the volume, as in the fundamental relation for a first-order closed system under a general mechanical load: $dU=T\,dS+\boldsymbol{\bar{\sigma}} V\,d\boldsymbol{\bar{\epsilon}}$, where $\boldsymbol{\bar{\sigma}}$ and $\boldsymbol{\bar{\epsilon}}$ are the stress and strain tensors, respectively. (If the load is pressure, or equitriaxial compressive stress, then we recover the familiar $dU=T\,dS-P\,dV$.)
3. As for deriving your starred equation, I checked Nye's Physical Properties of Crystals and Ugural & Fenster's Advanced Strength and Applied Elasticity, and they proceed as you do: define the increase in strain energy from a uniaxial load applied to a differential element and then build up to the complete 3D case. For an isotropic material (which obeys generalized Hooke's Law), for example, Ugural & Fenster obtain a strain energy density of $$W=\frac{1}{2E}\left(\sigma_{x}^2+\sigma_{y}^2+\sigma_{z}^2\right)-\frac{\nu}{2E}\left(\sigma_{x}\sigma_y+\sigma_{y}\sigma_z+\sigma_{x}\sigma_z\right)+\frac{1}{2G}\left(\tau_{xy}^2+\tau_{yz}^2+\tau_{xz}^2\right).$$

A: Why the partial derivative of the strain energy with respect to strain components gives the stress components?
Because the volumetric density of elastic potential energy
(I bet that's what you call "strain energy function", I'll use the "$\Pi$" letter for it)
is a quadratic form over the deformation(strain) tensor $\boldsymbol{\varepsilon}$
$$\Pi = \frac{1}{2} \boldsymbol{\varepsilon} {\cdot\cdot} \boldsymbol{M} {\cdot\cdot} \boldsymbol{\varepsilon} = \frac{1}{2} \sum_{a,b,c,d} \varepsilon_{ab} M_{abcd} \varepsilon_{cd}$$
where the tetravalent tensor $\boldsymbol{M}$ with components $M_{abcd}$ is the tensor of elastic moduli (stiffness tensor).
Thus its derivative is
$$\frac{\partial \Pi}{\partial \boldsymbol{\varepsilon}} = \boldsymbol{\varepsilon} {\cdot\cdot} \boldsymbol{M}, \quad \frac{\partial \Pi}{\partial \varepsilon_{cd}} = \sum_{a,b} \varepsilon_{ab} M_{abcd}$$
The second derivative is just the stiffness tensor
$$\frac{\partial^2 \Pi}{\partial \boldsymbol{\varepsilon} \partial \boldsymbol{\varepsilon}} = \boldsymbol{M}, \quad \frac{\partial^2 \Pi}{\partial \varepsilon_{ab} \partial \varepsilon_{cd}} = M_{abcd}$$
— this can be taken as its definition. It is symmetric over pairs of indices $M_{abcd} = M_{cdab}$, plus inside each pair due to the symmetry of $\boldsymbol{\varepsilon}$: $M_{abcd} = M_{bacd}$, $M_{abcd} = M_{abdc}$
And there's also the Hooke's law in its most abstract formulation, saying that the stress tensor $\boldsymbol{\sigma}$ is equal to
$$\boldsymbol{\sigma}(\boldsymbol{\varepsilon}) = \boldsymbol{\varepsilon} {\cdot\cdot} \boldsymbol{M} , \quad \sigma_{cd} = \sum_{a,b} \varepsilon_{ab} M_{abcd}$$
Finally, here's the energy definition of what is the stress tensor
$$\boldsymbol{\sigma}(\boldsymbol{\varepsilon}) = \frac{\partial \Pi}{\partial \boldsymbol{\varepsilon}}$$
Does this equation hold for all elastic bodies? Or just linear elasticity?
Well, for finite strain theory there're many different measures of deformation(strain) and many different measures of stress. If you want something energy conjugate with the deformation gradient $\boldsymbol{F}$, take a look at the first Piola-Kirchhoff stress tensor $\boldsymbol{T}$, for that is
$$\boldsymbol{T} = \frac{\partial \Pi}{\partial \boldsymbol{F}}$$
(here $\Pi$ is still the volumetric density of elastic potential energy)
or you may want the second Piola-Kirchhoff stress tensor $\boldsymbol{S}$, which is energy conjugate with the Cauchy-Green deformation $\boldsymbol{C}$
$$\boldsymbol{S} = \frac{\partial \Pi}{\partial \boldsymbol{C}}$$


text:
Q: Using HTTP proxies for load balancing I am trying to use HTTP proxies to handle load balancing, but I'm not sure if it's wise to do so. My issue is that I need to have multiple private servers, serving through a load balancer, to multiple public IPs. I am using Amazon EC2s for my servers with elastic IPs.
My understanding of traditional load balancing, is that the resolving IP would be that of the server that the load balancer forwards to. If that is correct, I cannot use traditional load balancing, because each of my public IPs must appear unique to their attached domain. So if a reverse IP lookup occurred, it would not be easy to locate similar apps.
What kind of issues might this configuration face? Is there a better solution?
Thanks
EDIT: I am sharing some additional information, even though I have solved the issue, to perhaps help someone in the future.
Our situation is that we offer a service that is white labelled to each individual client. Our app is hosted on a singular server, with a singular IP. When new clients came aboard they would point a subdomain's @host at our server's IP.
The issue arose when you ping the domain, run a whois, or something that reveals the domain's IP. Since the IP was not unique to the domain, you could easily discover a list of domains using the app. With little effort you could use that domain list to find a list of clients.
Our solution was to stand up an EC2 and point an elastic IP per client. Which worked, until we found a need for load balancing.
I tried to configure Amazon's ELB to fit our needs, but I was unable to get a configuration that would utilize both the elastic IPs and the load balancer.
THE RESULT:
Our configuration now, is using an EC2 instance with Nginx configured to reverse proxy our set of app servers. The elastic IPs are tied to the Nginx load balancer instance that then forwards the request on to the corresponding app server.
It may not be the best configuration, but it suits our needs, and the latency difference is negligible.
Hope that clears things up, thanks again.

A: As @EEAA and @DiogenesdeLight suggested I used Nginx reverse proxies to achieve my desired outcome.
I used this Nginx configuration: http://devblog.daniel.gs/2014/01/deploying-node-apps-on-aws-ec2-with.html
So far it seems to work fabulously, and it took all of five minutes to configure.
Thanks for the support.


text:
Q: Create grouped UITableView with sections I am trying to create something that looks like this:

But the user will be able to add more rows to each section at runtime using a button in the section footer. How can I groups this?

A: go for given link it will clear your concept about grouped table view it given some great examples  https://github.com/StorminGorman/MultipleTableViewSectionsExample

A: You can achieve grouped table view with multiple sections using following third party library. I have used following library many times , this library easy to use and also provide easy customization.
https://github.com/LaurentiuUngur/LUExpandableTableView


text:
Q: Copy of an custom np.ndarray edits original I wrote a custom class which inherits from np.ndarray (simplified example), I want to create a copy of the array, modify it without destroying the original and return it as new instance of Custom class.
However when I run the code original array is altered exactly as it's copy.
class Custom(np.ndarray):

    def __new__(cls, array_like):
        obj = np.asarray(array_like, dtype=object).view(cls)
        return obj

    def __array_finalize__(self, obj):
        if obj is None:
            return

@dataclass
class Empty:
    """ Stores constants. """
    pass

@dataclass
class Values:
    """ Stores constants. """
    pass

class Cell:

    def __init__(self, value: Empty | Values):
        self.value = value

    def __repr__(self):
        return repr(self.value)

def modify(instance: Custom, move_from: tuple, move_to: tuple):
    new_instance = np.copy(instance)
    moving_cell = new_instance[move_from].value
    new_instance[move_to].value = moving_cell
    new_instance[move_from].value = Empty()
    return new_instance

custom_1 = Custom([[Cell(Empty()), Cell(Empty()), Cell(Empty())],
                   [Cell(Empty()), Cell(Values()), Cell(Empty())],
                   [Cell(Empty()), Cell(Empty()), Cell(Empty())]])
custom_2 = modify(custom_1, (1, 1), (0, 0))
print(custom_1)
print(custom_2)

Found the problem, i altered value of class Cell, which was not copied.

A: You can use copy library:
import copy
second_array = copy.copy(first_array)
second_array = copy.deepcopy(first_array)enter code here


text:
Q: Rails/ActiveRecord: Can I establish polymorphic relationships with tables with differing id types? Establishing a many to many polymorphic association is a real head twister. I've already spent the afternoon on this and I'm running out of energy.
I have two models, Comment and Project. I have a third model Badge. A user can react to a comment or project by adding a badge. Comments and projects will be reaction_targets.
I think I understand how to do the many to many polymorphic part. The trouble is Comment and Project have different id types. Comment is indexed by bigint whereas Project uses uuid.
My join table is called reactions through which Badge points to reaction_targets
    class Badge < ApplicationRecord
      has_many :reactions
      has_many :reaction_targets, through: :reactions
    end

Each row in the join table points to a badge and a target.
    class CreateReactions < ActiveRecord::Migration[5.2]
      def change
        create_table :reactions do |t|
          t.references :reaction_target, polymorphic: true
          t.references :badge
        end
      end
    end

I've established that the association with reaction_target is polymorphic.
    class Reaction < ApplicationRecord
      belongs_to :badge
      belongs_to :reaction_target, polymorphic: true
    end

I point Comment at the join table.
    class Comment < ApplicationRecord
      has_many :reactions, as: :reaction_target
      has_many :badges, through: :reactions
    end

Everything works correctly:
    > b = Badge.first_or_create(name: 'badge')
    > c = Comment.create
    > c.badges
    #=> []
    > c.badges << b
    #=> (0.2ms)  SAVEPOINT active_record_1...

However things are different when it comes to Project.
I establish the association in the same manner:
    class Project < ApplicationRecord
      has_many :reactions
      has_many :badges, through: :reactions
    end

But it doesn't work the same.
    > b = Badge.first_or_create(name: 'badge')
    > p = Project.create
    > p.badges
    #=> #<Badge::ActiveRecord_Associations_CollectionProxy:0x3fdc34cde54c>

The first thing I see is that #badges returns an object other than an empty array.
And when I try to add a badge to the collection, I get an error:
    (1.5ms)  SAVEPOINT active_record_1
    ActiveRecord::StatementInvalid: PG::InFailedSqlTransaction: ERROR:  current transaction is aborted, commands ignored until end of transaction block
    : SAVEPOINT active_record_1
    from /Users/123/.rvm/gems/ruby-2.6.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/postgresql/database_statements.rb:75:in `async_exec'
    Caused by PG::InFailedSqlTransaction: ERROR:  current transaction is aborted, commands ignored until end of transaction block
    from /Users/123/.rvm/gems/ruby-2.6.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/postgresql/database_statements.rb:75:in `async_exec'

I can see in schema.rb, reaction_target_id is expected to be a bigint.
      create_table "reactions", force: :cascade do |t|
        t.string "reaction_target_type"
        t.bigint "reaction_target_id"
        t.bigint "badge_id"
        t.index ["badge_id"], name: "index_reactions_on_badge_id"
        t.index ["reaction_target_type", "reaction_target_id"], name: "index_reactions_on_reaction_target_type_and_reaction_target_id"
      end

I assume the error above is because of that. Is it possible to establish polymorphic relationships with tables that have differing index types? If so, what do I need to do to be able to add badges to projects? If not, is there a workaround?

A: You're missing as: :reaction_target on the has_many :reactions association in Project.
class Project < ApplicationRecord
  has_many :reactions, as: :reaction_target
  has_many :badges, through: :reactions
end

This is what specifies the polymorphic association which you declared as reaction_target.


text:
Q: Want to display red-border on required form textfields if they are empty with bootstrap So as the title says I want to give my form textfield a red border if they are required and happen to be empty on submit. I searched the internet to see if i could find how to do that but with no success... I already added .required to my form control and it does display "This field is required" below the texfields but without the red border. Can someone tell me what i did wrong?
My code looks like this at the moment:
<form id="addEditDivisionForm" method="post">

                    @GlobalResources.Division *

                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control required" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                <input type="button" id="btnSaveDivision" value=" @GlobalResources.Save" class="btn btn-default" />

</form>

I want it to look something like this:
http://1000hz.github.io/bootstrap-validator/

A: I finally found what i was looking for. It was very simple i just had this code below to my CSS and the problem was fixed:

.form-control.error {
    border-color: #E74C3C;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}


text:
Q: Regarding the graph of $y = k^{2} x$ If I plot the graph of $y = k^{2} x$, I believe finding $k$ using the gradient of the graph and then squaring it will give me the gradient. But I'm not sure what I'm doing is right. Is there another method to find the gradient of the graph?
EDIT: For example, if I plot the graph of $y=k^{2}x$ using some data and the graphing software (Logger Pro) generates the gradient value as 3.14. So will that be my $k^{2}$ value or do I have to square the value of $k$ obtained to get the gradient?

A: I am not entirely sure what you are after. The gradient is defined as the slope at a specific point $p \in \mathbb R^n$ of a function $f: \mathbb R^n \to \mathbb R$.
$\begin{equation}
\text{grad}(f) = \nabla f: \mathbb R^n \to \mathbb R^n \\
\nabla f(p) = \begin{pmatrix}\frac{\partial f(p)}{\partial x_1}\cr\frac{\partial f(p)}{\partial x_2}\cr \vdots\cr\frac{\partial f(p)}{\partial x_n}\cr\end{pmatrix}
\end{equation}$
In your case this would be given by the total derivative since your function depends on the one dimensional variable $x$:
$\begin{equation}
\text{grad}(y)=\frac{\text{d}y}{\text {d}x}= k^2
\end{equation}
$
So there is no need for squaring the value you obtain.

A: Geometrically
Try to plot
$$y=3x$$
Moving one step out along $x$ adds 3 to $y$. Moving one more $x$ step adds 3 more to $y$. We say that the gradient or the slope of this graph is 3. Your plotting software will tell you that the gradient is 3 as well.
Then try to plot
$$y=10x$$
Again, 10 is the gradient. Your plotting software will tell you that. Now plot
$$y=k^2x$$
Naturally, to keep the pattern, $k^2$ is the gradient. Not $k$ but $k^2$. So the squaring is already included. If your plotting software in some specific case measures the gradient to be $3.14$, then this means that $k^2=3.14$.
Mathematically
Finding the gradient from a linear expression is a simple differentiation:
$$\text{gradient} =\frac{\mathrm d y}{\mathrm dx} =\frac{\mathrm d}{\mathrm dx} \left(k^2x\right)=k^2$$
Again we see that the gradient, the derivative of a first-order polynomial, which is a linear function, is $k^2$ and thus includes the squaring.


text: Q: Como puedo poner seguridad a las sesiones en php y mysql ya hice la parte de seguridad y si funciona pero el problema es que no se como hacer que reconozca que la persona ya inicio sesión y puede utilizar esa parte de la pagina perdon por no pner mas imagenes la pagina no me deja


text:
Q: GCC -Wdangling-pointer correct or bug? I ran into some code that builds a linked list on the stack and via destructors cleans up correctly AFAICT
Code:
#include <iostream>
#include <sstream>
#include <vector>

class TIntermNode {
  public:
    TIntermNode(const std::string& name, const std::vector<TIntermNode*>& children) : name(name), children(children) {
    };
    const std::string name;
    const std::vector<TIntermNode*> children;
};

class TIntermRebuild
{
  public:
    TIntermRebuild() {};
    virtual ~TIntermRebuild();
    void rebuild(TIntermNode &node);

  private:
    void traverseAny(TIntermNode &currNode);
    void traversePre(TIntermNode &currNode);
    void traverseChildren(TIntermNode &currNode);
    void traversePost(TIntermNode &currNode);

    void printStack(const char* msg);

    struct NodeStackGuard;

    template <typename T>
    struct ConsList
    {
        T value;
        ConsList<T> *tail;
    };

    ConsList<TIntermNode *> mNodeStack{nullptr, nullptr};
};

struct TIntermRebuild::NodeStackGuard
{
    ConsList<TIntermNode*> oldNodeStack;
    ConsList<TIntermNode*> &nodeStack;
    NodeStackGuard(ConsList<TIntermNode *> &stack, TIntermNode *str)
        : oldNodeStack(stack), nodeStack(stack)
    {
        nodeStack = {str, &oldNodeStack};
    }
    ~NodeStackGuard() { nodeStack = oldNodeStack; }
};

TIntermRebuild::~TIntermRebuild() {}

void TIntermRebuild::printStack(const char* msg)
{
    std::cout << msg;
    ConsList<TIntermNode*>* node = &mNodeStack;
    while (node) {
        if (node->value) {
            std::cout << node->value->name << "->";
        }
        node = node->tail;
    }
    std::cout << "(e)\n";
}

// PS: comment the next line out and the warning goes away
#define printStack(msg)

void TIntermRebuild::traversePre(TIntermNode &originalNode)
{
    printStack("traversePre before:");
    NodeStackGuard guard(mNodeStack, &originalNode);
    printStack("traversePre after:");
}

void TIntermRebuild::traversePost(TIntermNode &currNode)
{
    printStack("traversePost before:");
    NodeStackGuard guard(mNodeStack, &currNode);
    printStack("traversePost after:");
}

void TIntermRebuild::traverseChildren(TIntermNode &currNode)
{
    printStack("traverseChildren before:");
    NodeStackGuard guard(mNodeStack, &currNode);

    for (auto node : currNode.children)
    {
        traverseAny(*node);
    }
    printStack("traverseChildren After:");
}

void TIntermRebuild::traverseAny(TIntermNode &currNode)
{
    traversePre(currNode);
    traverseChildren(currNode);
    traversePost(currNode);
}

void TIntermRebuild::rebuild(TIntermNode &currNode)
{
    traverseAny(currNode);
}

int main()
{
    TIntermRebuild rebuild;

    TIntermNode grandChild1("grandChild1", {});

    TIntermNode child1("child1", {&grandChild1});
    TIntermNode child2("child2", {});

    TIntermNode root("root", {&child1, &child2});
    rebuild.rebuild(root);
}

To explain what's happening. At the bottom a singally linked list "stack" is started.
NodeStackGuard contains ConsList (oldNodeStack) and a reference to an existing ConsList. I copyes existing ConsList and then points the existing one to its copy. This way it builds up a singally  linked list on the stack. It's destuctor restores the previous ConsList so on exit it's back to the way it started.
The issue is, with -Wdangling-pointer GCC complains
Compiler stderr
In constructor 'TIntermRebuild::NodeStackGuard::NodeStackGuard(TIntermRebuild::ConsList<TIntermNode*>&, TIntermNode*)',
    inlined from 'void TIntermRebuild::traverseChildren(TIntermNode&)' at <source>:87:47:
<source>:47:19: warning: storing the address of local variable 'guard' in '*(TIntermRebuild::ConsList<TIntermNode*>*)((char*)this + 8).TIntermRebuild::ConsList<TIntermNode*>::tail' [-Wdangling-pointer=]
   47 |         nodeStack = {str, &oldNodeStack};
      |         ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
<source>: In member function 'void TIntermRebuild::traverseChildren(TIntermNode&)':
<source>:87:20: note: 'guard' declared here
   87 |     NodeStackGuard guard(mNodeStack, &currNode);
      |                    ^~~~~
<source>:87:20: note: '<unknown>' declared here

see here
As far as I can tell there's nothing wrong with the code above.
A pointer is made to a variable that exists on the stack but that pointer is deleted when the local variable is deleted so nothing is dangling AFAICT.
I'm am missing where the dangling pointer is? Is this a bug in GCC? Is there some quirk of C++ I'm unaware of that's being triggered here? Is this just a limitation of what's possible it check for and I need to disable the warning?
Note: there is printStack and there is a macro removing it
#define printStack(msg)

if I remove the macro so that printStack is actually used the warning goes away which seems to suggest this is a gcc bug?


text:
Q: How to keep a local committed change from being pushed(think IDE files) I'm working on a project where we use IDEA .ipr files and local property files to build and whatnot.  These files have locally relevant changes and paths in them, so I want to ensure they don't get committed back to the remote but I'd still like these files to be versioned so I can (except for this) have a fairly standard git workflow.
Is there any way to permanently mark a change or the ongoing changes to a file in a branch/repo as a 'local only' change that's never to be pushed?
At least based on my understanding adding these files to .gitignore wouldn't do what I want it to do.

A: If it is possible to move these files to a separate folder, you can use it as a submodule to keep track of local history. Otherwise, I don't know better way than cherry picking, but it's rather inconvenient.


text:
Q: Webscraping Code does not work for url/Please help in modifying code I have the below working that I have inherited.
import os
import pandas as pd
from selenium import webdriver
from tabulate import tabulate
from datetime import datetime
import time
from bs4 import BeautifulSoup as bs

start = datetime.now()
pd.set_option('display.max_rows', 5000)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

browser = webdriver.Chrome()

class GameData:

    def __init__(self):
        self.date = []
        self.time = []
        self.game = []
        self.score = []
        self.home_odds = []
        self.draw_odds = []
        self.away_odds = []
        self.country = []
        self.league = []

def parse_data(url):
    browser.get(url)
    df = pd.read_html(browser.page_source, header=0)[0]
    html = browser.page_source
    soup = bs(html, "lxml")
    cont = soup.find('div', {'id': 'wrap'})
    content = cont.find('div', {'id': 'col-content'})
    content = content.find('table', {'class': 'table-main'}, {'id': 'tournamentTable'})
    main = content.find('th', {'class': 'first2 tl'})
    if main is None:
        return None
    count = main.findAll('a')
    country = count[1].text
    league = count[2].text
    game_data = GameData()
    game_date = None
    for row in df.itertuples():
        if not isinstance(row[1], str):
            continue
        elif ':' not in row[1]:
            game_date = row[1].split('-')[0]
            continue
        game_data.date.append(game_date)
        game_data.time.append(row[1])
        game_data.game.append(row[2])
        game_data.score.append(row[3])
        game_data.home_odds.append(row[4])
        game_data.draw_odds.append(row[5])
        game_data.away_odds.append(row[6])
        game_data.country.append(country)
        game_data.league.append(league)
    return game_data

urls = {
    "https://www.oddsportal.com/soccer/england/premier-league/results/"
}

if __name__ == '__main__':

    results = None

    for url in urls:
        try:
            game_data = parse_data(url)
            if game_data is None:
                continue
            result = pd.DataFrame(game_data.__dict__)
            if results is None:
                results = result
            else:
                results = results.append(result, ignore_index=True)
        except ValueError:
            game_data = parse_data(url)
            if game_data is None:
                continue
            result = pd.DataFrame(game_data.__dict__)
            if results is None:
                results = result
        except AttributeError:
            game_data = parse_data(url)
            if game_data is None:
                continue
            result = pd.DataFrame(game_data.__dict__)
            if results is None:
                results = result
            else:
                results = results.append(result, ignore_index=True)

print(tabulate(results, headers='keys', tablefmt="github"))
end = datetime.now()
time_taken = end - start
print('Time taken to complete: ', time_taken)

|    | date              | time   | game                             | score   |   home_odds |   draw_odds |   away_odds | country   | league         |
|----|-------------------|--------|----------------------------------|---------|-------------|-------------|-------------|-----------|----------------|
|  0 | Yesterday, 11 May | 19:15  | Southampton - Crystal Palace     | 3:1     |        1.89 |        3.8  |        4.11 | England   | Premier League |
|  1 | Yesterday, 11 May | 17:00  | Manchester Utd - Leicester       | 1:2     |        3.72 |        3.58 |        2.07 | England   | Premier League |
|  2 | 10 May 2021       | 19:00  | Fulham - Burnley                 | 0:2     |        2.24 |        3.44 |        3.38 | England   | Premier League |
|  3 | 09 May 2021       | 18:00  | Arsenal - West Brom              | 3:1     |        1.5  |        4.53 |        6.76 | England   | Premier League |
|  4 | 09 May 2021       | 15:30  | West Ham - Everton               | 0:1     |        2.15 |        3.56 |        3.48 | England   | Premier League |

I now need to get similar data output for https://www.oddsportal.com/matches/soccer/
When I change the url to:
urls = {
    "https://www.oddsportal.com/matches/soccer/"
}

I am getting this error
Traceback (most recent call last):
  File "C:/Users/Harshad/AppData/Roaming/JetBrains/PyCharmCE2020.3/scratches/scratch_36.py", line 79, in <module>
    game_data = parse_data(url)
  File "C:/Users/Harshad/AppData/Roaming/JetBrains/PyCharmCE2020.3/scratches/scratch_36.py", line 48, in parse_data
    league = count[2].text
IndexError: list index out of range

I am completely new to scraping data from the web hence this newbie question on how I can modify this code to make it work.
Please help

A: Run len(count) to check the number of elements in count. It might have found only 1 element. So when you try count[2].text it gives the IndexError.


text:
Q: How to replace string in python string with specific character? for example, I have a column named Children in data frame of python,
few names are [ tom (peter)  , lily, fread, gregson (jaeson 123)]  etc.
I want to ask that what code I should write, that could remove part of each name staring with bracket e.g '(' and so on. So that from my given names example tom(peter) will become tom in my column and gregson (123) would become gregson.  Since there are thousands of names with bracket part and I want to remove the part of string staring from bracket '(' and ending on bracket ')'.  This is a data frame of many columns but i want to do this editing in one specific column named as CHILDREN  in my dataframe named DF.

A: As suggested by @Ruslan S., you can use pandas.Series.str.replace or you could also use re.sub (and there are other methods as well):
import pandas as pd
df = pd.DataFrame({"name":["tom (peter)" , "lily", "fread", "gregson (jaeson 123)"]})
# OPTION 1 with str.replace :
df["name"] = df["name"].str.replace(r"\([a-zA-Z0-9\s]+\)", "").str.strip()

# OPTION 2 :with re sub
import re
r = re.compile(r"\([a-zA-Z0-9\s]+\)")
df["name"] = df["name"].apply(lambda x: r.sub("", x).strip())

And the result in both cases:
      name
0      tom
1     lily
2    fread
3  gregson

Note that I also use strip to remove leading and trailing whitespaces here. For more info on the regular expression to use, see re doc for instance.

A: You can try:
#to remove text between ()
df['columnname'] = df['columnname'].str.replace(r'\((.*)\)', '')
#to remove text between %%
df['columnname'] = df['columnname'].str.replace(r'%(.*)%', '')


text:
Q: Properly insert breaks in titles on the profile's reputation page I was browsing a user's profile, when I saw this monstrosity:

In the screenshot, the first and third line look fine.
The last line looks okay-ish. I'm impartial if the title should break here, or that the timestamp should move to a newline.
The second line however just looks plain ridiculous, with it taking up 4 lines, where two would have sufficed, if the title would break at more logical points.
The div is defined as <div class="d-flex g4 p8 py2 md:p6 fw-wrap bb bc-black-075">
Removing fw-wrap produces this:

At a first glance, this has no negative impact on responsiveness, but I could of course be wrong.


text:
Q: Show that $\sum_{i=0}^\infty V_i$ is an ideal of $L$. In this paper On prime ideals of Lie algebras, the author proved this theorem:
Let $P$ be an ideal of $L$. Then the following conditions are equivalent:
(i) $P$ is a prime ideal of $L$.
(ii) If $[a,\left\langle b^{L}\right\rangle] \subseteq P$ for $a, b \in L$, then either $a \in P$ or $b \in P$.
(iii) If $[a, H] \subseteq P$ for $a \in L$ and an ideal $H$ of $L$, then either $a \in P$ or $H \subseteq P$.
(i) $\Rightarrow$ (ii). For each $a \in \mathcal{L}$
$$\left\langle a^L \right\rangle= \sum_{i=0}^\infty V_i \qquad \textit{where} \qquad V_0 = (a) \qquad \textit{and} \qquad V_i = \big[\ldots\big[(a),\underbrace{L\big],\ldots,}_i\ L\big].$$
My question is I how can prove that $\sum_{i=0}^\infty V_i$ is an ideal of $L$ and the smallest ideal containing $a$.
i.e
$$\left\langle a^L \right\rangle= \sum_{i=0}^\infty V_i$$

My attempt:

For each $a \in L$, $\langle a^L \rangle$ is defined to be the smallest ideal of $L$ containing $a$. It must contain $a$, and all its scalar multiples, i.e. the $1$-dimensional $F$-vector subspace $(a) := F a \subset \langle a^L \rangle$. But if it contains $(a)$, then (by definition of ideal) it must also contain $[(a),L]$, and hence $[[(a),L],L]$, etc. Because it is a $F$-vector space it must contain their sum.
Therefore, $$\left\langle a^L \right\rangle \supseteq \sum_{i=0}^\infty V_i$$
Conversely, Let $x \in \sum_{i=0}^\infty V_i$ and $y \in L$, then $x \in (a)+[(a),L]+[[(a),L],L]+...$.
Thus $[x,y] \in [(a),L]+[[(a),L],L]+...$.
Therefore, $[x,y] \in \sum_{i=0}^\infty V_i$, hence $\sum_{i=0}^\infty V_i$ is an ideal containing $a$, so it contains $\left\langle a^L \right\rangle$.

A: Your proof of both inclusions looks good to me. To be very precise, one could make it clear that all actual sums in that infinite sum are actually finite, and mention that $\sum V_i$ is (of course) also a sub-vector space, but I would accept it as written.


text:
Q: Calculating intersections of a "2D cone" and segments Setup
Consider the following diagram:

The "2D cone" with origin A separates the 2D plane into 2 regions, inside and outside.
Consider the 4 representative edges $c, d, e, f$ that encompass all intersection cases (assume that an edge aligned with the cone's boudary is equivalent to $e$).
An edge is either fully inside the cone, has one end point inside and one outside, has both end points outside but a subset of its interior is inside, is fully outside.
We are looking for the points of intersection of the cone $A$ with each edge. For $c$ it would be  the rightmost end point and the point of intersection of the cone's edge with the segment, for $e$ it would be the 2 endpoints of the segment, for $f$ no intersection point exists, for $d$ it's the 2 points where the boundary of the cone intersects the interior of $d$.
Problem
With this setup here is the practical problem:
The cone $A$ is defined by an origin $A$ and 2 directions $d_1, d_2$. Each segment is defined by its 2 end points $p_1, p_2$.
Given an arbitrary cone, with inner angle less than $\pi$ and an arbitrary segment, use nothing but vector algebra to find the 2 intersection points. If no intersection is possible, identify it somehow, encoded numerically in the 2 points. You can assume the directions $d_1, d_2$ are always given to you in clockwise order.
Current approach
My current approach is to, grab the 2 end points of the segment, check their angled sign relative to the window (which is done through the dot product of 2 cross products). With the signed angles of each end point I identify whether the point is inside or outside the window. A point is in the interior iff $0 < \sigma < w$ where $\sigma, w$ are the signed angle of the point with respect to the rightmost edge of the cone and $w$ is the angle of the cone.
With that information I can decide which of the 4 cases I am actually in, then make the decisions with that assumption.
e.g If only one of the 2 endpoints is in the interior I know for a fact there is a unique point of intersection with one of the 2 boundaries, so figure out which one it is and then I know the 2 intersection points.
This is overly convoluted. I am curious if there is a more unified way that can find both intersection points without having to create a big tree of if else's

A: Here is an approach that avoids dividing into cases as well as any trigonometry. Suppose that the directions $d^1 = (d^1_1,d^1_2)$ and $d^2 = (d^2_1,d^2_2)$ are given in clockwise order. Rotate these vectors by $90^\circ$ clockwise and counterclockwise respectively to product
$$
l = (d_2^1,-d^1_1), \quad r = (-d^2_2, d^2_1).
$$
A point $x = (x_1,x_2)$ will lie within the cone if and only if it satisfies $x \cdot l \geq 0$ and $x \cdot r \geq 0$, where $v \cdot w$ denotes the dot-product of vectors $v$ and $w$.  More specifically, we have $x \cdot l \geq 0$ iff $x$ lies to the "right" of the "left-side" boundary, and $x \cdot r \geq 0$ iff $x$ lies to the "left" of the "right-side" boundary.
We are given two endpoints $p^1 = (p^1_1,p^1_2)$ and $p^2 = (p^2_1,p^2_2)$.  The line connecting these points is the set of all points
$$
p(t) = (1-t)p^1 + tp^2
$$
with $t \in \Bbb R$. Note that $p(t)$ is on the line segment connecting the two points when $0 \leq t \leq 1$. Moreover, $p(0) = p^1$ and $p(1) = p^2$.
We now find the "times" $t$ at which this line crosses either of the boundaries. That is, we solve
$$
l \cdot p(t_l) = 0 \implies (1-t_l)(l \cdot p^1) + t_l(l \cdot p^2) = 0 \implies t_l = \frac{l \cdot p^1}{(l \cdot p^1) - (l \cdot p^2)},\\
l \cdot p(t_r) = 0 \implies (1-t_r)(l \cdot p^1) + t_r(l \cdot p^2) = 0 \implies t_r = \frac{r \cdot p^1}{(r \cdot p^1) - (r \cdot p^2)}.
$$
If either of these numbers satisfy $0 \leq t \leq 1$, plug into $p(t)$ to produce the associated point.
The only case not accounted for here is division by zero, which occurs when the line segment is parallel to one of the boundaries.


text:
Q: Why does the swift compiler think the closure is trailing? I'm attempting to declare a void returning closure and use it immediately following another expression. So I realize the compiler doesn't 'see' the whitespace but why does it think someFunc has a closure argument when it clearly doesn't? In other words why is the ; necessary?
func someFunc() {

}

func someFunc2() {
    someFunc();

    { arg in
        print("\(arg + 1)")
    }(0)
}

When the semicolon is removed xcode gives the error "Argument passed to call that takes no arguments". Is this really according to design?

A: f { /* closure contents here */ } is the more common form of a trailing closure, but the brackets don't necessarily have to be omitted (in fact, they're necessary if there are other parameters before the closure), which means that f() { /* closure contents here */ } is also a valid trailing closure.
Some people like their starting { in a new line (I know this is the convention in C#, for example), so this behaviour you're seeing looks like it's meant to accommodate such people.

A: You say that "I'm attempting to declare a void-returning closure".  but you didn't declare closure in function return
So the changes are:-
func someFunction() {
    print("Some function is call")
}

func someFunction2() -> ((_ arg: Any) -> Void) {
    someFunction()

    return { arg in
        print("Closure return")
    }
}


text:
Q: Is this mapping from a hypercube into a Banach space of continuous functions itself continuous? Let $d, n \in \mathbb{N}$. Moreover, let $D \subset \mathbb{R}^d$ be compact and denote with
$\mathcal{C}(D, \mathbb{R}^n) $
the set of continuous functions from $D$ to $\mathbb{R}^n$. Then $\mathcal{C}(D, \mathbb{R}^n) $ is a Banach space with the usual maximum norm $\lVert f\rVert_{\infty} := \max_{x \in D} \lVert f(x) \rVert $.
Now choose $K>0$ and $l \in \mathbb{N}$. The map
$$ j : [-K,K]^l \rightarrow \mathcal{C}(D, \mathbb{R}^n) $$
$$ j(\theta) = \Phi_{\theta} $$
parametrizes a family of continuous functions $\Phi_{\theta}$ in such a way that, for each fixed $x  \in D$, the map
$$h_x : [-K,K]^l \rightarrow \mathbb{R}^n $$
$$h_x(\theta) = \Phi_{\theta}(x) $$
is continuous in $[-K,K]^l$ and continuously differentiable in $(-K,K)^l$.
From this, I want to conclude that $j$ is continuous. Is this true? If not, what additional assumptions would make this true?
I have tried using the sequence criterion of continuity for $j$, i.e. $\theta_n \rightarrow \theta$ should imply that $j(\theta_n) \rightarrow j(\theta)$. I then tried to show $j(\theta_n) \rightarrow j(\theta)$ by making use of the multidimensional mean-value theorem, but so far I have not been successful.
I am grateful for any advice!
Kind regards and thank you very much,
Joker


text:
Q: How to find out if the "TextChanged" event is fired if user is typing into a textbox or myTextBox.Text is called programmatically
Is there a way to find out if the "TextChanged" event is fired because

*

*the user is typing into a textbox or

*the programmer called myTextBox.Text = "something"?

Just to give you some color on this, I don't want to react when the user is typing each letter into the textbox so I am using the "Validated" event to catch when the user is done so I can react. The problem is I don't have a way to catch when the programmer does "myTextbox.Text = "something". The only way I know to catch changes there is to use TextChanged but then I don't want to be reacting when the user is typing each letter into the textbox. Any suggestions?

A: So in your "Formatted" Textbox class:
public override String Text{
   get{return text;}
   set
   {
      //perform validation/formatting
      this.text = formattedValue;
   }

this should allow you to format the text when it is changed by a programmer, the user input validation will still need to be handled in the validating event.

A: I will guess that you're creaing a UserControl that other developers will use, thus "end-user" programmers may set the text programmatically. I think the simplest thing would be to follow @jzworkman's suggestion and make a class that overrides the Text property setter. As @vulkanino notes, you should probably raise and catch the Validating event, though.
public class TextBoxPlus : TextBox {
    public event CancelEventHandler ProgrammerChangedText;
    protected void OnProgrammerChangedText(CancelEventArgs e) {
        CancelEventHandler handler = ProgrammerChangedText;
        if (handler != null) { handler(this, e); }
    }

    public override string Text {
        get {
            return base.Text;
        }
        set {
            string oldtext = base.Text;
            base.Text = value;
            CancelEventArgs e = new CancelEventArgs();
            OnProgrammerChangedText(e);
            if (e.Cancel) base.Text = oldtext;
        }
    }
}

In your source, add the same handler to both the Validating and ProgrammerChangedText events:
// Somewhere...
textBoxPlus1.Validating += textBoxPlus1_Validating;
textBoxPlus1.ProgrammerChangedText += textBoxPlus1_Validating;

void textBoxPlus1_Validating(object sender, CancelEventArgs e) {
    decimal d;
    if (!Decimal.TryParse(textBoxPlus1.Text, out d)) {
        e.Cancel = true;
    }
}

A: // This is the manual way, which is an alternative to the first way.
// Type 'this.TextChanged += ' into your form's constructor.
// Then press TAB twice, and you will have a new event handler.
this.TextChanged += new EventHandler(textBox1_TextChanged);

void textBox1_TextChanged(object sender, EventArgs e)
{
    //put the logic here for your validation/requirements for validation
    // ex.  if (textbox1.Text=="something") {//don't validate}
    //
}

A: If you want to perform validation, use the Validating event, not the Validated (which comes when it is too late to act).
That said, what's the real need here?

The Validating event is supplied an object of type CancelEventArgs. If
  you determine that the control's data is not valid, you can cancel the
  Validating event by setting this object's Cancel property to true. If
  you do not set the Cancel property, Windows Forms will assume that
  validation succeeded for that control, and raise the Validated event.

(http://msdn.microsoft.com/en-us/library/ms229603.aspx)


text:
Q: Showing all taxonomies for a certain post in a WP loop this might be a simple question but I just can't get my hands around it.
I have a WP_query listing of custom post type in wordpress, and I need to have an appropriate taxonomies (categories) displayed for each one of those items in the list.
I tried googling and searching through stackoverflow but came up short.
Also, this is what I'm using for displaying all the taxonomy slugs that exist for a certain post type:
function get_taxonomy_classes($theID) {

        $post_type  = get_post_type($theID);
        $taxonomies = get_object_taxonomies($post_type, 'objects');

        $terms = get_terms($taxonomies, array(
            'orderby' => 'name',
            'order' => 'ASC',
            'hide_empty' => TRUE
        ));
        foreach($terms as $term) {
            echo $term->slug . " ";
        }

    }

Still haven't found a way to use those terms with taxonomies above :(
Please help, thank you!

A: Nevermind, guys. I found an answer myself.
It's pretty simple, you just need wp_get_object_terms() function
   $termss = wp_get_object_terms(get_the_ID(), 'portfolio_category');
   foreach ($termss as $term) {
      echo $term->slug;
   }


text:
Q: How To Have One Input Be Reused And Add To A List In Python 3.x.x I'm trying to create a program that will add numerical inputs into an array and then find the sum of. I would prefer typing every number individually and then looping back to the input and adding it all to a list when the user is finished, but it seems like typing out 3, 3, 3, 3 would be easier. I also want a custom amount of numbers on the list ex. 32, 3, 5. And then the next time maybe 52, 3, 3, 22. How would I add this function?
I have tried using define functions to loop back to the start and also loops. I have tried to put 1, 1, 1 into the input. I have also tried changing it to a string.
numberarrayinput = 0
while not numberarrayinput == -100:
     numberarrayinput = int(input("Enter In Your Numbers One By One. Type -100 If You Are Done.\n"))
numberlist = []
numberlist = [numberarrayinput]
print(numberlist)
arraytotal = sum(numberlist)

I expected the output of 3,3,3,3 to return and print 23 at the end, but, I get an invalid literal error for int(). I do not know how to create a new list value so if I input just 5 it will return 5.

A: numberarrayinput = 0
numberlist = []
while not numberarrayinput == -100:
    numberlist.append(numberarrayinput)
    numberarrayinput = int(input("Enter In Your Numbers One By One. Type -100 If You Are Done.\n"))
print(numberlist)
arraytotal = sum(numberlist)
print(arraytotal)

Is this what you're looking for?
The problem is you weren't appending new values to your array. only the last number you entered, which in your case is always -100;


text:
Q: Custom Payment IPN notify_url On my website I'm using a custom PayPal checkout form and one of the elements in the form is:
input name="notify_url" type="hidden" value="http://www.example.com/ipn.php"

On actual PayPal I have my real ipn link, but could I route this to another ipn?
For example, let's say under my PayPal settings my ipn is: http://www.example.com/ipn_1.php
Can I set this link to say: http://www.example.com/ipn_2.php and then receive payment notifications at ipn_2.php instead of ipn_1.php like it says in my merchant settings?

A: Yes, when you use notify_url that will override what you have in your PayPal profile so it would hit that IPN URL instead.


text:
Q: Reemplazar una imagen por otra PHP y MYSQLI Tengo mi código para editar imágenes en mi base de datos, pero a la hora de reemplazar la imagen en la carpeta o la ruta dónde se guarda no las reemplaza, sino añade una nueva.
Dejo imagen a continuación:

La imagen que está subrayada en amarillo es la que quiero reemplazar. Y la imagen  que está subrayada con gris es la nueva imagen. Pero en vez de reemplazar la imagen vieja por la nueva solo la agrega y ya.
Éste es mi código:
<?php
session_start();

$conexion = mysqli_connect("localhost", "root", "", "trigoyponque2017");

$id             = $_GET['id'];
$titulo         = $_POST['titulo'];
$descripcion    = $_POST['descripcion'];

$foto1   = $_FILES["foto"]["name"];
$foto    = rand(0,9).rand(100,9999).rand(100,9999).".".$foto1;
$ruta    = $_FILES["foto"]["tmp_name"];
$destino = "../productos/".$foto;
move_uploaded_file($ruta,$destino);

if($_FILES["foto"]["name"]){
    $editar   = "UPDATE producto SET titulo= '$titulo', descripcion = '$descripcion', foto = '$foto' WHERE id= '$id'";
    echo "<script> alert ('Producto actualizado correctamente.'); window.location='editar_producto1.php?id=$id' </script>";
}else{
    $editar   = "UPDATE producto SET titulo= '$titulo', descripcion = '$descripcion' WHERE id= '$id'";
    echo "<script> alert ('Producto actualizado correctamente.'); window.location='editar_producto1.php?id=$id' </script>";
}

$resultado = mysqli_query($conexion,$editar);

if(!$resultado){
    echo "<script> alert('Error.'); window.location='editar_producto1.php?id=$id'</script>";
}else{
    echo "<script> alert('Producto actualizado correctamente.'); window.location='editar_producto1.php?id=$id'></script>";
}

mysqli_close($conexion);
?>

PD: Cabe aclarar que estoy guardando las fotos con números random como una especia de ID.
Imagen en Base de datos:

A: Eso pasa por que en ningún momento estas cambiando la foto en la carpeta nueva, siempre la estas añadiendo, entonces debes primero seleccionar la foto actual, eliminarla y ahí si seguir con tu flujo normal, algo así:
$foto1   = $_FILES["foto"]["name"];
$foto    = rand(0,9).rand(100,9999).rand(100,9999).".".$foto1;
$ruta    = $_FILES["foto"]["tmp_name"];
$destino = "../productos/".$foto;

$selecionar = "SELECT foto FROM producto WHERE id = '$id'";
$resultado_seleccionar = mysqli_query($conexion, $selecionar);

$foto_db = mysqli_fetch_array($resultado_seleccionar);
$ruta_foto_db = "../productos/" . $foto_db['foto'];

if(file_exists($ruta_foto_db)){
    unlink($ruta_foto_db);
}

if (!file_exists($destino)) {
    move_uploaded_file($ruta,$destino);
}

if($_FILES["foto"]["name"]){
    $editar   = "UPDATE producto SET titulo= '$titulo', descripcion = '$descripcion', foto = '$foto' WHERE id= '$id'";
    echo "<script> alert ('Producto actualizado correctamente.'); window.location='editar_producto1.php?id=$id' </script>";
}else{
    $editar   = "UPDATE producto SET titulo= '$titulo', descripcion = '$descripcion' WHERE id= '$id'";
    echo "<script> alert ('Producto actualizado correctamente.'); window.location='editar_producto1.php?id=$id' </script>";
}


text:
Q: Ubuntu 18.04 LTS - Battery stuck on 'estimating' I recently installed Ubuntu (today, actually!) from Windows 10 and I've been loving it so far. I'm currently on an HP Spectre x360 and the battery's status is stuck on "Estimating..". Occasionally it would give me the correct percentage after waiting for a long period of time or when charging. Is there anything I can do?
Update: Opening Power Statistics has 'forced' the Estimating status to go away and now displays the power. Why is this?


text:
Q: Modify Bluemix nodejs buildpack I'm looking to modify the NodeJS Buildpack in Bluemix. I want to run a nodeJS runtime with Java in it. Has anyone tried this before?
I found this buildpack, running nodeJS and Java 8. I tried to build from the buildpack but it doesn't seem to work
cf push <app_name> -b https://github.com/syahrul-aiman/nodejs-java-buildpack -s cflinuxfs2
I want to add java because I have a JAR file that will perform file merging operations triggered by my nodeJS apps.
Downloading and installing node 0.12.11...
Downloaded [https://pivotal-buildpacks.s3.amazonaws.com/concourse-binaries/node/node-0.12.11-linux-x64.tgz]
Using default npm version: 2.14.9
Downloading JAVA [http://download.oracle.com/otn-pub/java/jdk/8u73-b02/jdk-8u73-linux-x64.tar.gz]
Download complete!
Installing JAVA
Download complete!
Installing Maven
Downloading CF CLI [https://cli.run.pivotal.io/stable?release=linux64-binary&source=github]
Installation complete!
Download complete!


text:
Q: How to get Format Image from cordova/phonegap used getPicture From Gallery in Android? Hy guys,
i have some question about get format picture from galery used plugin phonegap/cordova. in ios, i do not have to get format, but in android i should getting format picture, example .png / .jpg / .gif.
In my code I set :

navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
}, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM
});
}

function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
if (device.platform == "Android" || device.platform == "android") {
 options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
}
options.mimeType = "image/jpg";
var user = Storage.getObject("user");
var params = new Object();
options.params = {
 user_id: parseInt(user.id)
}
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://www.exampl.com/app/upload-receiptPhotoLibrary", win, fail, options);
}

option.filename not result file with format file, how to get format file in option.filename ?

A: You need to check the mime type
var sFile = new MediaFile("some.jpg", "file:///mnt/sdcard/some.jpg");
console.log("file path = " + sFile.fullPath);
sFile.getFormatData(function(metadata) {
    console.log("mimeType = " + metadata.type);
}, function() {
    console.log("fail");
});


text:
Q: R matrix partition and concat How can I concat the matrix in R?
I have some large matrix with:
> dim(land)
[1] 1760  880

I want something like:
A B C D
E F G H

Split in two and concat to get:
C D A B
G H E F

A: Try this:
#reproducible matrix
land <- as.matrix(read.table(text="A B C D
                                E F G H"))
#output
cbind(land[,(ncol(land)/2+1):ncol(land)],
  land[,1:(ncol(land)/2)])

#      V3  V4  V1  V2
#[1,] "C" "D" "A" "B"
#[2,] "G" "H" "E" "F"