text:
Q: How to delete objects inside an object using an array? (React.js Reducer ) Example of the data (useContext)
data: {
  projects:{
    'project-1':{
      name: 'project-1',
      columnIds:['column-1', 'column-2'],
    },
    'project-2':{
      name: 'project-2',
      columnIds:['column-3'],
    },

  },
  columns:{
    'column-1':{
      title: 'column-1',
      content: 'abc',
    },
    'column-2':{
      title: 'column-2',
      content: 'def',
    },
    'column-3':{
      title: 'column-3',
      content: 'ghi',
    },
  },
}

If I delete the project-1 which has column-1 and column-2, it should also be deleted inside the columns object. So the result should be:
data: {
  projects:{
    'project-2':{
      name: 'project-2',
      columnIds:['column-3'],
    },

  },
  columns:{
    'column-3':{
      title: 'column-3',
      content: 'ghi',
    },
  },
}

I already know how to remove project-1 object but I'm stuck in removing the column-1 and column-2.
This was my code for removing column-1 and `column-2 data:
let newColumn = data.projects[projectname].columnIds.map((item) =>
  Object.keys(data.columns).filter((key) => key !== item)
);

A: You just need to check if there are corresponding column IDs before you delete the property. If there are, iterate over the IDs and delete the columns:

const data = {
  projects: {
    'project-1': {
      name: 'project-1',
      columnIds: ['column-1', 'column-2'],
    },
    'project-2': {
      name: 'project-2',
      columnIds: ['column-3'],
    },

  },
  columns: {
    'column-1': {
      title: 'column-1',
      content: 'abc',
    },
    'column-2': {
      title: 'column-2',
      content: 'def',
    },
    'column-3': {
      title: 'column-3',
      content: 'ghi',
    },
  },
}
const key = 'project-1'
const { columnIds } = data.projects[key]
if (columnIds.length > 0) {
  columnIds.forEach(id => {
    delete data.columns[id]
  })
}
delete data.projects[key]

console.log(data)

You can also create a copy of the object so you don't mutate the original one:

const data = {
  projects: {
    'project-1': {
      name: 'project-1',
      columnIds: ['column-1', 'column-2'],
    },
    'project-2': {
      name: 'project-2',
      columnIds: ['column-3'],
    },

  },
  columns: {
    'column-1': {
      title: 'column-1',
      content: 'abc',
    },
    'column-2': {
      title: 'column-2',
      content: 'def',
    },
    'column-3': {
      title: 'column-3',
      content: 'ghi',
    },
  },
}

function deleteColumns(obj, key) {
  const copy = {
    projects: { ...obj.projects },
    columns: { ...obj.columns }
  }
  const { columnIds } = copy.projects[key]
  if (columnIds.length > 0) {
    columnIds.forEach(id => delete copy.columns[id])
  }
  delete copy.projects[key]
  return copy
}

const afterDelete = deleteColumns(data, 'project-1')

console.log(afterDelete)
console.log(data)


text:
Q: Form - new page on submit button Last year i build a form for one of our costumers, when visitors submitted the form they
got a message on the same page. But now he asks me if it is possible to
make a succes page if the form is filled in correctly.
I can't make it work. It's a bit out of my league.
So i hope anyone of you can help me out!
$(document).ready(function() {

    $("#ajax-contact-form").submit(function() {
        $('#load').append('');

        var fem = $(this).serialize(),
            note = $('#note');

        $.ajax({
            type: "POST",
            url: "contact/contact2.php",
            data: fem,
            success: function(msg) {
                if ( note.height() ) {
                    note.slideUp(500, function() { $(this).hide(); });
                }
                else note.hide();

                $('#loading').fadeOut(300, function() {
                    $(this).remove();

                    // Message Sent? Show the 'Thank You' message and hide the form
                    result = (msg === 'OK') ? '
Uw bericht is verzonden, we nemen z.s.m. contact met u op!
' : msg;

                    var i = setInterval(function() {
                        if ( !note.is(':visible') ) {
                            note.html(result).slideDown(500);
                            clearInterval(i);
                        }
                    }, 40);
                }); // end loading image fadeOut
            }
        });

        return false;
    });

    <form id="ajax-contact-form" target="_blank" method="post" action="javascript:alert('success!');" >

A: Just redirect to success page after ajax success.

A: Instead of displaying the "success" message, redirect to a new page:
window.location = successPageUrl;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Checking for Minimum Value in column, and copying all the data after that minimum value So I'm still working on pulling and analyzing data from the same sheets that I've asked about before, but I've been asked to re-evaluate my approach.
Refer to here for a bit of a background on what I am doing: Setting Excel Worksheet to a Variable, and calling the variable in a different sub
Now I have to find the minimum value that can be found in my column, and then copy all the data in that column that appears after it.
Here is the code I currently have:
Public Path As String
Public Counter As Integer
Public NameFile As Workbook
Public Celltxt As String 'Checks cell value in D2, used to compare to Strings to confirm part type
Public MyFolder As String 'Path collected from the folder picker dialog
Public MyFile As String 'Filename obtained by DIR function
Public wbk As Workbook 'Used to loop through each workbook
Public thisWb As Workbook
Public MasterFile As String
Public Min As Variant

Sub Consolidate_Diagramms_Data()

Dim wb As Workbook

Dim TestStr As String

TestStr = ""

TestStr = Dir("C:\DataAnalyzation\Consolidated Diagramm Data.xlsx")

Application.DisplayAlerts = False

If TestStr = "" Then

    Set NameFile = Workbooks.Add

    NameFile.SaveAs Filename:="C:\DataAnalyzation\Consolidated Diagramm Data.xlsx"

    Range("A1").Value = "Part Number"

    Range("B1").Value = "Date"

    Range("C1").Value = "Time"

    Range("D1").Value = "Part Type"

    Range("E1").Value = "Comment"

    Range("F1").Value = "Zero"

    Else

    Workbooks.Open Filename:="C:\DataAnalyzation\Consolidated Diagramm Data.xlsx"

    Range("A1").Value = "Part Number"

    Range("B1").Value = "Date"

    Range("C1").Value = "Time"

    Range("D1").Value = "Part Type"

    Range("E1").Value = "Comment"

    Range("F1").Value = "Zero"

End If

MasterFile = "C:\DataAnalyzation\Consolidated Diagramm Data.xlsx"

Call AllWorkbooks

End Sub

Sub AllWorkbooks()

Dim LastRow As Long

Dim minRange As Variant

Set thisWb = ActiveWorkbook

'On Error Resume Next

Application.ScreenUpdating = False 'Opens the folder picker dialog to allow user selection

MsgBox "Please select the folder from which you wish to consolidate your data."

With Application.FileDialog(msoFileDialogFolderPicker)

.Title = "Please select a folder"

.Show

.AllowMultiSelect = False

   If .SelectedItems.Count = 0 Then 'If no folder is selected, abort

MsgBox "You did not select a folder"

      Exit Sub

   End If

MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder

End With

Counter = 0

LHCounter = 0

RHCounter = 0

FeedshaftCounter = 0

MyFile = Dir(MyFolder) 'DIR gets the first file of the folder

'Loop through all files in a folder until DIR cannot find anymore

Do While MyFile <> ""

    LastRow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1).Row

    Counter = Counter + 1

    Set wbk = Workbooks.Open(Filename:=MyFolder & MyFile)

Application.ScreenUpdating = False

EventState = Application.EnableEvents
Application.EnableEvents = False

CalcState = Application.Calculation
Application.Calculation = xlCalculationManual

PageBreakState = ActiveSheet.DisplayPageBreaks
ActiveSheet.DisplayPageBreaks = False

    'Copy Part Number, Date, Time, Part Type, and Comment

    Workbooks(MyFile).Activate 'Activates the Data Sheet

    If Range("B1").Value = "" Then

        GoTo Nd

    End If

    ActiveSheet.Range("A2:E2").Copy 'Copies the Part Number, Date, Time and Part Type

    'Paste Part Number, Date, Time, Part Type, and Comment

    Workbooks("Consolidated Diagramm Data.xlsx").Activate 'Activates the final Workbook

    Range("A" & LastRow).PasteSpecial Paste:=xlPasteAll 'Pastes the Date into "A2"

    Application.CutCopyMode = False

    'Copy Force

    Workbooks(MyFile).Activate

    Range("D4").Activate

    minRange = Application.WorksheetFunction.Min(Sheets(1).Range("D4:D500"))

    minRange.Activate

    ActiveCell.End(xlDown).Copy

    Workbooks("Consolidated Diagramm Data.xlsx").Activate

    Range("F" & LastRow).Activate

    ActiveCell.PasteSpecial Paste:=xlPasteAll, Transpose:=True

    Application.CutCopyMode = False

    GoTo Nd

    'End of Copy/Paste coding

Nd:

wbk.Close savechanges:=False

MyFile = Dir 'DIR gets the next file in the folder

Loop

Application.DisplayAlerts = True

Application.ScreenUpdating = True

MsgBox ("A total of " & Counter & " files have been consolidated.")

End Sub

The problem that I am running into is that I cannot seem to be able to find the minimum value, activate that cell, and copy all the data in that column that follows after it.
At the lines:
    minRange = Application.WorksheetFunction.Min(Sheets(1).Range("D4:D500"))

    minRange.Activate

I am getting a "Runtime Error '424': Object Required" fault.
Below is the updated portion of my code where I'm searching for the minimum value. I'm currently getting a "Run-time 1004: Unable to get the Match property of the WorksheetFunction class".
Workbooks(MyFile).Activate

    Range("D4").Activate

    Set myRng = Range("D4:D" & Rows.Count)

    minValue = Application.WorksheetFunction.Min(myRng)

    myRow = Application.WorksheetFunction.Match(minValue, myRng, 0)

    Range(myRow, myRng).Activate

    ActiveCell.End(xlDown).Copy

    Workbooks("Consolidated Diagramm Data.xlsx").Activate

    Range("F" & LastRow).Activate

    ActiveCell.PasteSpecial Paste:=xlPasteAll, Transpose:=True

    Application.CutCopyMode = False

    GoTo Nd

A: The following will give you the row of the minimum value (assuming there is only one):
Dim myRng As Range
Dim myRow as Long
Dim minValue as Long
Set myRng = Range("A1:A" & Rows.Count)
minValue = Application.WorksheetFunction.Min(myRng)
MyRow = Application.WorksheetFunction.Match(minValue, myRng, 0)


text:
Q: Switch from TabBarView back to Standard View I have implemeneted an application where you login, and once you log in it brings you to a tab bar view. However, I want to implement a log out button where when the user pushes the button it brings them back to the login view.
I have the following code right now, but it dosn't work. The UIBarButton is being invoked, because its producing NSLog output to gdb. However it dosn't switch the views.
In my view for the tab bar.
- (IBAction) logoutButtonPushed {
    NSLog(@"Yes, I was pushed");
    [self.appdelegate logout];
}

Then in my app delegate.
//  Logout and return to the welcome view
- (void) logout {

    [self.tabBarViewController.view removeFromSuperview];
    [window addSubview:self.welcomeViewController.view];
    [window bringSubviewToFront:self.welcomeViewController.view];

    [userModel logout];
}

Just for kicks, here is how I bring the tab bar to the front.
//  Switches to the tab bar view from either the welcome or registersuccess view
- (void) switchToTabBarView {

    [self.registerSuccessViewController.view removeFromSuperview];
    [self.welcomeViewController.view removeFromSuperview];
    [window addSubview:self.tabBarViewController.view];
    [window bringSubviewToFront:self.tabBarViewController.view];

}

Any help, or suggestions to improve my code (I probably have many a bad practice) would be welcomed. Thanks!

A: Refer to my answer for this question.
You should not use self, because it won't refer to the tabbar controller. Instead of self, use the instance of the view controller where you placed your tabbar controller
In AppDelegate.h
YourViewController *yourViewControllerObj;
@property(nonatomic,retain) YourViewController *yourViewControllerObj;

In AppDelegate.m
@synthesize yourViewControllerObj;

In YourViewController.m, set object for your AppDelegate instance:
- (void)viewDidLoad
{
    appDelegate.yourViewControllerObj = self;
    // Do whatever you want
}

then in your logout function
- (IBAction) logoutButtonPushed {
  NSLog(@"Yes, I was pushed");
  loginScreen *loginScreenObj = [[loginScreen alloc] initWithNibName:@"loginScreen" bundle:[NSBundle mainBundle]];
  [appDelegate.yourViewControllerObj  presentModalViewController:loginScreenObj animated:YES];
  [loginScreenObj release];
}


text:
Q: Desktop version to server migration I have installed ubuntu desktop 10.10 and lamp server and i am using it for past 6 months. and i never use that computer for anything else.. Now i feel like removing unwanted components like media programs, open office etc which is not needed for a server. but i would like to keep the GUI just as a option for ease of use.. will there be any problem if i remove those components. i dont want to install server edition from the beginning..

A: Ubuntu Server Edition is the same Ubuntu with different packages. I've installed Servers and installed the ubuntu-desktop package if I felt the need for a GUI on the system. I'm sure doing the reverse would work as well.
If you want a GUI but do not want the additional bloat that comes with Desktop edition, go ahead with it. Uninstalling Open Office, GIMP, Firefox etc should not cause any problems at all.

A: Surely you can do this though apart from uninstalling the office suite, which would free several hundred megabytes of diskspace, most other programs use very little disk space so uninstalling them would give you little benefits for the time spent.
Also be aware that some programs are required for Ubuntu to function properly so it's possibly to accidentally uninstall the whole desktop while trying to uninstall, for example, evolution. Just review the list of packages to be uninstalled in synaptic before proceeding - a very long list may indicate trouble


text:
Q: Hmmm, seems like your kit isn't activating:Nativescript-fabric I am using nativescript framework to build the mobile apps. I tried use the plugin nativescript-fabric.
But it won't work. I got the error like this  Fabric Crashlytics "Hmmm, seems like your kit isn't activating" whilst verifying install.(ios)
"Hmmm, seems like your kit isn't activating" message on the Fabric Controller after following the instruction to run the app in Xcode.
"nativescript-fabric": "^1.0.6",
  Crashlytics (3.9.3)
  Fabric (1.7.2)
Please give any suggestion. How to work with this. I need to upload the apk.


text:
Q: Folder.MoveTo will reset the main folder fields. can i preserve them I am working on a remote event receiver inside SharePoint online, and i have a code to move a folder to another library. now the source and destination libraries have the same content type and each library contain 5 managed metadata columns. now i want to move FolderA from lib1 to lib2, so i try the follow:-
Folder folder = context.Web.GetFolderByServerRelativeUrl(context.Web.ServerRelativeUrl + "/lib1/" + currentFilingSystemItem["DealName"].ToString());
folder.MoveTo(context.Web.ServerRelativeUrl + "/lib2/" );

But this will raise an error that it can not rename FolderA to lib2, folder already exists, so seems i need to add the FolderA name inside the destination path, so i tried the following:-
 Folder folder = context.Web.GetFolderByServerRelativeUrl(context.Web.ServerRelativeUrl + "/lib1/" + currentFilingSystemItem["DealName"].ToString());
 folder.MoveTo(context.Web.ServerRelativeUrl + "/lib2/"+ currentFilingSystemItem["DealName"].ToString());

this has moved the folder, but the main folder FolderA will lost its managed metadata values, while the MoveTo has preserve the managed metadata for the sub-folders and files. can anyone advice if i can force the MoveTo to preserve the managed metadata for the main folder as well?
Thanks


text:
Q: How can I set properties on multiple clones in a generic list after instantiation I don't understand why this does not work:
Vector3 pos = new Vector3(x,0,y);
TerrainTiles.Add(Instantiate(Resources.Load("Prefabs/TerrainTile"), pos, Quaternion.identity) as TerrainTile);
Debug.Log("List items: " + TerrainTiles.Count.ToString());
TerrainTiles[TerrainTiles.Count - 1].xPosition = x;

Running the Debug.Log shows that the list items are being created but when I try to reference any of them as in the last line of code above I am getting a NullReferenceException.

A: I am not familiar with the product you are using but it appears that TerrainTiles is a collection with one null value. If so, .Count will still return a number. Check your paths. Is Resources.Load() supposed to load an entire directory?
Try this:
TerrainTile tile;

if((tile = Instantiate(Resources.Load("Prefabs/TerrainTile"), pos, Quaternion.identity) as TerrainTile) != null){
    TerrainTiles.Add(tile);
}

A: Firstly, make sure your prefab is accesible with a path containing a 'Resources' folder as stated in the documentation: http://docs.unity3d.com/Documentation/ScriptReference/Resources.html
Secondly, you cannot load an entire directory, you can only load a particular resource one at a time. So here "Prefabs/TerrainTile" should refer to a file named TerrainTile.prefab (or another extension).
And as @drankin2112 already pointed out, it is safer to check the reference before adding it to the list (or any collection):
TerrainTile tile;
tile = Resources.Load("Prefabs/TerrainTile", typeof(TerrainTile)) as TerrainTile);
// Check whether resource exists
if (tile != null)
{
    tile = Instantiate(tile, pos, Quaternion.Identity) as TerrainTile;
    // Check whether instantiation worked
    if (tile != null)
    {
        tileList.Add(tile);
    }
}

A: This ended up solving the problem:
    TerrainTiles.Add(Instantiate(Resources.Load("Prefabs/TerrainTile", typeof(TerrainTile)), pos, Quaternion.identity) as TerrainTile);

Thank all of you for your advice and assistance.


text:
Q: javascript toggle menu on and off Hey everyone I have been struggling with the nav menu and getting it to toggle on and off, it seems to be turning on and off in the dev tools but the li links don't disappear, I have tried rewriting the code, but still can't get it to work, I double checked to make sure i was selecting the right elements, please if anyone can help I would sincerely appreciate it!
Thank You
here is the code:

const showMenu = (toggleId, navId) => {
  const toggle = document.getElementById(toggleId),
    nav = document.getElementById(navId)

  if (toggle && nav) {
    toggle.addEventListener("click", () => {
      nav.classList.toggle("show");
    })
  }
};

showMenu('nav-toggle', 'nav-menu');
<link rel="stylesheet" href="practice.css">
<link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'>

    Sneaker Warehouse

Home

Featured

Women

New

Shop

A: I got it working by reading one of the comments on this post. you forgot to add the css.
html
<link rel="stylesheet" href="practice.css">
<link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'>

    Sneaker Warehouse

    <button class='nav_menu' id='nav-menu'>

Home

Featured

Women

New

Shop

    </button>

js
const showMenu = (toggleId, navId) => {
  const toggle = document.getElementById(toggleId),
    nav = document.getElementById(navId)

  if (toggle && nav) {
    toggle.addEventListener("click", () => {
      nav.classList.toggle("show");
      toggle.classList.toggle("show");
    })
  }
};

showMenu('nav-toggle', 'nav-menu');

css
.nav_menu {
  display: none;
}

.show {
  display: initial;
}


text:
Q: Deleting all nodes in a binary tree using O(1) auxiliary storage space? The standard algorithm for deleting all nodes in a binary tree uses a postorder traversal over the nodes along these lines:
if (root is not null) {
   recursively delete left subtree
   recursively delete right subtree
   delete root
}

This algorithm uses O(h) auxiliary storage space, where h is the height of the tree, because of the space required to store the stack frames during the recursive calls.  However, it runs in time O(n), because every node is visited exactly once.
Is there an algorithm to delete all the nodes in a binary tree using only O(1) auxiliary storage space without sacrificing runtime?

A: Let me start with a serious joke: If you set the root of a BST to null, you effectively delete all the nodes in the tree (the garbage collector will make the space available). While the wording is Java specific, the idea holds for other programming languages. I mention this just in case you were at a job interview or taking an exam.
Otherwise, all you have to do is use a modified version of the DSW algorithm. Basically turn the tree into a backbone and then delete as you would a linked list. Space O(1) and time O(n). You should find talks of DSW in any textbook or online.
Basically DSW is used to balance a BST. But for your case, once you get the backbone, instead of balancing, you delete like you would a linked list.

A: It is indeed possible to delete all the nodes in a binary tree using O(n) and O(1) auxiliary storage space by using an algorithm based on tree rotations.
Given a binary tree with the following shape:
           u
          / \
         v   C
        / \
       A   B

A right rotation of this tree pulls the node v above the node u and results in the following tree:
        v
       / \
      A   u
         / \
        B   C

Note that a tree rotation can be done in O(1) time and space by simply changing the root of the tree to be v, setting u's left child to be v's former right child, then setting v's right child to be u.
Tree rotations are useful in this context because a right rotation will always decrease the height of the left subtree of the tree by one.  This is useful because of a clever observation: it is extremely easy to delete the root of the tree if it has no left subchild.  In particular, if the tree is shaped like this:
     v
      \
       A

Then we can delete all the nodes in the tree by deleting the node v, then deleting all the nodes in its subtree A.  This leads to a very simple algorithm for deleting all the nodes in the tree:
while (root is not null) {
    if (root has a left child) {
        perform a right rotation
    } else {
        delete the root, and make the root's right child the new root.
    }
}

This algorithm clearly uses only O(1) storage space, because it needs at most a constant number of pointers to do a rotation or to change the root and the space for these pointers can be reused across all iterations of the loop.
Moreover, it can be shown that this algorithm also runs in O(n) time.  Intuitively, it's possible to see this by looking at how many times a given edge can be rotated.  First, notice that whenever a right rotation is performed, an edge that goes from a node to its left child is converted into a right edge that runs from the former child back to its parent.  Next, notice that once we perform a rotation that moves node u to be the right child of node v, we will never touch node u again until we have deleted node v and all of v's left subtree.  As a result, we can bound the number of total rotations that will ever be done by noting that every edge in the tree will be rotated with its parent at most once.  Consequently, there are at most O(n) rotations done, each of which takes O(1) time, and exactly n deletions done.  This means that the algorithm runs in time O(n) and uses only O(1) space.
In case it helps, I have a C++ implementation of this algorithm, along with a much more in-depth analysis of the algorithm's behavior.  It also includes formal proofs of correctness for all of the steps of the algorithm.
Hope this helps!

A: Algorithm 1, O(n) time and O(1) space:
Delete node immediately unless it has both children. Otherwise get to the leftmost node reversing 'left' links to ensure all nodes are reachable - the leftmost node becomes new root:
void delete_tree(Node *node) {
    Node *p, *left, *right;

    for (p = node; p; ) {
        left = p->left;
        right = p->right;
        if (left && right) {
            Node *prev_p = nullptr;
            do {
                p->left = prev_p;
                prev_p = p;
                p = left;
            } while ((left = p->left) != nullptr);
            p->left = p->right;
            p->right = prev_p;       //need it on the right to avoid loop
        } else {
            delete p;
            p = (left) ? left : right;
        }
    }
}

Algorithm 2, O(n) time and O(1) space: Traverse nodes depth-first, replacing child links with links to parent. Each node is deleted on the way up:
void delete_tree(Node *node) {
    Node *p, *left, *right;
    Node *upper = nullptr;

    for (p = node; p; ) {
        left = p->left;
        right = p->right;
        if (left && left != upper) {
            p->left = upper;
            upper = p;
            p = left;
        } else if (right && right != upper) {
            p->right = upper;
            upper = p;
            p = right;
        } else {
            delete p;
            p = upper;
            if (p)
                upper = (p->left) ? p->left : p->right;
        }
    }
}

A: I'm surprised by all the answers above that require complicated operations.
Removing nodes from a BST with O(1) additional storage is possible by simply replacing all recursive calls with a loop that searches for the node and also keeps track the current node's parent. Using recursion is only simpler because the recursive calls automatically store all ancestors of the searched node in a stack. However, it's not necessary to store all ancestors. It's only necessary to store the searched node and its parent, so the searched node can be unlinked. Storing all ancestors is simply a waste of space.
Solution in Python 3 is below. Don't be thrown off by the seemingly recursive call to delete --- the maximum recursion depth here is 2 since the second call to delete is guaranteed to result in the delete base case (root node containing the searched value).
class Tree(object):
    def __init__(self, x):
        self.value = x
        self.left = None
        self.right = None

def remove_rightmost(parent, parent_left, child):
    while child.right is not None:
        parent = child
        parent_left = False
        child = child.right
    if parent_left:
        parent.left = child.left
    else:
        parent.right = child.left
    return child.value

def delete(t, q):
    if t is None:
        return None

    if t.value == q:
        if t.left is None:
            return t.right
        else:
            rightmost_value = remove_rightmost(t, True, t.left)
            t.value = rightmost_value
            return t

    rv = t
    while t is not None and t.value != q:
        parent = t
        if q < t.value:
            t = t.left
            parent_left = True
        else:
            t = t.right
            parent_left = False

    if t is None:
        return rv

    if parent_left:
        parent.left = delete(t, q)
    else:
        parent.right = delete(t, q)

    return rv

def deleteFromBST(t, queries):
    for q in queries:
        t = delete(t, q)
    return t


text:
Q: Duplicate log output, but no duplicate handlers I am getting duplicate log output from a logger that only has 1 handler attached.
How can I debug this?
Code (should be copy-and-paste-able):
import io
import logging
import os
import sys
from typing import Optional

DEFAULT_LOG_LEVEL = logging.INFO

def get_sub_loggers():
    return [
        logging.getLogger('a'),
        logging.getLogger('b'),
        logging.getLogger('c')
    ]

def safe_add_handler(logger: logging.Logger, h: logging.Handler) -> None:
    if h not in logger.handlers:
        logger.addHandler(h)

def safe_add_filter(logger: logging.Logger, f: logging.Filter) -> None:
    if f not in logger.filters:
        logger.addFilter(f)

def configure_logging(main_logger: logging.Logger,
                      log_level = DEFAULT_LOG_LEVEL,
                      log_file = None,
                      fmt: Optional[str] = None,
                      force_add_handler: bool = False) -> None:
    main_logger.setLevel(log_level)
    logging.captureWarnings(True)  # send all warnings to be logged

    if force_add_handler or not main_logger.hasHandlers():
        if log_file is None or log_file == '-':
            log_file = sys.stderr

        if isinstance(log_file, (str, os.PathLike)):
            handler = logging.FileHandler(log_file)
        else:
            handler = logging.StreamHandler(log_file)

        handler.setFormatter(logging.Formatter(fmt if fmt is not None else logging.BASIC_FORMAT))

        main_logger.addHandler(handler)
        log_output_location = handler.stream.name if isinstance(handler, logging.StreamHandler) else handler.baseFilename
        main_logger.info('Writing logs to {}'.format(log_output_location))
    else:
        main_logger.info('Using existing log handlers')

    main_logger.info('Using log level {}'.format(log_level))

    for logger in get_sub_loggers():
        logger.setLevel(log_level)
        for h in main_logger.handlers:
            safe_add_handler(logger, h)
        for f in main_logger.filters:
            safe_add_filter(logger, f)
        main_logger.debug('Configured logger {}'.format(logger.name))

    main_logger.info('Configured submodule loggers.')

configure_logging(logging.getLogger())

a_logger = logging.getLogger('a')
assert len(a_logger.handlers) == 1

# Should only output "hi" once, but it does it twice
a_logger.info('hi')

A: Loggers propagate log events to their ancestors' handlers by default. a_logger may only have one handler, but its parent, the root logger, also has a handler (actually the same handler). a_logger.info('hi') is handled by both handlers (actually the same handler twice).
You don't need to attach the same handler to every logger. Attaching it to the root logger is enough.


text:
Q: Simple script - execute command on selected file I want to make a script that will execute .jar file on selected file. Later I will add that script to right-click menu via the tool Nautilus Actions or just place it into nautilus-scripts folder. I have a problem creating script.
When I am in a usual console screen and want to execute this jar file on any other file, I use this syntax
myfile.jar ./someotherfile.xml
and the jar file will write the output to the console screen.
So I created a file script.sh, added lines in it
#!/bin/bash
/home/username/myfile.jar $1

But it does not output anything. I know I am doing something wrong. Please help.
To sum, I need a script that will use selected file as a parameter, open the gnome-terminal, inside that terminal it will start JAR file and pass it the selected file.
I am confident that this is a very simple procedure, but I am total newbie with shell scripting.

A: You might also go for
!/bin/sh
gnome-terminal -x java -jar /home/askmoo/myfile.jar "$1"

in order to first open gnome terminal and then execute  your java application in it. This way you would be able to get output printed out to the terminal.

A: There is always a "right click properties" pop-up to executables (and icons) on the desktop and folders in Gnome, KDE and others. I'm not sure how you would go about this with the nautilus actions extension but you can always force your terminal to hang after a command exits like this:
$ cat > /usr/local/bin/har.sh
#!/bin/sh
java -jar /home/jaroslav/tmp/src/hat/bin/hat.jar
while true;do
read  -p "finished reading? " quit;
[[ "$quit" == "yes" ]] && exit
done

$ chmod 755 /usr/local/bin/hat.sh
$ hat.sh

Usage:  hat [-stack=<bool>] [-refs=<bool>] [-port=<port>] [-baseline=<file> -debug=<int>] [-version] <file>

        -stack false:     Turn off tracking object allocatoin call stack.
        -refs false:      Turn off tracking of references to objects
        -port <port>:     Set the port for the HTTP server.  Defaults to 7000
        -exclude <file>:  Specify a file that lists data members that should
                          be excluded from the reachableFrom query.
        -baseline <file>: Specify a baseline object dump.  Objects in
                          both heap dumps with the same ID and same class will
                          be marked as not being "new".
        -debug <int>:     Set debug level.
                            0:  No debug output
                            1:  Debug hprof file parsing
        -version          Report version number
        -donationware     Give information on the status of HAT
        <file>            The file to read

For a JDK 1.2 (or better) dump file, you may specify which dump in the file
by appending "#<number>" to the file name, i.e. "foo.hprof#3".

All boolean options default to "true"

finished reading? no
finished reading? ^C
$

give the terminal CTRL+C to exit (or type yes)
there is also the properdies dialog:
.. ok I just looked through nautilus properties... no luck (I f* hate gnome, they keep making it dumber and dumber)
Its still available in KDE: (but id as soon just use the infinite-while loop), the number of boxes to navigate to get to those settings is just overwhelming.

A: ./myfile.jar and myfile.jar are two different commands. The first executes a file in the current directory (providing the execute bit is set), the latter searches $PATH for a program named myfile.jar.
If $PATH is /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games, then it searches for (in order):
/usr/local/sbin/myfile.jar
/usr/local/bin/myfile.jar
/usr/sbin/myfile.jar
/usr/bin/myfile.jar
/sbin/myfile.jar
/bin/myfile.jar
/usr/games/myfile.jar

I doubt if your jar file is really an executable, if it's a Java ARchive, your shellscript should be:
#!/bin/sh
java -jar /home/askmoo/myfile.jar "$1"


text:
Q: Applying Zorn's Lemma to natural numbers Zorn's Lemma states that if every chain $C$ in a partially ordered set $X$ has an upper bound then there is at least one maximal element in $X$.
Let $n\in \mathbb{N}$, $C_n \subset \mathbb{N}$ be the set containing the natural numbers $\{1,\dots,n\}$. Then if $k\le n$, $C_k\subset C_n$, so $C_n$ is a chain. Also, $C_n$ has an upper bound, such as $n+1$. But what is the maximal element of $\mathbb{N}$?
There's something I don't get in Zorn's Lemma statement.

A: You just take some examples of chains, but there are many others, for example the multiples of any positive integer is a chain. The hypothesis of the lemma is that every chain must have a upper bound, but $\mathbb{N}$ is a total ordered set, then every subset of $\mathbb{N}$ is a chain, in special, $\mathbb{N}$ itself is a chain.
The Zorn's lemma is quite useless in a total ordered set, because, if this set satisfies the hypothesis, the upperbound of the set itself (which is a chain) is the maximal element.


text:
Q: How to run nine patch editor in android studio Ubuntu? I tried to run ninepatch jar from sdk folder using command java -jar ninepatch.jar in terminal. My bad, nothing happened. I tried various web based ninepatch editors like romannurik
 which won't serve my purpose.
How can I run ninepatch jar in Ubuntu Linux.

A: Why do you want to try the hard way,when people has made your life little bit easier.
9patch -> http://romannurik.github.io/AndroidAssetStudio/nine-patches.html
Or,in Android Studio you can right click on your image file from drawable and create 9 patch image. And then you can edit the file.


text:
Q: how to build a grid list like this in swiftUI?

*

*this grid view has 2 rows

*this grid always has 5 columns

*this grid scrollable in X axis(horizontally)

*this grid item is a custom view(has a image and some text)

*this grid item is auto-fit

I'm new to swiftUI,I want to build a grid view as highlight image above, desire to be helped from you, thanks!

A:
struct ContentView: View {
    let numberOfColumn = 5
    let rows = [GridItem(.fixed(50)),GridItem(.fixed(50))]
    let space:Float = 10.0

    var body: some View {
        GeometryReader { proxy in
            ScrollView(.horizontal) {
                LazyHGrid(rows: rows ,spacing: 10, content: {
                    ForEach(0 ..< numberOfColumn * 2) { item in
                        Rectangle() //replace with your cell view
                            .frame(width: CGFloat( getColumnWidth(width: Float(proxy.size.width))))
                    }
                })
            }
        }
    }

    func getColumnWidth(width: Float) -> Float {
        ((width) - ((space)*Float(numberOfColumn-1))) / Float(numberOfColumn)
    }
}


text:
Q: Prove $a_n = \begin{cases}1 & \text{if $n=2^k$ for some $k\in N$}\\ 0 & \text{otherwise} \end{cases}$ diverges. Prove $a_n = \begin{cases}1 & \text{if $n=2^k$ for some $k\in N$}\\ 0 & \text{otherwise} \end{cases}$ diverges.
I need to prove that this diverges but I am not sure how to do so. I know that it diverges because we can see that,
$a_n = 0,1,0,1,0,0,0,1...$
My attempt:
Case 1: When $L = 0$
let $\epsilon = 1$
$$|a_n-0| < 1$$
$$|a_n| < 1$$
Case 2: When $L = 1$
$$|a_n-1| < 1$$
By Triangle Inequality:
$$|a_n+a_n-1| \le |a_n| + |a_n-1|$$
$$|a_n+a_n-1| \le 1 + 1 = 2 \neq 1$$
Thus it diverges?
I'm not sure if this is a valid proof so if anyone can help me with this, that would be really appreciated.

A: By diverges, we mean that the sequence doesn't converge. Note that if a sequence converges to a limit $L$ then every subsequence must converge to the same $L$.
Now you can easily see that the subsequence $a_{n_{2^k}} \rightarrow 1$ while you can find a subsequence that converges to $0$. Hence the original sequence doesn't converge.

A: You clearly know that the sequence diverges, and also why it diverges. But it looks as if you may be expected to use an  "$\epsilon$-$N$" argument.
First we proceed very informally. If our sequence had a limit $b$, then $a_n$ will be very close to $a$ whenever $n$ is large enough. But the sequence has $0$'s arbitrarily far out, and also $1$'s arbitrarily far out, and $0$ and $1$  cannot be simultaneously  very close to $b$.
More formally, let $\epsilon=\frac{1}{10}$. If the sequence converges to $b$, then there is an $N$ such that if $n\gt N$ then $|a_n-b|\lt \epsilon=\frac{1}{10}$.
From this, we derive a contradiction.
There is an integer $p\gt N$ such that $a_p=0$. Also, there is a $q=2^k\gt N$ such that $a_q=1$. Now by the triangle inequality we have
$$1=|a_p-a_q| \le |a_p-b|+|b-a_q|\lt \frac{1}{10}+\frac{1}{10}=\frac{2}{10}.$$
This is impossible, since it is not the case that $1\lt \frac{2}{10}$.

A: Try to go back to the definitions when you are doing proofs like this. You want to show that $a_n$ diverges, so what does it mean to diverge? A sequence converges if there exists some $L$ such that for any $\epsilon > 0$, we can find some $N$ such that for all $n\geq N$, $|L-a_n|<\epsilon$. Now, you're trying to hold that this condition does not hold for this sequence, so what would that mean? It would mean that for any $L$, there exists some $\epsilon>0$ such that for all $N$ there exists some $n\geq N$ where $|L-a_n|>\epsilon$. Side-note: you should get really good at taking the negations of propositions. Let's break that last sentence down:

*

*For all $L$

*there exists $\epsilon$ such that

*for all $N$

*there exists $n$ such that

*$|L-a_n|\geq \epsilon$

Now what? Well, we want to prove something about all $L$, so how about let's fix an arbitrary $L$ and prove that the claim holds. So fix $L$. Now we want to show that a certain $\epsilon$ exists. The trick here is to just call this value $\epsilon$ and hope we can find a specific value for it later which proves the claim. So we'll leave $\epsilon$ open right now and check the next part: for all $N$. Again, we're showing something holds for all $N$, so let's fix an arbitrary $N$ and prove it. Now, again, we have there exists *n*, so let's leave that $n$ free and hope we find something. Finally, we have $|L-a_n|\geq \epsilon$, which is really the meat of what we need to prove. So essentially, we have $L$ and $N$ fixed, and we are looking for a pair $\epsilon,n$ such that $|L-a_n|\geq \epsilon$ holds; if we can find this pair, we've proven the claim. Note that so far all of this has just been setup. The first step in a proof is figuring out exactly what you need to prove, and often that's the toughest part.
So, the question is simply, given a fixed $N$ and $L$, can we find $n$ and $\epsilon$ so that $L$ is more than $\epsilon$ away from $a_n$? To be safe, let's take epsilon to be very small and see what happens: let $\epsilon=\frac{1}{2}$ (we'll make it smaller later if we need to). We know that for any $n$, $a_n$ is either $0$ or $1$. So take $n$ to be the next power of 2 larger than $N$, so that $a_n=1$. Now, if $|L-1|\geq \frac{1}{2}$, we're done: we've found our pair $\epsilon,n$ such that the desired condition holds. Otherwise, we know that $a_{n+1}=0$ and $|L-1|<\frac{1}{2}$. Then, $1-L\leq |1-L| < \frac{1}{2}$. Rearranging, we get $\frac{1}{2}<L\leq|L|=|L-0|=|L-a_{n+1}|$, so we've found a pair such that the condition holds. Either way, we're done.


text:
Q: Do manual build fail in Jenkins using shell script I would like to mark a Jenkins build to fail on one scenario for example:
if [ -f "$file" ]
then
    echo "$file found."
else
    echo "$file not found."
    #Do Jenkins Build Fail
fi

Is it possible via Shell Script?
Answer: If we exit with integer 1, Jenkins build will be marked as failed.  So I replaced the comment with exit 1 to resolve this.

A: All you need to do is exit 1.
if [ -f "$file" ]
then
    echo "$file found."
else
    echo "$file not found."
    exit 1
fi

A: To fail a Jenkins build from .NET, you can use Environment.Exit(1).
Also, see How do I specify the exit code of a console application in .NET?.

A: To fail a Jenkins build from Windows PowerShell, you can use Steve's tip for C# as follows:
$theReturnCode = 1
[System.Environment]::Exit( $theReturnCode )

Notes;
1.Windows recycles exit codes higher than  65535. (  https://stackoverflow.com/a/31881959/242110 )
2.The Jenkins REST API has a '/stop' command, but that will cancel the build instead of actually failing it. ( https://jenkinsapi.readthedocs.org/en/latest/build.html )
3.Jenkins can also mark a build 'unstable', and this post ( https://stackoverflow.com/a/8822743/242110 ) has details on that solution.


text:
Q: Iterating through an array on scroll in jQuery or JavaScript I have used Lettering.js to create a collection of <span> elements with class "char*", * signifying an integer in this example. I created an array of these elements as follows:
var characterArray = $("[class^='char']");

I have used the Fisher-Yates Shuffle Algorithm below:
function shuffle(array) {
    var m = array.length, t, i;

    // While there remain elements to shuffle…
    while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
    }

    return array;
}

To manipulate characterArray as follows:
    var disappearArray = shuffle(characterArray);

So I currently have an array containing a randomly ordered collection of elements that I want to iterate through on scroll incrementally. My goal is to have a <span> element contained in the array display:none every time the user scrolls, until all <span> elements in the array are not displaying.
I have tried:
$(window).scroll(function(){
    $.each(disappearArray, function(i, val) {
        $(val).addClass("hidden");
    });
});

but on scroll all the elements are set to display:none.
How can I set this to happen on an incremental basis?

A: $(window).scrollTop() will return a value of how much you have scrolled, so you might consider some amount of scrolled pixels, for each span. makes sense? :)
$(window).scroll(function(){
    var scrolled  = $(window).scrollTop();

    $.each(disappearArray, function(i, val) {
        scrolled > i * disappearArray.length?
        $(val).addClass("hidden") : $(val).removeClass("hidden");
    });
});

Something similar :) Hope it helps you. Good luck!


text:
Q: Formula excel Promedio con condiciones tengo 4 celdas donde quiero sumar el valor de las 4 luego dividir entre 4 y condidicionar que:
si el total da un valor de 4 o menos ponga un 1
si el total da 6 o menos pona un 2
si el total da un 8 o menos de un 3
si el total da un 9 exacto ponga un 4
Pero me marca error, soy nuevo en excel, si me puede instruir por favor
Esta es la formula que intente sin exito
=SI(SUMA(F15:I15)/4<=4,1),SI(SUMA(F15:I15)/4<=6,2),SI(SUMA(F15:I15)/4<=8,3),SI(SUMA(F15:I15)/4=9,4)

A: La estructura que necesitas es la siguiente:
=SI(PRUEBA_LOGICA; VALOR SI VERDADERO; SI(PRUEBA_LOGICA, VALOR_SI_VERDADERO; SI(...))... ;VALOR SI FALSO)

Esto te permite anidar todos los si's que quieras, definiendo siempre el caso verdadero de cada prueba lógica, es decir, lo que devuelve la fórmula en caso que tu prueba lógica sea verdadera, y anidar en el si no, el resto de casos, siempre definiendo los valor si verdadero.
Al final, te queda un valor si falso por no continuar anidando si's: Esto es lo que devolverá la fórmula si no entra en ningún caso positivo, es decir, si no se cumplen ninguna de las pruebas lógicas que has definido.

A: Prueba así:
=SI(PROMEDIO(F15:I15)<=4,1,SI(PROMEDIO(F15:I15)<=6,2,SI(PROMEDIO(F15:I15)<=8,3,SI(PROMEDIO(F15:I15)=9;4,"OTRO RESULTADO"))))
No has especificado qué pasa si el resultado del promedio es mayor que 9, por eso he añadido lo de OTRO RESULTADO.
Si eso no puede suceder nunca, entonces usa:
=SI(PROMEDIO(F15:I15)<=4,1,SI(PROMEDIO(F15:I15)<=6,2,SI(PROMEDIO(F15:I15)<=8,3,4,)))


text:
Q: Mermaid boxes too small in HTML Quarto I am creating a mermaid diagram in HTML format in Quarto, but the problem is that the boxes are too small for the words in the diagram. Here is a reproducible example:
---
title: "Mermaid boxes too small in HTML Quarto"
format: html
---

```{mermaid}
flowchart LR
  A[Data preparation] --> B(Data exploration)
  B --> C{Modelling}
  C --> D[Prediction]
  D --> E[Conclusion]
```

Output:

As you can see, the boxes are too small for the words. So I was wondering if anyone knows how to prevent this (maybe automatically)?


text:
Q: How to verifiy if IP is used by particular server or not using Shell script? I am trying to run a Shell script which fails at grep state, below is what I am running
activeIP=`grep -Po '(?<=active.server.ip=).*' /etc/active.properties`

command="ifconfig | grep "$activeIP

eval "$command"

if [ $? == 0 ]; then
    echo"You are on Active"
else
    echo"You are not on Active"
fi

active.properties file contents:
active.server.ip=10.25.15.1
standby.server.ip=10.25.15.2

Please help......

A: I would use a different tool for parsing the file, and also I'd avoid the eval since it's so easy to go wrong with that.  So using awk, and assuming you're using bash I'd do it like:
activeIP=$(awk -F= '$1 == "active.server.ip" {print $2}' /etc/active.properties)
if ip addr show | grep -qw "$activeIP"; then
    echo "You are on Active"
else
    echo "You are not on Active"
fi

Explanation:
First we use awk with -F= to split fields on =.  Then if the first field is equal to active.server.ip we'll print the second field.  Note, if you have/allow whitespace around the = this will need to be changed a bit.  We store that printed value in activeIP just as you did in your attempt.
Next, we check if the given IP shows up in our current IP list.  The ip command is the newer version of ifconfig, so I swapped for that.  There's no need to build a string and eval it because bash will already do variable substitution as when it's executing the command.
We'll use grep to check the output of the ip addr show command, and we add the -w to match words, so if our IP is a substring of another IP it won't match (e.g., the string 192.168.114.3 will not match the IP 192.168.114.37).  Also, since we don't actually care about the matching line, I added -q to make it run quietly.
Finally, if will look at the exit status already, so we don't have to do an explicit test for $?.
As another possible step reduction, we could actually skip storing the IP in a variable and let bash do process substitution for us like so:
if ip addr show | grep -qw $(awk -F= '$1 == "active.server.ip" {print $2}' /etc/active.properties); then
    echo "You are on Active"
else
    echo "You are not on Active"
fi

So it will do the awk "in line" as it were.


text:
Q: How to set data on an already created editor? I want to set data to 3 nos. of already created editors which I am unable to do.
I tried pt. no. 2 to set data which is happening on a newly created editor and not to the existing one.

*

*Below is where i am creating my 3 editors:

create_editor: function () {
            window.editors = {};
            document.querySelectorAll('.editor').forEach((node, index) => {
                ClassicEditor
                    .create(node, {
                        //removePlugins: [ 'Heading', 'Link' ],
                        toolbar: ['bold', 'italic', 'bulletedList', 'numberedList', 'blockQuote', 'Heading'],
                        //placeholder: 'Type the content here!'
                    })
                    .then(editor => {
                        //console.log(editor);
                        window.editors[index] = editor
                    })
                    .catch(error => {
                        //console.error(error);
                    });
            });
        }

*Below is where i am trying to set my data to all my 3 existing editors:

set_editor: function (elem, data) {
            ClassicEditor
                .create(document.querySelector('#' + elem))
                .then(editor => {
                    editor.setData(data);
                })
        }

The data are stored in a local storage and I want to retrieve them and set them to my already 3 created editors which currently is not happening.

A: Your problem here is that you need to get an instance of existing ClassicEditor to edit it.
As provided in this answer, you can store your instances in a global variable (like you are already doing, but instead of index store element.id as key)
Also from your comments, it is clear that you are facing race condition between editor create and editor set, so instead of saving the editor in window.editors save the promise, that way you can wait for editor create to finish before setting the value.
create_editor: function () {
    window.editors = {};
    document.querySelectorAll('.editor').forEach(node => {
        window.editors[node.id] =
        ClassicEditor
            .create(node, {
                //removePlugins: [ 'Heading', 'Link' ],
                toolbar: ['bold', 'italic', 'bulletedList', 'numberedList', 'blockQuote', 'Heading'],
                //placeholder: 'Type the content here!'
            })
            .then(editor => {
                //console.log(editor);
            })
            .catch(error => {
                //console.error(error);
            });
    });
}

set_editor: function (elem, data) {
    window.editors[elem].then(editor => editor.setData(data));
}


text:
Q: The cluttered and not very useful Bugs page Any visitor or user who clicks the Bugs tab, situated on the Top Questions Page, is presented with  *single page of bugs ranked in order of votes. These upvotes might lead an inexperienced user (and they're still around) to believe these bugs are listed in order of importance e.g. "Top" = "highest (priority)". Instead, they are listed according to popularity.

*

*The first reported bug, with 127 upvotes, is Deletion votes from users who later become moderators shouldn't prevent community undeletion. I contend that it was never a bug to begin with. Users cannot vote to undelete a post that was deleted by five users if one of them was later elected as a mod. This appears to be by design but if it's not, why is it still listed as a bug after 5 years and 10 months? Call it an oversight, a forgivable lapse, a side-issue, but I don't think that can be classified as a software error.

*The second bug–85 upvotes–reported in 2016 is Why is my profile image different?
It is my understanding, very limited, I know, that this bug has since been fixed. In any case, SE issued avatars (Gravatars) that change overnight no longer happens. That bug has been resolved, hasn't it? Of what use is it to the community today? Shouldn't it have a moderator's tag or something, saying "fixed" or status completed?

*The third reported bug is dated 2012: If users with <20 rep can't chat, why does SO nag me to move comment threads to chat? However, it was soon closed as a duplicate of a feature request:  Disable chat migration notification if one of the users has insufficient rep?. That FR earned a status-completed tag in 2018. Again, who could possibly be interested in this "bug" today when, first of all, it was really a criticism of the chat design/functionality and not a bug. And secondly, it's closed, which means no new answers can be posted

*The fourth top-rated bug, with 71 upvotes, is:  The editor should be able to convert multi-line blocks to lists But is it a bug, in the real sense of the word? It appears to be another Feature Request. The answer posted suggests a viable solution of listing items but doesn't SE also allow users to make lists by using numbers followed by a period? For example,

*

*Item one

*Item two

*Item three (and so on)

UPDATE
Spurred by comments and Laurel's answer, I flagged the aforementioned post February 13, suggesting that it was not a bug. The flag was rejected with this boilerplate message

declined - flags should only be used to make moderators aware of content that requires their intervention

So, MSE is left with a "bug" that was reported 5 years and 11 months ago. I'm not sure how to interpret the response to my flag or the evident lack of activity or response this "bug" has produced.

*

*Bug #5 was closed for being off-topic by Adam Lear ♦ in January this year, but it's still on the list. Which begs the question, why are off-topic posts allowed to clutter the Bugs page?

*Bug #6 (64 upvotes) Is my SO Coffee Mug defective?
Although it has the status-norepro tag, it doesn't exclude it from appearing on the main page. We can agree that it was a fun post while it lasted, however,  it is not a bug. A Stack Overflow coffee mug that does not automatically refill itself, is a problem for its owner not for the community. I dunno, maybe it belongs on the meme list?
In order to view the most recent bugs, a user must click on the sandwich menu, top left corner, then click on Questions which takes them to the All Questions page and then...(pause) there's no tab for bugs! How come? Why is there one on the Top Questions page but not on the All Questions?
The solution is to click the bug tag and then click Newest. This seems a rather counter-intuitive and tiresome process for a newcomer who will probably end up reporting a duplicate bug.
Why is there a bug tab on one page but not on the other? Why does that bug page have only one page, there is no page 2, 3, 4 etc?
What purpose does that page have: curiosity to find out which bug in MSE history collected the most upvotes?  It's only until you reach the bottom that SE tells its visitors, Looking for more bugs? Browse the complete list.

Wouldn't it be better if there was a message at the top of the page? For example,

If you are looking for a complete list of bugs, click here

Wouldn't a handy list of unresolved bugs, ranked highest in priority, help prevent newcomers from posting duplicate bugs and encourage all users to upvote the reported bugs they care most about?

A:
Wouldn't a handy list of unresolved bugs, ranked highest in priority, help prevent newcomers from posting duplicate bugs and encourage all users to upvote the reported bugs they care most about?

This is already mostly how it works (assuming that people upvote because a bug is high priority and not for the lulz). Bugs that are tagged status-completed, status-declined, status-deferred, or status-bydesign are removed from the tab, since there are higher voted bugs that aren't on the bugs tab:

Having only one page is expected because it is a page under "Home" not "Questions" (see for example the Active page under "Home" and compare it to the one under questions.) On these pages, the link to more questions is always at the bottom of the list.
Addressing the specific questions:

*

*The first question you mention seems to be a bug, especially since the answers, one by a SE employee and another by a (now) former SE employee, say they don't think it should be this way.

*The second question (which I posted) is still unresolved. Although people's images have stopped changing and being inconsistent, the Gravatar option still shows the new, wrong Gravatar for me (which is why I'm using an Imgur image of the old, good pic).

*The third question does not have have a status-completed tag. It is closed as a duplicate of a post with that tag. I think it would be a good idea to exclude closed questions from the tab though. In the meantime, a moderator could add a status-completed tag to the duplicate.

*The fourth question seems like a bug for the sole reason that I can't imagine anyone designing it that way on purpose, but I could also see it being an oversight. I'm on the fence on whether it should be tagged bug, but I think it ultimately doesn't matter. Nevertheless, if you see a mistagged question, you can retag it.

Lastly, because this tab (and the feature request tab) don't exist on other sites, I think that everyone here should know how to find only questions with a specific tag. Honestly, these tabs don't seem like much use to me, especially considering what Custom Question Lists can do (and what they will be able to do). The fact that there are 13-16 different lists of questions between all the different menus (depending on what site you're on; see here for more info), some with very opaque behavior, is confusing though.


text:
Q: Joi validation - how to make field validation based on the array value? I've been trying to implement the following logic:
if methods array includes object { type: 0 }
then grade field is requires
else grade field is optional
const methodTypeSchema = Joi.object({
  type: Joi.number(),
});

export const schema = Joi.object({
  methods: Joi.array().items(methodTypeSchema),
  grade: Joi.string().when('methods', {
    is: Joi.array().has(Joi.object({ type: 0 })),
    then: Joi.required(),
    otherwise: Joi.optional(),
  }),
});

I'll be grateful for the help.

A: hm, now it seems working... my mistake was that instead of default Joi.string() I used some custom functions


text:
Q: How to make the code flow without closing the VTK render window? I'm using Visual Studio 2010, VTK 5.6 and configure my projects without using CMake.
I'm dealing with numerical computing and want to generate several plots during the runtime using VTK. Starting with the line plot example given in the VTK web page I managed to generate the plot that I want. The problem is that the code doesn't continue without closing the plot window.
From my "main.cpp" file, I send the command to a header file, where the VTK procedure is initiated.
residualPlotter(x,xdim1d);

"residualPlotter" is the function that generates the plot. It's given below:
int residualPlotter(double* res, int size)
{

  // Create a table with some points in it
  vtkSmartPointer<vtkTable> table =
    vtkSmartPointer<vtkTable>::New();

  vtkSmartPointer<vtkFloatArray> arrX =
    vtkSmartPointer<vtkFloatArray>::New();
  arrX->SetName("X Axis");
  table->AddColumn(arrX);

  vtkSmartPointer<vtkFloatArray> arrF =
    vtkSmartPointer<vtkFloatArray>::New();
  arrF->SetName("Function");
  table->AddColumn(arrF);

  // Fill in the table with some example values
  table->SetNumberOfRows(size);
  for (int i = 0; i < size; ++i)
  {
    table->SetValue(i, 0, i);
    table->SetValue(i, 1, res[i]);
  }

  // Set up the view
  vtkSmartPointer<vtkContextView> view =
    vtkSmartPointer<vtkContextView>::New();
  view->GetRenderer()->SetBackground(1.0, 1.0, 1.0);
  view->GetRenderWindow()->SetSize(800,600);

  // Add multiple line plots, setting the colors etc
  vtkSmartPointer<vtkChartXY> chart =
    vtkSmartPointer<vtkChartXY>::New();
  view->GetScene()->AddItem(chart);
  vtkPlot *line = chart->AddPlot(vtkChart::LINE);
  line->SetInput(table, 0, 1);
  line->SetColor(0, 100, 0, 255);
  line->SetWidth(1.75);

  // Set up an interactor and start
  vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
    vtkSmartPointer<vtkRenderWindowInteractor>::New();
  renderWindowInteractor->SetRenderWindow(view->GetRenderWindow());
  renderWindowInteractor->Initialize();
  renderWindowInteractor->Start();

  return EXIT_SUCCESS;

}

So, I want the code to continue without the need to close the window. How should I modify the code?
Thank you all.

A: If you just want to render the plot, do something else, update and render again you can skip the renderWindowInteractor code, and simply call
view->Render();

This will render the plot with the data you supplied, and control will return to your code. You can continue doing this and call Render() on the view whenever you want to see an updated chart.

A: Marcus D. Hanwell mentioned a timer event at the comment. There is a code at a VTK example section. For me, I modified the snippet;
// Initialize must be called prior to creating timer events.
renderWindowInteractor->Initialize();

// Sign up to receive TimerEvent
vtkSmartPointer<vtkTimerCallback> cb = vtkSmartPointer<vtkTimerCallback>::New();
renderWindowInteractor->AddObserver(vtkCommand::TimerEvent, cb);

int timerId = renderWindowInteractor->CreateRepeatingTimer(100);
std::cout << "timerId: " << timerId << std::endl;

renderWindowInteractor->Start();

and I changed the vtkTimerCallback class at the sample code (in here, the background color keep being changed);
class vtkTimerCallback : public vtkCommand
{
public:
    static vtkTimerCallback *New()
    {
        vtkTimerCallback *cb = new vtkTimerCallback;
        cb->TimerCount = 0;
        return cb;
    }

virtual void Execute(vtkObject *vtkNotUsed(caller), unsigned long eventId, void *vtkNotUsed(callData))
{
    if (vtkCommand::TimerEvent == eventId)
    {
        ++this->TimerCount;
    }
    /* this section will be excuted */
    cout << this->TimerCount << " " << "This is from vtkTimerCallback" << endl;
    background_color = (double) rand() / RAND_MAX;
    cout << background_color << endl;
    renderer->SetBackground(background_color, background_color, background_color);
    renderWindow->AddRenderer(renderer);
    renderWindow->Render();
    /* ----- */
}
private:
    int TimerCount;
};

I declared the renderer and renderWindow as global variable, so the window change the window in the main section.

A: I added the grid to a vtkActor as follow:

vtkSmartPointer actor_grid = vtkSmartPointer::New();
vtkSmartPointer chart = vtkSmartPointer::New();
renderer->AddActor(actor_grid);

This works well since it is not associated with an interactor.
Thanks.


text:
Q: Spring Data JPA Sort with Nested Object's Property Consider the following structure:
public class Survey {
  @ManyToOne
  @JoinColumn(name = "team_id")
  private Team team;
}

public class Team {
  private String teamName;
}

I've created a REST endpoint to get all surveys. It also provides paging and sorting capabilities:
  @GetMapping("/all")
  public ResponseEntity<SurveyListViewResponse> getAllSurveys(
      @RequestParam(required = false) String userName,
      @RequestParam(required = false) String userEmail,
      @RequestParam(required = false) String teamName,
      @RequestParam(value = "quarter", required = false) String namedQuarter,
      @RequestParam(defaultValue = "id") String orderBy,
      @RequestParam(defaultValue = "DESC") Sort.Direction direction,
      @RequestParam(defaultValue = AppConstant.DEFAULT_PAGE) int page,
      @RequestParam(defaultValue = AppConstant.DEFAULT_PAGE_SIZE) int size,
      @RequestParam(required = false) SurveyStatus status) {

    Sort sort = Sort.by(direction, orderBy);
    Pageable paging = PageRequest.of(page, size, sort);

    SurveyListViewResponse surveyListViewResponse =
        surveyService.findAllSurveys(surveySpecification, paging);

    return ResponseEntity.status(HttpStatus.OK).body(surveyListViewResponse);
  }

So while accepting orderBy, there's a requirement to sort with properties within the nested objects like teamName, userName, userEmail, etc.
Passing these properties to the Sort.by method is not possible.

A: To achieve this, we can pass in the parameter the same way we accept a parameter in Query DSL. So for example, if we want to sort all the Surveys with respect to teamName, we have to simply pass team_teamName as property to Sort.by method i.e. Sort sort = Sort.by(Sort.Direction.ASC, "team_teamName");


text:
Q: Save screenshot of a DIV as and image How to take screenshot of a DIV which contain more than one images? Actually I am dragging images into DIV and want to take screenshot using Jquery or Javascript but without using server side scripting language.

A: Assuming you have a button to click (to trigger the capture), and that the images are on the same domain, load the html2canvas JS file, then add this:
$('#btn').click(function() {
  html2canvas($('#DIV'), {
    onrendered: function(canvas) {
      //do something with the canvas element - upload, append to a display element, etc.  For example:
    var myImage = canvas.toDataURL("image/png");
    window.open(myImage);
    }
  });
});


text:
Q: Storing TimeSpan in db4o I know that TimeSpan's are immutable.
I have a object which contains a TimeSpan field. This field is updated frequently. Every time I update the object in the db, db4o updates the TimeSpan field. So far, so good.
But the old TimeSpan structs are remaining in the db, so the db grows and grows.
How can I prevent db4o for saving the others? I only need the TimeSpan currently held in this field.
class Test {
    TimeSpan _totalRuntime;
    void Work() {
        DateTime start = DateTime.Now;
        _totalRuntime = _totalRuntime.Add(DateTime.Now - start);
    }
}

// Open the db
IObjectContainer db = Db4oEmbedded.OpenFile(ConfigDb4O(), _db4OFilename);

public static IEmbeddedConfiguration ConfigDb4O() {
    IEmbeddedConfiguration config = Db4oEmbedded.NewConfiguration();
    config.Common.Diagnostic.AddListener(new DiagnosticToConsole());
    return config;
}

db4o 7.12.132.14217 (.NET20)

A: As reported here db4o has some issues when updating value types that uses the "default typehandler" (you can see a typehandler as the piece of code in charge of marshaling objects to something that db4o can store).
We plan to fix this as soon as we find the time. Meanwhile I see at least 2 possible workarounds:

*

*Store TimeSpan.Ticks (a long) instead of the timespan itself, or

*Write a custom typehandler for TimeSpan (Harder, but not impossible).

PS: You can follow progress about this issue using the link above.
Best
Adriano


text:
Q: Convert Git tag to Python version on the command line in Gitlab CI In a Gitlab CI pipeline, I want to check that the package that was just uploaded to a registry is there and works well. What I do is basically:
[…]

stages:
  - […]
  - deploy
  - deploytest

pip-upload:
  stage: deploy
  rules:
    - if: '$CI_COMMIT_TAG && $CI_COMMIT_TAG =~ /v[1-9].+/'
  script:
    - python3 setup.py sdist
    - python3 -m twine upload --repository-url […] dist/*

test-pip:
  stage: deploytest
  rules:
    - if: '$CI_COMMIT_TAG && $CI_COMMIT_TAG =~ /v[1-9].+/'
  script:
    - python3 -m pip install --extra-index-url […] --upgrade --pre "mypackage==$PACKAGE_VERSION"
    - cd /tmp
    - python3 -m pytest --pyargs mypackage

This however requires the creation of the Python version from the git tag on the command line. I use setuptools_scm in my package. I there a way to call this package in a way that it returns the version corresponding to a particular git tag?

A: You can run python -m setuptools_scm to get the version. See python -m setuptools_scm --help for additional options.
You can also run python setup.py --version to get the version (assuming setuptools-scm is installed).


text:
Q: Factor a template parameter pack operation In the following template function definition, I write two times the relatively long expression details::transform(std::forward<T>(t)) where t is a parameter pack.
How can I factor it?
auto pack = details::transform(std::forward<T>(t)) of course doesn't work.
template<class ...T>
void f(T&&... t)
{
    auto check = (details::transform(std::forward<T>(t)) && ...);
    if (check == false) {
        return;
    }
    details::act(details::transform(std::forward<T>(t))...);
}

For tests purpose, here is a complete program on coliru.

A: You could use a macro.
#define FORWARD_TRANSFORM(type, var) details::transform(std::forward<type>(var))

Then your function becomes
template<class ...T>
void f(T&&... t)
{
    auto check = (FORWARD_TRANSFORM(T, t) && ...);
    if (check == false) {
        return;
    }
    details::act(FORWARD_TRANSFORM(T, t)...);
}

A: There's a sad truth to C++. Forwarding can become a cluster of tokens. And the more complex the expression that needs things forwarded, the more painful it can become.
Sadly, the only way I know to mitigate it, is with the preprocessor...
#define FWD(...) std::forward<decltype(__VA_ARGS__)>(__VA_ARGS__)

With that in hand, we can refactor your function to use an IILE to generate that pack only once:
template<class ...T>
void f(T&&... t)
{
    [](auto&&... pack) {
        auto check = (FWD(pack) && ...);
        if (check == false) {
            return;
        }
        details::act(FWD(pack)...);
    }(details::transform(FWD(t))...);
}

That way, you only call transform once per argument. I assume that's the net goal. Otherwise, you can probably use the preprocessor to generate something simpler without a lambda.

A: You can't do that. Your two variadic expressions expand to different patterns. The best you can do is something like this (without macros):
template<class ...T>
void f(T&&... t)
{
    using details::transform;
    // (T&&)t == std::forward<T>(t);

    auto check = (transform((T&&)t) && ...);
    if (check == false) {
        return;
    }
    details::act(transform((T&&)t)...);
}


text:
Q: Best way to populate a page with dynamic content I have been thinking about this for some time now, for the purpose of an example lets say we have index.php which has a whole bunch of content and a search box, when a user inputs data into the search box results appear below such as images and data for each result.
What is the best way to populate these results?
Example one

AJAX Post to results.php which echos the complete results including
      HTML and aesthetic tags. Then back on the first page include
      all the data that was returned using .html(data);

Example Two

Have the skeleton of the results and hide them, (wrapper
      divs and everything that is included for each result)
      And then AJAX and retrieve data and populate the divs and show them

Or any other suggestions you may have?

A: *

*User enters in search term.

*Perform AJAX GET to results.php.

*Return data from results.php in JSON format.

*Replace search results with said data.

A: this is in the index.php
$('#search').live('click',function(){
  $.ajax({
    url: 'result.php',
    data: {keyword: $('#search_box').val()},
    type: 'POST',
    dataTupe: 'json',
    success: function(response){
      $('.result_box').html(response['data']);
    }
  });
});

this is how your result.php swill look like
$keyword = $_POST['keyword'];
$result = getResults($keyword);
die(json_encode(array('data'=>$result)));

getResults function should be where you retrieve the data based on your keyword search.
hope this helps.

A: If the structure doesn't change, it is better to use JSON and populate in the local JavaScript.
Consider there are set of books. Around 100. And if you gonna output the HTML to be updated, it would surely cost much. While, you output just the thing like:
{
    success:true,
    rows:[{
        "id":"1",
        "title":"Office Space",
        "director":"Mike Judge",
        "released":"1999-02-19",
        "genre":"1",
        "tagline":"Work Sucks",
        "coverthumb":"84m.jpg",
        "price":"19.95",
        "available":"1"
    },{
        "id":"3",
        "title":"Super Troopers",
        "director":"Jay Chandrasekhar",
        "released":"2002-02-15",
        "genre":"1",
        "tagline":"Altered State Police",
        "coverthumb":"42m.jpg",
        "price":"14.95",
        "available":"1"
    },{
        "id":"4",
        "title":"American Beauty",
        "director":"Sam Mendes",
        "released":"1999-10-01",
        "genre":"2",
        "tagline":"... Look Closer",
        "coverthumb":"12m.jpg",
        "price":"19.95",
        "available":"1"
    },{
        "id":"5",
        "title":"The Big Lebowski",
        "director":"Joel Coen",
        "released":"1998-03-06",
        "genre":"1",
        "tagline":"The \"Dude\"",
        "coverthumb":"49m.jpg",
        "price":"21.90",
        "available":"1"
    },{
        "id":"6",
        "title":"Fight Club",
        "director":"David Fincher",
        "released":"1999-10-15",
        "genre":"3",
        "tagline":"How much can you know about yourself...",
        "coverthumb":"94m.jpg",
        "price":"19.95",
        "available":"1"
    }]
}

This can be very well parsed by jQuery.parseJSON and displayed as table or inside lis or complex divs.

A: It really depends on what's easier for you in terms of current page structure and the structure of received data. Both approaches are completely fine, although I might be leaning a bit towards the first one since it's easier to use and you can format the output in the PHP file (in case you need that)... yet the only difference is basically the amount of data received by AJAX and with today's internet speeds, a couple of HTML tags along with the content won't make much of a difference.

A: The second option is much better IMHO, use JSON to grab the data, and worry about inserting it on the client side, after you retrive it. Think about it this way: the less data you're sending / receiving the better.
Here's couple of points

*

*The code is easier to maintain, if you're just passing JSON, and your views have to change at a later date.

*Code is more readable for devs if they're just passing JSON, they can fix issues with the data easier without having to go through lots of layout HTML structure.

A: Both is possibel but going with the full html answer (option 1) is better in most cases.
If you have a dynamic php page you shoulld use a template engine.
I usually end up with multiple templates: A main template with the page structure, a menu template, a article template ... and in your case the result template.
Then you can make your search request with or without ajax. If js is enabled you just render the results with the "result" template; return the html fragment and insert it into the apropiate point of your page.
If js is diasbled, you request a new page which renders the results in a new Page.
You COULD use a js template engine too, but so far I have found none which has a decent implementation in PHP and js.

A: JSON is the best option as it sends a lot less data. An example straight from Jquery docs showing that you don't need to generate a skeleton for your data. As you can see the only thing you need to create is a container to hold the elements created from the javascript. <img> tags are created as needed and appended in to the specified images div container.
<!DOCTYPE html>
<html>
<head>
    <style>img{ height: 100px; float: left; }</style>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="images">

</div>
<script>
    $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
        {
            tags: "mount rainier",
            tagmode: "any",
            format: "json"
        },
        function(data) {
            $.each(data.items, function(i,item){
                $("<img/>").attr("src", item.media.m).appendTo("#images");
                if ( i == 3 ) return false;
            });
        });</script>

</body>
</html>


text:
Q: Trying to prove a property for the region of convergence of a Laplace transform I've been studying Schaum's outlines for Signals and Systems, and came across this:

And I understood the part until $$ \int_{t_{1}}^{t_{2}} |x(t)|e^{-\sigma_{0}}e^{-(\sigma_{1}-\sigma_{0})t}\,dt $$
Where did the $$ -\sigma_{0} -(\sigma_{1} - \sigma_{0})t $$ come from? Did the book add/divide the process? It didn't really explain what to do before that, so I might have overlooked something.
I got that the exponential with complex values is equal to one because of the absolute value, but after that, I get a bit lost by the addition of another exponential


text:
Q: Find the residue of $e^{\frac{1}{z^2-1}}\sin(\pi z)$ at $z=1$ I'm dealing with the following problem (from an old qualifying exam):

Let $\gamma$ be a closed curve in the right half-plane that has index $N$ with respect to the point 1. Find
  $$
\int_{\gamma}e^{\frac{1}{z^2-1}}\sin(\pi z)\,dz.
$$

I take this problem as, "Find $\text{Res}\left(f,1\right)$," where $f$ is the integrand. For an essential singularity like I believe $f$ has at $z=1$, you have to expand into the Laurent series. This is the closest I got: By partial fraction decomposition,
$$
\frac{1}{z^2-1}=\frac{1}{2(z-1)}-\frac{1}{2(z+1)},
$$
So
$$
f(z)=e^{\frac{1}{2(z-1)}}e^{-\frac{1}{2(z+1)}}\sin(\pi z)=\frac{1}{2i}e^{\frac{1}{2(z-1)}}\sin\left(\frac{z\pi}{2(z+1)}\right).
$$
If I could magically find a Taylor expansion about $z=1$ of $\sin\left(\frac{z\pi}{2(z+1)}\right)$ I'd be all set, but it seems quite disgusting to work out. I've also tried integrating over a simpler closed curve containing $z=1$ but I can't seem to find something that turns out integrable. Any help is greatly appreciated. Thanks.

A: Expanding the functions $\exp$ and $\sin$ in Laurent series we get
[
\begin{align}
 \exp \left( {\frac{1}{{z^2  - 1}}} \right) = \sum {\frac{1}{{\left( {z^2  - 1} \right)^n n!}}}  = \sum {\frac{1}{{\left( {z + 1} \right)^n \left( {z - 1} \right)^n n!}}}  = \sum {\frac{{\frac{1}{{\left( {z + 1} \right)^n }}}}{{\left( {z - 1} \right)^n n!}}}
\end{align}
Also,
\begin{align}
 \sin \pi z = \sin \pi \left( {z + 1 - 1} \right)=\sin \left( {\pi \left( {z - 1} \right) + \pi } \right) = \sin \pi \left( {z - 1} \right)\cos \pi  + \sin \pi \cos \pi \left( {z - 1} \right) \\
  =  - \sin \pi \left( {z - 1} \right)
 \end{align}
and since
\begin{align}
\sin z = \sum {\frac{{\left( { - 1} \right)^n }}{{\left( {2n + 1} \right)!}}z^{2n + 1} }  \Rightarrow \sin \pi \left( {z - 1} \right) = \sum {\frac{{\left( { - 1} \right)^n }}{{\left( {2n + 1} \right)!}}\pi ^{2n + 1} \left( {z - 1} \right)^{2n + 1} }
\end{align}
Thus,
\begin{align}
&\exp \left( {\frac{1}{{z^2  - 1}}} \right)\sin \pi \left( {z - 1} \right)
\\
&=  - \left( {\sum {\frac{1}{{\left( {z + 1} \right)^n \left( {z - 1} \right)^n n!}}} } \right)\left( {\sum {\frac{{\left( { - 1} \right)^n }}{{\left( {2n + 1} \right)!}}\pi ^{2n + 1} \left( {z - 1} \right)^{2n + 1} } } \right) \
\\
&=- \left( {1 + \frac{{\frac{1}{{\left( {z + 1} \right)}}}}{{\left( {z - 1} \right)}} + \frac{{\frac{1}{{\left( {z + 1} \right)^2 }}}}{{\left( {z - 1} \right)^2 2!}} + \frac{{\frac{1}{{\left( {z + 1} \right)^3 }}}}{{\left( {z - 1} \right)^3 3!}} + \frac{{\frac{1}{{\left( {z + 1} \right)^4 }}}}{{\left( {z - 1} \right)^4 4!}} + \frac{{\frac{1}{{\left( {z + 1} \right)^5 }}}}{{\left( {z - 1} \right)^5 5!}}  +   \cdots } \right) \\
  &\times \left( {\pi \left( {z - 1} \right) - \frac{{\pi ^3 }}{{3!}}\left( {z - 1} \right)^3  + \frac{{\pi ^5 }}{{5!}}\left( {z - 1} \right)^5  +  \cdots   +  \cdots } \right) \\
 &\Rightarrow \text{The coefficient of }\frac{1}{z-1}=-
\left( {\frac{\pi }{{1!2!}}\frac{1}{{\left( {z + 1} \right)^2 }} - \frac{{\pi ^3 }}{{3!4!}}\frac{1}{{\left( {z + 1} \right)^4 }} + \frac{{\pi ^5 }}{{5!6!}}\frac{1}{{\left( {z + 1} \right)^6 }} +  \ldots  } \right)
\\
&=
 - \sum {\frac{{\left( { - 1} \right)^n \pi ^{2n + 1} }}{{n!\left( {n + 1} \right)!}}\frac{1}{{\left( {z + 1} \right)^{2n + 2} }}}
  = g\left( z \right)
\end{align}
\begin{align}
{\mathop{\rm Res}\nolimits} \left\{ {f\left( z \right),1} \right\} = g\left( 1 \right)
 =
 - \sum {\frac{{\left( { - 1} \right)^n \pi ^{2n + 1} }}{{n!\left( {n + 1} \right)!}}\frac{1}{{2^{2n + 2} }}}
\end{align}


text:
Q: Open in next editor disabled automatically in Xcode Suddenly the open in next editor is disabled automatically in Xcode.
I can't open one more text editor or storyboard. It's disabled for only one project only.
Anyone know how to enable it? Thank you!

A: The editor is focussed.

*

*Click on the  icon
or

*Select menu View > Editor > Focus or

*Press ⇧⌥⌘↩


text:
Q: How to hard-code pass a variable from template B coming "from template A to Template B" to a route function? I'm building a web application that shows a list of books, the user clicks on a book, and he is directed to a book contains another list of the information of that book.
Books.html redirects the user to review.html, the problem is url_for function in books.html file doesn't work as intended.
books.html file is a bootstrap 4 predefined list, I've just the  link
to href="{{url_for('review', book_id=book.id)}}"
@app.route("/books")
def books():
    ''' show books in a list. '''

    # Select book info based on first characters.
    books = db.execute("SELECT * FROM books WHERE isbn LIKE :isbn", {"isbn":"0"+"%"})

    if books is None:
        raise RuntimeError("Error @ books route, Didn't fetch rows from books table.")

    return render_template("books.html",books=books)

@app.route("/books/<int:book_id>")
def review(book_id):
    ''' Show book information inner and API '''

    # Get book information from books table using book_id got from books.html
    bookInfo = db.execute("SELECT * FROM books WHERE id=:book_id", {"book_id": book_id}).fetchone()

    # Error handling.
    if bookInfo is None:
        raise RuntimeError("Error @ route: review, didn't fetch book information from books table.")

return render_template("review.html", bookInfo=bookInfo)

{% extends "base.html" %}

{%block body%}

    {% for book in books %}

{{book.title}}

ISBN: {{book.isbn}}

author: {{book.author_name}}

        publication year: {{book.publish_year}}

    {%endfor%}

{%endblock%}

{% extends "base.html" %}

{%block body%}]

Book title

{{bookInfo.title}}

Book author

{{bookInfo.author_name}}

ISBN

{{bookInfo.isbn}}

Publication year

{{bookInfo.publish_year}}

{%endblock%}

I expect to have a list of information about the book the user picked, but instead, I get this error:
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.


text:
Q: What to do about equality constraints in the Simplex Tableau method The question I've got is: Maximise $$2x-y+3z$$
subject to $$2y+z \leq 2$$ $$x+y+z=4$$ $$x-2y+z \geq 3$$ $$x,y,z \geq 0$$
Using the Simplex Tableau method. I know that for $\leq$ constraints you need slack variables, for $\geq$ you need slack and artificial variables, but what are you supposed to do with the equality constraint? I read a lecture online where it said convert it to both a $\leq$ and a $\geq$ constraint, so in this case we would have: $$ x+y+z=4$$ can be written as $x+y+z\leq 4$ and $x+y+z\geq 4$ but then it went onto say that we could just neglect the second constraint which would yield $-x-y-z\leq 4$.
Could anyone give anymore clarification if this is indeed correct and if so, why we get the final result from the two inequalities?

A: To get an optimal solution, it is necessary to have a basic solution as a starting point. This means, that the number of constraints must be equal to the number of basic variables. Thus every constraint has to have a positive slack variable or a positive artificial variable. If the slack variable is negative or is not needed, then you add an artificial variable.
There are three cases:
$\color{blue}{\leq \texttt{constraint:}}$
If you have a $\leq$-constraint, then you have to add a slack variable for each constraint.
$2y+z  \leq 2 \quad \Longrightarrow \quad 2y+z +s_1=2$
$\color{blue}{=\texttt{constraint:}}$
If you have a $=$-constraint, then you do not have to add a slack variable for each constraint. But you have to add an artificial variable for each constraint.
$x+y+z=4 \quad \Longrightarrow \quad x+y+z+a_1=4$
$\color{blue}{\geq \texttt{constraint:}}$
If you have a $\geq$-constraint, then you have to substract a slack variable for each constraint. Additionally you have to add an artificial variable for each constraint.
$x-2y+z \geq 3 \quad \Longrightarrow \quad x-2y+z-s_2+a_2 = 3$
The initial simplex tableau is
$\begin{array}{|c|c|c|c|c|c|c|c|} \hline x & y & z & s_1 & s_2 & a_1 & a_2 & RHS \\ \hline -2 & 1 & \color{green}{-3} & 0 & 0 & 0 & 0 & 0 \\ \hline 0 & 2 & \color{red} 1 & 1 & 0 & 0 & 0 & \color{orange}{2} \\ \hline 1 & 1 & 1 & 0 & 0 & 1 & 0 & 4 \\ \hline 1 & -2 & 1 & 0 & -1 & 0 & 1 & 3  \\ \hline \end{array} $
The coefficients of the objective function have to be multiplied by (-1), because the objective function has to be maximized.
The initial basic solution is $(x, y, z, s_1, s_2, a_1, a_2)=(0, 0, 0, 2, 0, 4, 3)$
The first pivot element is the red One.


text:
Q: How can I sync events from yahoo/google calendar with MySql? - in PHP for a web app I want to make a web app that will show some data from a MySQL database, and I need it to be able to connect to Yahoo/Google calendars from each user, so the user will add his calendar when he registers. Is that possible?

A: Google Calendar allows Web application developers to access user-generated content and event information through its REST-based Developer API. PHP's SimpleXML extension and Zend's GData Library are ideal for processing the XML feeds generated by this API and using them to build customized PHP applications. This article introduces the Google Calendar Data API, demonstrates how you can use it to browse user-generated calendars; add and update calendar events; and perform keyword searches.
Here is the article tutorial for that go to this link and learn how to do that. I think that will help you.


text:
Q: Can't send auth headers with axios Can't send authorization header with rest API. Got 'OPTIONS' error with status 0. All headers and options are allowed on the server. Server is written on PHP.
Here is my request:
axios.post(`${API_URL}users/${23}/profile/main/update`,
    {formData},{
    headers:{ 'Content-Type':'multipart/form-data',
    Authorization:`Bearer ${token}`}
    })

It seems like it does not send the header when there is authorization. However, it works, if i delete authorization, and leave only content type

A: This should do the trick
axios({
 method: 'POST',
 url:`${API_URL}users/${23}/profile/main/update`,
 headers: {
    'Content-Type':'multipart/form-data',
    'Authorization':`Bearer ${token}`},
 data: formData
})

Refer docs for browser

A: Try to send as below:
var headers = {
  'Content-Type': 'multipart/form-data',
  'Authorization': `Bearer ${token}`
}

axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData}, headers)

Try using Ajax call below:
import $ from 'jquery';

$.ajax({
  url:`${API_URL}users/${23}/profile/main/update`,
  processData: false,
  contentType: false,
  data : formData,
  method : "POST",
  headers: {
    "Authorization": `Bearer ${token}`
  }
});

A: I had this same issue, it is possible that you are not passing the sent auth header from your apache config to your php application.
you might need to set

WSGIPassAuthorization On

inside your virtualhost config.
Check this


text:
Q: Windows Batch file to start multiple services in sequence I need to create a batch file to start a handful of Windows services, which need to start in a certain order. Also the last three services can only start when the service previous has started up (can take about 30 seconds for this to happen).
I was going to use SC START <SERVIVENAME>
How can I make the last three servies wait until the previous has started?


text:
Q: Connecting to database within ssh'ed application I've setup a systemd-nspawn container with my development environment. I start Intellij Idea within this container via:
ssh -Y user@development idea.sh

Now, when I try to connect the database console to my database server, running in a Windows VM, I get a timeout and the connection fails. Testing if the server is reachable with netcat works fine. The container, the Windows VM and the host are connected to a network bridge, each with it's own IP.
So: What must be done to successfully connect Intellij Idea via JDBC to my database server in this setup?
So far, I've tried a port forwarding ssh -Y -L1234:database:1234 user@development idea.sh with no success.

A: You must choose remote port forwarding -R instead of local port forwarding -L. The correct shell command would be:
ssh -Y -R1234:database:1234 user@development idea.sh


text:
Q: Rewrite Rule: Subdirectory to Subdirectory? I want to rewrite from a subdirectory to a subdirectory.
Example, I have an application on http://example.com/level1/level2.
Now I want to be able to visit http://example.com/level1 and the application should be opened which is on http://example.com/level1/level2.
Im just trying to figure out the rewrite rule since 2 hours, but nothing seems to work.
Is this even possible, or is rewriting only possible from root directory?
Thanks

A: put this code in your  /level1/.htaccess file:
RewriteEngine On
RewriteBase /level1/

RewriteRule ^((?!level2/).*)$ level2/$1 [L,NC]


text:
Q: Why is CH true if it cannot be proved? Continuum hypothesis (CH) states that there can be no set whose cardinality is strictly between that of integers and real numbers. Godel, 1940 and Paul Cohen,1963 showed that CH can neither be proved nor be disproved.
How can we assert that a statement is true if it cannot be proven? What are the bases to make such assertions? I know this is a deep subject, and I confess that I don't have technical tools to understand everything on this topic. But I would like to have some understanding on why CH has to be true if it cannot be proven.
Do you have any other examples where statements are absolutely true (i.e with 100% certainty) but cannot be proved??
EDIT: Is "CH cannot be proved" the same as "proof will not exist ever in future"? Or is it that "CH cannot be proved" implies the insufficient human knowledge to prove it?

A: In mathematics, and in particular when talking about the incompleteness phenomenon, there is a grave danger of confusing the two terms "True" and "Provable".
Being "true" is a semantic property of a statement. Statements are true in a particular interpretation of the language, or a particular model of a theory. Whereas being provable is a syntactical property which means that there is a sequence statements which are axioms, or inferences from the axioms which is both finite, and its final statement is the statement we wanted to prove.
The completeness theorem tells us that $T$ proves a statement if and only if the statement is true in every model of $T$. So we sometimes abuse the meaning and say things like "Cantor's theorem is true in $\sf ZF$" when we mean that $\sf ZF$ can prove Cantor's theorem.
Sometimes, as in the case of arithmetic, there is an intended interpretation or a standard model for the theory. With the integers we have a standard model that we know to characterize. That is the model we care about. So in the context of Peano's axioms of arithmetic we say that $\varphi$ is true if it is true in the standard model, and provable if it is true in every model. However $\sf ZFC$ is far from $\sf PA$ in this context, and it does not have a standard or intended interpretation (in set theory the term "standard model" means something which is far more arbitrary than in $\sf PA$).
So finally we ask what does it mean for $\sf CH$ to be true? Since we don't have a standard model for set theory, we can't associate some "Platonic truth" to the statement in the language of set theory. Some will be true in some models, and some will be false in other models. The continuum hypothesis - and its negation - are both such statement. And when we say that the continuum hypothesis is not provable from the axioms of $\sf ZFC$, we mean that mathematically we have proved that this statement does not have a proof from the axioms. How did we do that? We showed that there models where it is true, and models where it is false (assuming there are models to begin with, of course).
So saying that $\sf CH$ is true, but not saying where is meaningless in the sense that it doesn't offer sufficient information to properly evaluate the claim. It is true in $L$, which is Godel's constructible universe (i.e. in every model of set theory satisfying the statement $V=L$ the continuum hypothesis is true). But it need not be true in other models of set theory (e.g. models of $\sf PFA$).
Edit:
From the question's comments it shows that the question rose after reading a statement of the form "the continuum hypothesis is true for all practical purposes" and "the continuum hypothesis is true for Borel sets". The statement simply say that if we are only concerned about Borel sets (or some other indicated family of sets) then they are either countable, or have the cardinality of the continuum.
Historically when Cantor set to prove his continuum hypothesis, it was simply to find a bijection between open intervals and the real numbers; and using a clever method he showed that uncountable closed sets must have the cardinality of the continuum. Cantor expected that these proofs can carry on on some "complexity" of sets, and eventually cover all the sets. However the construction of taking complement and countable unions only gives us the Borel sets, and indeed shortly after leaving the Borel sets one can already run into classes which do not have to satisfy the continuum hypothesis.

Further reading:

*

*Why is the Continuum Hypothesis (not) true?

*Unprovable things

*Neither provable nor disprovable theorem


text:
Q: Using pull-right inside element aligns the text with the center. How do I align it with the baseline So, I've looked around SO, and I've found the inverse of this question mostly everywhere. That makes me feel this is either a rarer occurrence, or something trivial that I just can't figure out.
https://jsfiddle.net/je5dpqrL/
The above jsFiddle shows that I have an
 element within which I've put an anchor tag with the pull-right class of Bootstrap. Since I want the anchor to display in a smaller font, I'm using font-weight and font-size. Now, since it's floating, the text is centered.
Is there any way to align the text so that the baseline of the Title and the  element is the same?

A: You can adjust the vertical position of the  with line-height (and use for example em to make it relative size):
.cl {
    font-weight: normal;
    font-size: 40%;
    display: inline-block;
    line-height:4em
}

A: This is what you need https://jsfiddle.net/p05bu4c2. Create a span inside the link

.cl {
 font-weight: normal;
 font-size: 40%;
 display: inline-block;
}
.cl span {
 line-height: 1;
 vertical-align: bottom;
}

h2 {
    border:1px solid #ff0000;
}

Title Stuff

A: So, The following code seems to work:

TextTest

Turns out that adding an .inside-block to an element inside the .pull-right class seems to fix it. No need to play around with line-heights
JSFiddle: https://jsfiddle.net/je5dpqrL/10/
EDIT: Thanks to Diamond for this suggestion of adding an element inside the  tag, although the CSS is completely different from the one suggested by him.