text:
Q: Sourcetree + Git clone stuck at "Updating files 100%" Problem
I am getting stuck at "Updating files: 100%" when cloning a git repo on Windows when using Sourcetree.
Full output
git -c filter.lfs.smudge= -c filter.lfs.required=false -c diff.mnemonicprefix=false -c core.quotepath=false --no-optional-locks clone --branch master https://[REDACTED] C:\Users\[REDACTED]
Cloning into 'C:\Users\[REDACTED]'...
Updating files:  11% (1860/16666)
Updating files:  12% (2000/16666)
[...]
Updating files:  98% (16333/16666)
Updating files:  99% (16500/16666)
Updating files: 100% (16666/16666)
Updating files: 100% (16666/16666), done.

Versions

*

*Sourcetree: 3.4.8.0

*Git (Embedded): 2.35.0

(Note that I think I had this issue on earlier versions as well a few months ago.)

A: Configure Sourcetree to use System git instead of Embedded git as a workaround.
See Sourcetree -> Options -> Git -> Git Version
(Note: Git (System) version is 2.35.1)


text:
Q: Android : convert an audio file into array of complex numbers (for FFT) In order to process a FFT on an audio signal, I first need to convert my audio file into an array of complex numbers. I still don't understand if this part requires to save a .CSV of .TXT file on my sd card or if I can simply stock data in my application as a variable.
I would simply like to understand how this part really works in order to go further in my FFT program : from my .3gpp audio file (by the way, is it a good format to use for what I am doing?) saved on my sd card, what should I do to have my array of complex numbers, the input for the FFT ?
If anyone has an example of existing code used to convert audio file to binary data, I would really appreciate to take a look at it and to understand how to implement it in my activity.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Не работают генераторы Не работают генераторы, выкидывает ошибку
 Can't find variable: regeneratorRuntime

вот код где возникает ошибка
 function* generateSequence() {
  yield 1;
  yield 2;
  return 3;
}

let generator = generateSequence();

let one = generator.next();

console.log(JSON.stringify(one));

Вот скомпилированный код webpack.
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;
/******/
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            exports: {},
/******/            id: moduleId,
/******/            loaded: false
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.loaded = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "/static/";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

    "use strict";

    var _marked = [generateSequence].map(regeneratorRuntime.mark);

    function generateSequence() {
      return regeneratorRuntime.wrap(function generateSequence$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return 1;

            case 2:
              _context.next = 4;
              return 2;

            case 4:
              return _context.abrupt("return", 3);

            case 5:
            case "end":
              return _context.stop();
          }
        }
      }, _marked[0], this);
    }

    var generator = generateSequence();

    var one = generator.next();

    console.log(JSON.stringify(one));

/***/ }
/******/ ]);
//# sourceMappingURL=main.js.map

Вот часть конфига webpack
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        plugins: ['transform-runtime'],
        loader: 'babel-loader',
        query: {presets: ['es2015', 'react', 'stage-2']}
      }
    ]

A: Нужно было добавить transform-regenerator в плагины
{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: {
      presets: ['es2015', 'react', 'stage-2'],
      plugins: [
        ["transform-runtime"],
        ["transform-regenerator"]
      ],
   }
}


text:
Q: Hibernate performs insert instead of update I am using hibernate for a kind of music management thing.
The song entity looks like this:
@Entity
@Table(name = "Song")
public class Song implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "artist_id")
    private Artist artist;
}

The artist entity looks like this:
@Entity
@Table(name = "Artist")
public class Artist implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    private String name;
}

The problem I am facing right now is that if I post a Song with artist "abc" and after that another Song with artist "abc" another entry in the artist database will be created.
Is there a way to make hibernate look for those "duplicates" or do I have to do this myself?


text:
Q: couldn't find setup.py file in my cdk project in cloud9 i'm trying to start cdk project (python)
according to the tutorial i need to work on app-stack.py file and set-up.py file
but i can't find the second fileThis Is the created project
this is the tutorial project


text:
Q: Error in cordova android app with ConnectivityManager Hi cordova and android masters) I new in "cordova development".
I built android app on cordova. My app can open files with use of com.megster.cordova.FileChooser plugin. But since august app has a error when selecting and open file (file storage in FS on android device).
In logcat of AndroidStudio I have warnings:
2019-12-02 18:50:02.532 10395-10395/com.quaternity.offline W/cr_AwContents: WebView.destroy() called while WebView is still attached to window.
2019-12-02 18:50:02.617 10395-10395/com.quaternity.offline W/cr_AwContents: Application attempted to call on a destroyed WebView
    java.lang.Throwable
        at org.chromium.android_webview.AwContents.a(PG:355)
        at org.chromium.android_webview.AwContents.r(PG:636)
        at aIE.loadingStateChanged(PG:135)
        at android.os.MessageQueue.nativePollOnce(Native Method)
        at android.os.MessageQueue.next(MessageQueue.java:328)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:6253)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
2019-12-02 18:50:02.633 10395-10479/com.quaternity.offline E/ConnectivityManager.CallbackHandler: callback not found for RELEASED message

I don't now what to do. I have changed version of cordova, of android platform and change others filechooser plugins, but it's not help.
Now my cordova version 8.1.2, android version 7.1.4. Do anyone had such problem?


text:
Q: Define a callback for command start I am trying to automatically time execution of all top-level expressions.  Task Handlers are almost what is needed, however they are called only after the command completes, rather than before.
An alternative approach would be to modify every top-level expression to be wrapped in system.time, however I am not aware of a method to do this either.

A: For completeness here is a function you can use as a task callback to automatically cause a system notification for any top level command that takes more than 5 seconds to run.
# devtools::install_github("gaborcsardi/notifier")
notify_long_running <- function(second_cutoff = 5) {
  last <- proc.time()[1]
  function(expr, value, ok, visible) {
    duration <- proc.time()[1] - last
    if (duration > second_cutoff) {
      notifier::notify(msg = paste0(collapse = " ", deparse(expr)),
                       title = sprintf("Completed in %.02f (s)", duration))
    }
    last <<- proc.time()[1]
    TRUE
  }
}

addTaskCallback(notify_long_running())

A: Two years late, but try this solution to automatically time all commands:
proc <- function(...) {
    utime <- proc.time()[1]
    utime_diff <- utime-get0(".prev_time", envir=globalenv(), ifnotfound=0)
    options(prompt=paste0(utime_diff,"s> "))
    assign(".prev_time", utime, envir=globalenv())
    return(TRUE)
    }
ret <- addTaskCallback(proc)

The "user time" returned by proc.time doesn't increment when idle, so it'll only calculate the time spent running the command.
This gives you pretty close to accurate measure, down to a 10th of a second at least:
start_time <- proc.time()[1]

st_time <- system.time({for(x in 1:10000000) {
    log(x)
}})[1]

pt_time <- proc.time()[1] - start_time

print(paste("time using proc.time()", pt_time))
print(paste("time using syste.time()", st_time))

"time using proc.time() 1.908"
"time using syste.time() 1.884"

A: There's no real way to profile "top-level commands" because R doesn't know what those are. How are you defining them?
If system.time is not granular enough for you (because it doesn't look at individual pieces of code), my suggestion would be to go in the opposite direction and use Rprof, which allows you to start and stop the timing of expressions and, on output (summaryRprof()) prints a breakdown by function call. Mind you, this is by function call, not by "top-level function" call: if you're looking specifically for R to benchmark whatever you think of as a top-level function, system.time may indeed be your best bet


text:
Q: git: reset submodule branch to remote tag I have a main module with tags and I have some submodules under the main module.
I want to reset the main module to a specific tag (example "v2.11.0") and reset the submodules to this tag also. the tag is only in the main module, so it is a remote tag for the submodules.
git fetch --all --tags
git reset --hard tags/v2.11.0
git submodule foreach --recursive git checkout -B master
git submodule foreach --recursive git reset --hard tags/v2.11.0

Resetting the main module to the tag works. But resetting the submodules to the remote tag doesnt work with the code above.
Do you know whats wrong?
Greetz

A: A tag is a name for a commit.  The tags/v2.11.0 tag in the superproject is therefore a name for—that is, represents the number, or hash ID of—a particular commit in the superproject.  So this:

git fetch --all --tags
git reset --hard tags/v2.11.0

is a little weird,1 but not entirely crazy.
Each submodule, though, is a separate Git repository.  That separate Git repository may or may not have a tag v2.11.0; if it does have such a tag, that tag will represent some other commit that exists in that other Git repository:

the tag is only in the main module ...

I presume that this means that each submodule has no such tag.

... so it is a remote tag for the submodules

No, it's not.  There's no such thing as a "remote tag".  A tag is just a name for a commit hash ID, and in any given repository, you either have the tag, or you don't.  If you don't have the tag, you don't have that name.  Some other repository's tag is a name for some hash ID in that repository.
Git is all about commits.  Each commit has a unique hash ID.  That's a lot of what you're doing with Git: you might use a branch name like master or develop or whatever, or a tag name like v2.11.0, but you're really telling Git get me commit b0ff0cab1e....  (The full hash ID is long and ugly, but you can find it with:
git rev-parse tags/v2.11.0

for instance.)
A normal way to use a superproject is to have, in the superproject commit, the correct hash ID for each submodule.  That's part of the commit itself, as an entity that Git calls a gitlink.  Checking out the superproject commit results in putting that gitlink into the superproject Git's index.  That Git's index now holds, as a path-name-and-hash-ID pair like path/to/submodule and feedc0ffee..., the commit that one might want the submodule to git checkout (as a detached HEAD).
If you want to make each submodule be a detached HEAD at that commit, you would now run:
git submodule update checkout

or:
git submodule update --recursive checkout

to make the submodule itself recursively check out any of its own submodules.

1The --all option to git fetch means fetch from all remotes.  This makes a little bit of sense in the context in which you're using it, since each remote could have some set of tags, and this would get your Git to copy all of their tags, into a massive tag-union.  If there are conflicts—if remote A says that tag v1.2.3 should mean deadbeef and remote B says that tag v1.2.3 should mean feedf00d, whichever one you pick up first "wins", in general.
The git reset --hard is likely the wrong thing to do.  If you're already on a detached HEAD, this is like doing a git checkout of the given tag, with the side effect of throwing away any work that has not yet been committed.  If you are on a branch name, this alters the stored hash ID in that branch name, which is probably wrong.
Overall, it is probably more sensible to run git fetch --tags, without --all, to fetch from the current remote, or to pick a specific remote to trust; or if there's only one remote, git fetch --tags will use that one remote and then --all is unnecessary.  Then, having done that, use git checkout tags/v2.11.0 or git switch --detach tags/v2.11.0, which will complain if there is uncommitted work.

A: git submodule update --init --recursive
git submodule foreach git checkout -f -B master

This will set the submodules to the commits which belong to the superproject tag. Afterwards the master branch will be checked out on this commit.


text:
Q: Selectbox overlapping The Superfish Menu Bar The menu bar is a superfish 3-layer menu.
The code for the css of the menu bar is  :-
 /*** ESSENTIAL STYLES ***/
.sf-menu, .sf-menu * {
    margin:         0;
    padding:        0;
    list-style:     none;
}
.sf-menu {line-height:  1.0;}
.sf-menu ul {
    position:       absolute;
    top:            -999em;
    width:          11em; /* left offset of submenus need to match (see below) */
}
.sf-menu ul li {width:100%;}
.sf-menu li:hover {visibility:inherit; /* fixes IE7 'sticky bug' */}
.sf-menu li {
    float:          left;
    z-index:        9999;     #######Edited the Z-index here##########
    position:       relative;
}
.sf-menu a {display:block;position: relative;}
.sf-menu li:hover ul,
.sf-menu li.sfHover ul {
    left:           0;
    top:            2.5em; /* match top ul list item height */
    z-index:        99;
}
ul.sf-menu li:hover li ul,
ul.sf-menu li.sfHover li ul {top:-999em;}
ul.sf-menu li li:hover ul,
ul.sf-menu li li.sfHover ul {left:11em; /* match ul width */top:0;}
ul.sf-menu li li:hover li ul,
ul.sf-menu li li.sfHover li ul {top:-999em;}
ul.sf-menu li li li:hover ul,
ul.sf-menu li li li.sfHover ul {left:10em; /* match ul width */top: 0;}

/*** DEMO SKIN ***/
.sf-menu {float:left;margin-bottom: 1em;}
.sf-menu ul {box-shadow: 2px 2px 6px rgba(0,0,0,.2);}
.sf-menu a {
    border-left:    1px solid #fff;
    border-top:     1px solid #CFDEFF;
    padding:        .75em 1em;
    text-decoration:none;
}
.sf-menu a, .sf-menu a:visited  { /* visited pseudo selector so IE6 applies text colour*/
    color:          #13a;
}
.sf-menu li {background:#BDD2FF;}
.sf-menu li li {background:#AABDE6;}
.sf-menu li li li {background:#9AAEDB;}
.sf-menu li:hover, .sf-menu li.sfHover,
.sf-menu a:focus, .sf-menu a:hover, .sf-menu a:active {
    background:     #CFDEFF;
    outline:        0;
}

Html code for the select box is :-
<select name="designation" id="designation" class=forCombobox>
<option value="">--Select--</option>
</select>

CSS for forCombobox : -
    .forCombobox
{
    font-family: Verdana;
    font-size: 11px;
    color: #000000;
    z-index:-1;
    border: 1px outset;
    border-color:#58585A;
}

I have set the Z-index as 9999 ...still the menu bar is overlapping the select Box.
And the select box has no Z-index set .
What to do...?

A: From w3schools.com:

The z-index property specifies the stack order of an element.
An element with greater stack order is always in front of an element with a lower stack order.
Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed).


text:
Q: How to access errors when using WebdriverJS? We are using the superb WebdriverJS (with Selenium) to perform acceptance testing on our web app.  Everything works fine, and our tests execute successfully when we use Firefox and Safari.
However, when we use PhantomJS, our tests fail with unhelpful errors.  It's almost as if... Javascript isn't even running inside the client page!  Something that would cause this would be if PhantomJS' javascript environment ran into errors.  Unfortunately, I can't seem to find a way to access Javascript errors when using PhantomJS with WebdriverJS.
If we were using PhantomJS directly, we could simply do (from the PhantomJS site):
page.onError = function(msg, trace) {
  console.log(msg);
  trace.forEach(function(item) {
    console.log('  ', item.file, ':', item.line);
  });
}

Unfortunately, I don't know how to access this mysterious page object when using PhantomJS within WebdriverJS.  Any thoughts?

A: You can actually access JS errors in your PhantomJS stdout log at INFO level.
$ phantomjs --webdriver 4444 --webdriver-loglevel=INFO
You can even push things forward by setting the log level to DEBUG and see what actually PhantomJS does to execute the commands you send through Webdriver / Ghostdriver.

A: I figured out a workable solution!  Essentially, it involves using an onerror event handler to intercept (and store) the Javascript errors.  Then, once the DOM is ready, we report the errors via hidden DOM elements.  This allows Selenium to look for specific elements (e.g. ".javascript-errors"), which is something it's naturally quite good at.  Thanks go to myriad other blog posts and SO questions for getting me to this point.
The code:
//For detecting and reporting Javascript errors via Selenium.  Note that this should be in its own file to allow this code to reliably detect syntax errors in other files.
var errors = [];

//Handle all errors
window.onerror = function(message, url, line) {
    errors.push({"message":message, "url":url, "line":line});
}

//Report errors visually via HTML once the DOM is ready
window.onload = function() {
    if(errors.length==0)
        return;

  var div = document.createElement("div");
  div.className = 'javascript-errors';
  div.innerHTML = '';
    var style = "position:absolute; left:-10000px; top:auto; width:1px; height:1px;"; //CSS to hide the errors; we can't use display:none, or Selenium won't be able to read the error messages.  Adapted from http://webaim.org/techniques/css/invisiblecontent/

    for(var i=0; i<errors.length; i++)
      div.innerHTML += '
' + errors[i].message.replace('<', '<').replace('>', '>') + '
' + errors[i].url + '
' + errors[i].line + '
';

    document.body.appendChild(div);
}


text:
Q: Why is string search not working? I am attempting to create an automatically updating worksheet which tracks all the positions of where the text boxes line up in terms of columns. This is to create a gantt chart. basically when i drag the text box it is to tell me what week it is in and every time I change one text box it will update that. The following picture illustrates this well.
The issue is when i keep dragging the text box and change positions over and over again, the weeks dont overwrite the previous week7-week13 but just concatenates the new position ontop of the old one as follows:

I am trying to write an if statement which basically says that if the substring "week" in in the caption then parse the multi-line textbox into lines and overwrite the first line with the new position.
This is the code I wrote I just need help with this if statement:
Option Explicit
Public alltxt As String
Private selectText() As String

Private Sub CommandButton1_Click()
    UF1.Show
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim ws As Worksheet
    Set ws = Target.Parent
    Dim temp
    Dim i
    Dim pos

    Dim shp As Shape
    Dim line As Variant
    For Each shp In ws.Shapes   'loop through all shapes
        If shp.Type = msoTextBox Then 'that are text boxes
            'write the header cells into the text box
            temp = shp.OLEFormat.Object.Caption
            **If InStr(temp, "week")= 0 Then**
                shp.OLEFormat.Object.Caption = ws.Cells(1, shp.TopLeftCell.Column).Text & " - " & ws.Cells(1, shp.BottomRightCell.Column).Text & vbNewLine & shp.OLEFormat.Object.Caption
                Else
                    selectText = Split(shp.OLEFormat.Object.Caption, vbNewLine)
                    selectText(0) = ws.Cells(1, shp.TopLeftCell.Column).Text & " - " & ws.Cells(1, shp.BottomRightCell.Column).Text
                End If

        End If
    Next shp
End Sub

Any push in the right direction would be greatly appreciates. And please keep in mind I am relatively new to vba so this may be a really easy fix.
Thanks in advance

A: I think your if condition is fine, but there seems to be an error in the else part
EDIT: The final if condition could be modified to:
If InStr(temp, "week")= 0 Then
    shp.OLEFormat.Object.Caption = ws.Cells(1, shp.TopLeftCell.Column).Text & " - " & ws.Cells(1, shp.BottomRightCell.Column).Text & vbNewLine & shp.OLEFormat.Object.Caption
Else
    selectText = Split(shp.OLEFormat.Object.Caption, Chr(10))
    shp.OLEFormat.Object.Caption = ws.Cells(1, shp.TopLeftCell.Column).Text & " - " & ws.Cells(1, shp.BottomRightCell.Column).Text
    for i=1 to UBound(selectText)
        shp.OLEFormat.Object.Caption = shp.OLEFormat.Object.Caption & vbNewLine & selectText(i)
    Next i
End If

Care for the OS dependent new line character (See vbNewline vs Chr(10) as linebreak delimiter in Windows vs. Mac OSX)


text:
Q: Can I prevent SWF hotlinking with htaccess? I have a website with some Flash games. I noticed that someone somehow copied my entire website using an online tool. I was notified by the security I implemented into my server.
It seems this person is using a tool to scrape everything, because I visited his website and saw this on a page: "This file was not retrieved by Teleport Pro, because it was unavailable, or its retrieval was aborted, or the project was stopped too soon."
He/she managed to get all the static content of my website and the SWF of the games. Luckily my files communicate with files from my server in order for the game to start, so he cannot use the games.
I would like to prevent this from being done again in the future. Probably the solution would be to disable SWF hotlinking? If so, I need to know how this can be done using .htaccess or Apache.
I need some advice about what can I possibly do, and if is there a way to protect a website from these scraping tools.

A: If you require a referrer for your HTML files, that means people will not be able to deep-link to them legitimately from other sites. You can certainly do this for assets, but then any thief worth their salt will know what you have done, and will fake the referrer in order to get the files anyway. This is unfortunately a fairly trivial thing to do, and thus probably not worth your time.
So, the main thing left to do is what you have done already - prevent the Flash applications from starting up unless they can contact your site and obtain permission. It may be worth your looking at some professional AS/Flex libraries for this - I would guess they exist in a commercial form.
Even better, if the games can periodically have a need to access your server, maybe for assets or level maps, you'll give your opponents enough reverse-engineering to make it not worth their while.


text:
Q: Highlight RibbonButton after clicking is there any chance to highlight RibbonButton after clicking and remove it after clicking again? Im using xaml and code behind event after clicking button.

A: Try using a RibbonToggleButton instead, it should have the behavior you're looking for. If you want to keep track of the state of the button you can set a binding on the isChecked property which will be true when the button is highlighted.


text:
Q: Binary tree node with pointer to siblings in Rust I am trying to figure out the equivalent of the typical setSibling C code exercise:
// Assume the tree is fully balanced, i.e. the lowest level is fully populated.
struct Node {
   Node * left;
   Node * right;
   Node * sibling;
}

void setSibling(Node * root) {
   if (!root) return;
   if (root->left) {
      root->left->sibling = root->right;
      if (root->sibling) root->right->sibling = root->sibling->left;
      SetSibling(left);
      SetSibling(right);
   }
}

Of course Rust is a different world, so I am forced to think about ownership now. My lousy attempt.
struct TreeNode<'a> {
    left: Option<&'a TreeNode<'a>>,
    right: Option<&'a TreeNode<'a>>,
    sibling: Option<&'a TreeNode<'a>>,
    value: String
}

fn BuildTreeNode<'a>(aLeft: Option<&'a TreeNode<'a>>, aRight: Option<&'a TreeNode<'a>>, aValue: String) -> TreeNode<'a> {
    TreeNode {
        left: aLeft,
        right: aRight,
        value: aValue,
        sibling: None
    }
}

fn SetSibling(node: &mut Option<&TreeNode>) {
    match node {
        Some(mut n) => {
            match n.left {
                Some(mut c) => {
                    //c*.sibling = n.right;
                    match n.sibling {
                        Some(s) => { n.right.unwrap().sibling = s.left },
                        None => {}
                    }
                },
                None => {}
            }
        },
        None => return
    }
}

What's the canonical way to represent graph nodes like these?

A:
Question: what's the canonical way to represent graph nodes like these?

It seems like a typical case of "confused ownership" once you introduce the sibling link: with a strict tree you can have each parent own its children, but the sibling link means this is a graph, and a given node has multiple owners.
AFAIK there are two main ways to resolve this, at least in safe Rust

*

*reference counting and inner mutability, if each node is reference-counted, the sibling link can be a reference or weak reference with little trouble, the main drawbacks are this requires inner mutability and the navigation is gnarly, though a few utility methods can help

*"unfold" the graph into an array, and use indices for your indirection through the tree, the main drawback is this requires either threading or keeping a backreference (with inner mutability) to the array, or alternatively doing everything iteratively

Both basically work around the ownership constraint, one by muddying the ownership itself, and the other by moving ownership to a higher power (the array).
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=68d092d0d86dc32fe07902c832262ef4 seems to be more or less what you're looking using Rc & inner mutability:
use std::cell::RefCell;
use std::rc::{Rc, Weak};

#[derive(Default)]
pub struct TreeNode {
    left: Option<Rc<TreeNode>>,
    right: Option<Rc<TreeNode>>,
    sibling: RefCell<Option<Weak<TreeNode>>>,
    v: u8,
}

impl TreeNode {
    pub fn new(v: u8) -> Rc<Self> {
        Rc::new(TreeNode {
            v,
            ..TreeNode::default()
        })
    }
    pub fn new_with(left: Option<Rc<TreeNode>>, right: Option<Rc<TreeNode>>, v: u8) -> Rc<Self> {
        Rc::new(TreeNode {
            left,
            right,
            v,
            sibling: RefCell::new(None),
        })
    }
    pub fn set_siblings(self: &Rc<Self>) {
        let Some(left) = self.left() else { return };
        let right = self.right();

        left.sibling.replace(right.map(Rc::downgrade));

        if let Some(sibling) = self.sibling() {
            // not sure this is correct, depending on construction, with
            // 3  5
            //  \  \
            //  2  4
            //   \/
            //   1
            // (2) has a sibling (4) but doesn't have a right node, so
            // unconditionally setting right.sibling doesn't seem correct
            right
                .unwrap()
                .sibling
                .replace(sibling.left().map(Rc::downgrade));
        }

        left.set_siblings();
        right.map(|r| r.set_siblings());
    }

    pub fn left(&self) -> Option<&Rc<Self>> {
        self.left.as_ref()
    }
    pub fn right(&self) -> Option<&Rc<Self>> {
        self.right.as_ref()
    }
    pub fn sibling(&self) -> Option<Rc<Self>> {
        self.sibling.borrow().as_ref()?.upgrade()
    }
}

fn main() {
    let t = TreeNode::new_with(
        TreeNode::new_with(TreeNode::new(1).into(), TreeNode::new(2).into(), 3).into(),
        TreeNode::new(4).into(),
        5,
    );
    t.set_siblings();

    assert_eq!(t.left().and_then(|l| l.sibling()).unwrap().v, 4);
    let ll = t.left().and_then(|l| l.left());
    assert_eq!(ll.map(|ll| ll.v), Some(1));
    ll.unwrap().sibling().unwrap();
    assert_eq!(
        t.left()
            .and_then(|l| l.left())
            .and_then(|ll| ll.sibling())
            .unwrap()
            .v,
        2
    );
}

Note that I assumed the tree is immutable once created, only the siblings links have to be generated post-facto. So I only added inner mutability for those. I also used weak pointers which probably isn't necessary, if the tree is put in an inconsistent state it's not like that'll save anything. All it requires is a few upgrade() and downgrade() calls in stead of clone() though so it's not a huge imposition.
That aside, there are lots of issues with your attempt:

*

*having the same lifetime for your reference and your content is usually an error, the compiler will trust what you tell it, and that can have rather odd effects (e.g. of telling the compiler that something gets borrowed forever)

*SetSibling (incorrect naming conventions btw) taking an Option is... unnecessary, function clearly expects to set a sibling, just give it a sibling, and remove the unnecessary outer layer of tests

*match is nice, when you need it. Here, you probably don't, if let would do the trick fine especially since there is no else branch

*rust generally uses methods, and the method to create an instance (if one such is needed) is idiomatically called new (if there's only one)


text:
Q: PHP $_Session , JS not allowing member login after successful username and password inserted so, this implementation worked with an md5 password check but after implementing a password hash check (for a safer password storage in my database) the member is not allowed to log in. The user after typing the correct email and password is only brought back to the index.php page. Any help would be appreciated. this is my session.php code:
<?php
     session_start();
    //Check whether the session variable SESS_MEMBER_ID is present or not
    // do check

    if(!isset($_SERVER['HTTP_REFERER'])){
        // redirect them to your desired location
        header('Location: custom_404.html');
        exit;
    }
    if (!isset($_SESSION['alogin']) || (trim($_SESSION['alogin']) == '')) { ?>
    <!-- send to home page -->
    <script>
    window.location = "../index.php";
    </script>
    <?php
    }
    $session_id=$_SESSION['alogin'];
    $session_depart = $_SESSION['arole'];
    ?>

here is what should work within index.php:
    <?php
    session_start();
    include('includes/config.php');
    if(isset($_POST['signin']))
    {
        $username=$_POST['username'];
        $username=strtolower($username);
        $password=$_POST['password'];

        $sql ="SELECT * FROM tblemployees where EmailId = '$username'";
        $query= mysqli_query($conn, $sql);
        $count = mysqli_num_rows($query);

        if($count>0)
        {
            $passwordCheck = mysqli_fetch_assoc($query)['Password'];
            if(!password_verify($password,$passwordCheck)){
                echo "<script>alert('Wrong password please try again.');</script>";
            }
            while ($row = mysqli_fetch_assoc($query)) {
                if ($row['role'] == 'Admin') {
                    $_SESSION['alogin']=$row['emp_id'];
                    $_SESSION['arole']=$row['Department'];
                    echo "<script type='text/javascript'> document.location = 'admin/admin_dashboard.php'; </script>";
                }
                elseif ($row['role'] == 'Staff') {
                    $_SESSION['alogin']=$row['emp_id'];
                    $_SESSION['arole']=$row['Department'];
                    echo "<script type='text/javascript'> document.location = 'staff/index.php'; </script>";
                }
                else {
                    $_SESSION['alogin']=$row['emp_id'];
                    $_SESSION['arole']=$row['Department'];
                    echo "<script type='text/javascript'> document.location = 'heads/index.php'; </script>";
                }
            }
        }
        else{

          echo "<script>alert('Wrong email or password please try again.');</script>";

        }

    }
    // $_SESSION['alogin']=$_POST['username'];
    //  echo "<script type='text/javascript'> document.location = 'changepassword.php'; </script>";
    ?>

A: Your login code is wrong. The loop
while ($row = mysqli_fetch_assoc($query))

is never fetching anything, because you already read the row with
$passwordCheck = mysqli_fetch_assoc($query)['Password'];

You should just fetch the row once, and use that for both the password and role checks.
You also should use a prepared statement to prevent SQL injection.
<?php
session_start();
include('includes/config.php');
if(isset($_POST['signin']))
{
    $username=$_POST['username'];
    $username=strtolower($username);
    $password=$_POST['password'];

    $sql ="SELECT * FROM tblemployees where EmailId = ?";
    $stmt= mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "s", $username);
    mysqli_stmt_execute($stmt);
    $query = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_assoc($query);
    if($row)
    {
        $passwordCheck = $row['Password'];
        if(!password_verify($password,$passwordCheck)){
            echo "<script>alert('Wrong email or  password please try again.');</script>";
        } else {
            if ($row['role'] == 'Admin') {
                $_SESSION['alogin']=$row['emp_id'];
                $_SESSION['arole']=$row['Department'];
                echo "<script type='text/javascript'> document.location = 'admin/admin_dashboard.php'; </script>";
            }
            elseif ($row['role'] == 'Staff') {
                $_SESSION['alogin']=$row['emp_id'];
                $_SESSION['arole']=$row['Department'];
                echo "<script type='text/javascript'> document.location = 'staff/index.php'; </script>";
            }
            else {
                $_SESSION['alogin']=$row['emp_id'];
                $_SESSION['arole']=$row['Department'];
                echo "<script type='text/javascript'> document.location = 'heads/index.php'; </script>";
            }
        }
    }
    else{
        echo "<script>alert('Wrong email or password please try again.');</script>";
    }

}
// $_SESSION['alogin']=$_POST['username'];
//  echo "<script type='text/javascript'> document.location = 'changepassword.php'; </script>";
?>


text:
Q: Is it true that $\lim_{n\to \infty} \dfrac{\int_{\frac{1}{n}}^{1}\frac{f(x)}{x}dx}{n}=0$? Suppose $f$ is $L^{1}[0,\infty)$ and non-negative, and $\int_{0}^{\infty}f(x)dx=1$.
Is it true that $lim_{n\to \infty} \dfrac{\int_{\frac{1}{n}}^{1}\frac{f(x)}{x}dx}{n}=0$?
I derive this problem from a probability problem where I am asked to compute a limit of an expectation and $f$ is the probability density function. However, I cannot make an estimate for this integral.
Thanks!

A: Hint: You can rewrite the limit as
$$\lim\limits_{n\rightarrow\infty}{\left(\int\limits_{0}^{1}{\frac{f(x)}{nx}\mathbb{1}_{[1/n,1]}(x)\text{ d}x}\right)}. $$
Show that
$$\left|\frac{f(x)}{nx}\mathbb{1}_{[1/n,1]}(x)\right|\le|f(x)|$$
for all $x$ and $n$. Then apply the Dominated Convergence Theorem.


text:
Q: How Gulp + sourcemaps work for debugging So I just got set up with Gulp yesterday and after a rocky start I'm well on my way to automating build processes, but I decided to try and do something a teensy bit trickier and suddenly hit another wall.
My desired output is to have a minified javascript file which I can serve to the browser and, upon inspecting in Chrome or Firefox, see the original source code. Pretty simple, right?
I currently have the following in my gulpfile:
gulp.task('minify', function() {
    gulp.src('./sources/**/*.js')
    .pipe(sourcemaps.init())
    .pipe(minify({
        ext:{
            src:'.js',
            min:'.min.js'
        }
    }))
    .pipe(sourcemaps.write('maps'))
    .pipe(gulp.dest('./www/js'));
});

This successfully generates the sourcemaps in ./www/js/maps/ and it puts the following at the bottom of the uncompressed files:
//# sourceMappingURL=maps/<whatever>.js.map

However it does not append such a comment to the bottom of the compressed files. As such when I open these files in a browser it's unable to show me the original source.
What am I doing wrong?

A: You can try this:
gulp.task('minify', function() {
    gulp.src('./sources/**/*.js')
    .pipe(sourcemaps.init())
    .pipe(minify({
        ext:{
            src:'.js',
            min:'.min.js'
        }
    }))
    .pipe(sourcemaps.write('maps', {
      addComment: true
    }))
    .pipe(gulp.dest('./www/js'));
});


text:
Q: Docker container 'Connect ECONNREFUSED localhost' I am running a simple Nodejs application with 2 containers. A server container and a client. I have a setup so that when the client makes a request to the server, it streams some data back to the client, however when I try to make this request from the client, I receive the following error
connect ECONNREFUSED 127.0.0.1:8080

This is also the case when I use the containers IP address. Both containers are on the same network. I confirmed this with docker network inspect. When I make the same request via Postman, it works fine.
Here is my setup
Server Setup
Server Dockerfile
FROM node:12
EXPOSE 8080
WORKDIR /home/node/server
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "app.js"]

Server http function
http.createServer(function(request, response){
    filePath = path.join("./serverdata", 'filename.txt');
    var stat = fs.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'text/plain',
        'Content-Length': stat.size
    });

    var readStream = fs.createReadStream(filePath);
    readStream.pipe(response);
})
.listen(port);

Client Setup
Client Dockerfile
FROM node:12
WORKDIR /home/node/client
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "capp.js"]

Client Get Function
NB using the server container IP yielded same results
http.get('http://localhost:8080', (resp)=>{
    let data = '';

    resp.on('data', (chunk)=>{
        data += chunk;
    });

    resp.end('end', ()=>{
        console.log(data);
    });
}).on("error", (err)=>{
    console.log(err.message);
});

Docker Compose
version: "3.2"

services:
  server-app:
    build: ./serverClient
    ports:
      - 8080:8080
    volumes:
      - servervol:/serverdata

  client-app:
    build: ./clientClient
    ports:
      - 8081:8081
    volumes:
      - clientvol:/clientdata
    depends_on:
      - "server-app"

volumes:
  servervol:
    driver: local
  clientvol:
    driver: local

I have read a few posts proclaiming that the issue is with using localhost instead of the container IP, but I have tried both with no success. As mentioned, when done in Postman, it works fine; this leads me to think that the issue is with the client part. Any guidance is much appreciated.
Thanks

A: Since you are using Docker Compose, by default (because you didn't specify network) your services share the same (default) network, and therefore you can use the name of the service instead of its IP address to communicate with it because Docker can figure out the IP address based on service name due to service name resolution.
And because of all that Docker magic, the only thing you need to change is the way you connect to server:
http.get('server-app:8080', (resp) => { ... })


text:
Q: MongoServerSelectionError: getaddrinfo ENOTFOUND at Timeout._onTimeout So you may have seen this question type somewhere else. but the thing here is I tried all of the things we need to do according to docs and saw other posts with similar errors but still my error is not fixed. So I use keyv and use MongoDB atlas as storage adapter in this code, but the error is from MongoDB. Also, there is no error in the "keyv" because it works for other people, there is error in the MongoDB
So now I will list whatever I tried:
1. Made sure there is IP access
2. The userid and passcode are correct
3. The MongoDB atlas is running
4. Read the docs and code multiple times
5. If u think adding the +srv with the code will fix the error, it won't, it doesn't work with keyql idk why also it is not present in many codes, I already tried it

So this is the code
const { Client, Intents, MessageEmbed, Collection } = require('discord.js');
let client = new Client({ intents: [Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES] });
const dotenv = require('dotenv');
const Keyv = require('keyv');
const keyv = new Keyv('mongodb://Discord:password@cluster0.auifa.mongodb.net/Cluster0');
dotenv.config();

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', async (msg) => {
     if (msg.author.bot) return;
    let number = msg.content.split(' ')[1];
    if (msg.content === '!ping') {
        msg.channel.send('ping!')
    }

// Use like const prefix = await getGuildPrefix(); `
    const getGuildPrefix = async () => {
        const prefixMap = await keyv.get('prefix');
        return prefixMap ?. [msg.guild.id] || "!"
    }

// Sets the prefix to the current guild.
    const setGuildPrefix = async (prefix) => {
        let prefixMap = await keyv.get('prefix');
        if (!prefixMap)
    {
     prefixMap = "!";
    }
        prefixMap[msg.guild.id] = prefix;
        await keyv.set('prefix', `${prefixMap}`);
    }

    let prefix = await getGuildPrefix();
// Get prefix command.
    if ((msg.content === `${process.env.prefix}prefix`) || (msg.content === `${prefix}prefix`)) {
        msg.channel.send(`Your server prefix is ${prefix}`)
    }

// Change prefix command
    const commandPrefix = await getGuildPrefix();
    if ((msg.content.startsWith(`${process.env.prefix}setprefix`)) || (msg.content.startsWith(`${commandPrefix}setprefix`))) {
        const newPrefix = number;

        if (newPrefix.length === 0) {
            msg.channel.send(`Please enter a valid prefix`);
        }

        await setGuildPrefix(newPrefix)
        msg.channel.send(`Your server prefix is now '${newPrefix}'`);
    }
})
client.login(process.env.token);

And this is the error message
Keyv connection error: MongoServerSelectionError: getaddrinfo ENOTFOUND cluster0.auifa.mongodb.net
    at Timeout._onTimeout (D:\javascript\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7) {
  reason: TopologyDescription

A: Connection string does not look like an Atlas one.
It has to be something like: mongodb+srv://<username>:<password>@cluster0.auifa.mongodb.net/YOUR-DB
Login to your Atlas account then:

*

*Go to Databases page

*Click on Connect button

*Choose "Connect your application"

*Copy your connection string

Docs about Mongo Atlas connection: https://docs.atlas.mongodb.com/connect-to-cluster/#connect-to-a-cluster


text:
Q: How to make table resize automaticly Left block with 2s overflowing with text and resizing. But right blocks don't. I want to make blocks with 4s and 5s automatically resize to the top of the block with 7s. How can I do this?
I want to keep a table-like design with any amount of text or any size.
No grid or flexbox allowed

HTML:
<!DOCTYPE html>

  <link rel="stylesheet" href="styles.css">

  11 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 1111

    222 22 2222222 22222222 222222222 222222222222222 222222   22222222222 22 2222222 22222222 222222222 222222222222222 222222   22222222222 22 2222222 22222222 222222222 222222222222222 222222   22222222222 22 2222222 22222222 222222222 2222222222222
    222 22 2222222 22222222 222222222 222222222222222 222222   22222222222 22 2222222 22222222 222222222 222222222222222 222222   22222222222 22 2222222 22222222 222222222 222222222222222 222222   22222222222 22 2222222 22222222 222222222 222222222222222 222222   22222222222 22 2222222 22222222 222222222 222222222222222 222222   22222222222 22 2222222 22222222 222222222 222222222222222 222222   2222222222 222222   22222222222 22 2222222 22222222 222222222 222222222222222 222222   22222222222 22 2222222 22222222 222222222 222222222222222 222222   22222222

3333 33333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 333333

444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444

6 6666 6 66 66666 666 6 6666 6 66 66666 666 6 6666 6 66 66666 666 666

5555 555 5 55 55555555 555 5 55 55555555 555 5 55 55555555 555 5 55 5555

  77 7 7 7777 777 7777 77 7 7 7777 777 7777 77 7 7 7777 777 7777 777

CSS:
body{
    border: 1px solid #000;
    display: table;
}

.header{
    display: table-header-group;
    background-color: lightblue;
    height: 15vh;
}

.footer{
    display: table-footer-group;
    background-color: lightblue;
    height: 15vh;
}

.rowgroup{
    display: table-row-group;
}

.cell{
    display: table-cell;

}

.row{
    display: table-row;

}

.caption{
    display: table-caption;
}

.left{
    background-color: peachpuff;
    height: fit-content;
    min-height: 70vh;
    width: 25vw;
    /*overflow-wrap: break-word;*/
}

.top{
    background-color: lightgreen;
    height: fit-content;
    min-height: 10vh;
    /*overflow-wrap: break-word;*/
}

.right{
    background-color: peachpuff;
    height: fit-content;
    min-height: 60vh;
    width: 25vw;
}

.bottom{
    background-color: lightgreen;
    height: fit-content;
    min-height: 10vh;
}

.middle{
    background-color: whitesmoke;
    height: fit-content;
    min-height: 50vh;
}

.block{
    padding: 2vh;
}

StackOverflow wants me to add some details, but I already upload an image.

A: You need to add diplay: flex.

            11 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111
            1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1
            11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11
            1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11
            1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11
            1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11
            1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11 1111 1 1 111111 1 11
            1111 1 1 1111

            222 22 2222222 22222222 222222222 222222222222222 222222 22222222222 22 2222222 22222222 222222222
            222222222222222 222222 22222222222 22 2222222 22222222 222222222 222222222222222 222222 22222222222 22
            2222222 22222222 222222222 2222222222222
            222 22 2222222 22222222 222222222 222222222222222 222222 22222222222 22 2222222 22222222 222222222
            222222222222222 222222 22222222222 22 2222222 22222222 222222222 222222222222222 222222 22222222222 22
            2222222 22222222 222222222 222222222222222 222222 22222222222 22 2222222 22222222 222222222 222222222222222
            222222 22222222222 22 2222222 22222222 222222222 222222222222222 222222 2222222222 222222 22222222222 22
            2222222 22222222 222222222 222222222222222 222222 22222222222 22 2222222 22222222 222222222 222222222222222
            222222 22222222

3333 33333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333
                3333 3 33333333333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3
                33333333333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333
                3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 33333333333 3333 3333 3 333333

444 4444 4444444444 4444 4444444444 4444 4444444444 4444
                            4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444
                            4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444 4444444444 4444
                            4444444444 4444

6 6666 6 66 66666 666 6 6666 6 66 66666 666 6 6666 6 66 66666 666
                            666

5555 555 5 55 55555555 555 5 55 55555555 555 5 55 55555555 555 5 55 5555

            77 7 7 7777 777 7777 77 7 7 7777 777 7777 77 7 7 7777 777 7777 777

also, for the CSS part, you'll need to change your min-height or create a class specific for the box of 6s.
.bottom{
    background-color: lightgreen;
    height: fit-content;
    min-height: 10vh;
}

I hope that helps.
Also, I'm not sure what you're building, but I suggest you take a look at HTML tables.
Good luck!


text:
Q: Running scipy.integrate.ode in multiprocessing Pool results in huge performance hit I'm using python's scipy.integrate to simulate a 29-dimensional linear system of differential equations. Since I need to solve several problem instances, I thought I could speed it up by doing computations in parallel using multiprocessing.Pool. Since there is no shared data or synchronization necessary between threads (the problem is embarrassingly parallel), I thought this should obviously work. After I wrote the code to do this, however, I got very strange performance measurements:

*

*Single-threaded, without jacobian: 20-30 ms per call

*Single-threaded, with jacobian: 10-20 ms per call

*Multi-threaded, without jacobian: 20-30 ms per call

*Multi-threaded, with jacobian: 10-5000 ms per call
What's shocking is that what I thought should be the fastest setup, was actually the slowest, and the variability was two orders of magnitude. It's a deterministic computation; computers aren't supposed to work this way. What could possibly be causing this?
Effect seems system-dependent
I tried the same code on another computer and I didn't see this effect.
Both machines were using Ubuntu 64 bit, Python 2.7.6, scipy version 0.18.0, and numpy version 1.8.2. I didn't see the variability with an Intel(R) Core(TM) i5-5300U CPU @ 2.30GHz processor. I did see the issue with an Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz.
Theories
One thought was that there might be a shared cache among processors, and by running it in parallel I can't fit two instances of the jacobian matrix in the cache, so they constantly battle each other for the cache slowing each other down compared with if they are run serially or without the jacobian. But it's not a million variable system. The jacobian is a 29x29 matrix, which takes up 6728 bytes. The level 1 cache on the processor is 4 x 32 KB, much larger. Are there any other shared resources between processors that might be to blame? How can we test this?
Another thing I noticed is that each python process seems to take several hundred percent of the CPU as it's running. This seems to mean that the code is already parallelized at some point (perhaps in the low-level library). This could mean that further parallelization wouldn't help, but I wouldn't expect such a dramatic slowdown.
Code
It would be good to try out the on more machines to see if (1) other people can experience the slowdown at all and (2) what are the common features of systems where the slowdown occurs. The code does 10 trials of two parallel computations using a multiprocessing pool of size two, printing out the time per scipy.ode.integrate call for each of the 10 trials.
'odeint with multiprocessing variable execution time demonsrtation'

from numpy import dot as npdot
from numpy import add as npadd
from numpy import matrix as npmatrix
from scipy.integrate import ode
from multiprocessing import Pool
import time

def main():
    "main function"

    pool = Pool(2) # try Pool(1)
    params = [0] * 2

    for trial in xrange(10):
        res = pool.map(run_one, params)
        print "{}. times: {}ms, {}ms".format(trial, int(1000 * res[0]), int(1000 * res[1]))

def run_one(_):
    "perform one simulation"

    final_time = 2.0
    init_state = [0.1 if d < 7 else 0.0 for d in xrange(29)]
    (a_matrix, b_vector) = get_dynamics()

    derivative = lambda dummy_t, state: npadd(npdot(a_matrix, state), b_vector)
    jacobian = lambda dummy_t, dummy_state: a_matrix
    #jacobian = None # try without the jacobian

    #print "jacobian bytes:", jacobian(0, 0).nbytes

    solver = ode(derivative, jacobian)
    solver.set_integrator('vode')
    solver.set_initial_value(init_state, 0)

    start = time.time()
    solver.integrate(final_time)
    dif = time.time() - start

    return dif

def get_dynamics():
    "return a tuple (A, b), which are the system dynamics x' = Ax + b"

    return \
    (
        npmatrix([
        [0, 0, 0, 0.99857378006, 0.053384274244, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        [0, 0, 1, -0.003182219341, 0.059524655342, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        [0, 0, -11.570495605469, -2.544637680054, -0.063602626324, 0.106780529022, -0.09491866827, 0.007107574493, -5.20817921341, -23.125876742495, -4.246931301528, -0.710743697134, -1.486697327603, -0.044548215175, 0.03436637817, 0.022990248611, 0.580153205353, 1.047552018229, 11.265023544535, 2.622275290571, 0.382949404795, 0.453076470454, 0.022651889536, 0.012533628369, 0.108399390974, -0.160139432044, -6.115359574845, -0.038972389136, 0, ],
        [0, 0, 0.439356565475, -1.998182296753, 0, 0.016651883721, 0.018462046981, -0.001187470742, -10.778778281386, 0.343052863546, -0.034949331535, -3.466737362551, 0.013415853489, -0.006501746896, -0.007248032248, -0.004835912875, -0.152495086764, 2.03915052839, -0.169614300211, -0.279125393264, -0.003678218266, -0.001679708185, 0.050812027754, 0.043273505033, -0.062305315646, 0.979162836629, 0.040401368402, 0.010697028656, 0, ],
        [0, 0, -2.040895462036, -0.458999156952, -0.73502779007, 0.019255757332, -0.00459562242, 0.002120360732, -1.06432932386, -3.659159530947, -0.493546966858, -0.059561101143, -1.953512259413, -0.010939065041, -0.000271004496, 0.050563886711, 1.58833954495, 0.219923768171, 1.821923233098, 2.69319056633, 0.068619628466, 0.086310028398, 0.002415425662, 0.000727041422, 0.640963888079, -0.023016712545, -1.069845542887, -0.596675149197, 0, ],
        [-32.103607177734, 0, -0.503355026245, 2.297859191895, 0, -0.021215811372, -0.02116791904, 0.01581159234, 12.45916782984, -0.353636907076, 0.064136531117, 4.035326800046, -0.272152744884, 0.000999589868, 0.002529691904, 0.111632959213, 2.736421830861, -2.354540136198, 0.175216915979, 0.86308171287, 0.004401276193, 0.004373406589, -0.059795009475, -0.051005479746, 0.609531777761, -1.1157829788, -0.026305051933, -0.033738880627, 0, ],
        [0.102161169052, 32.057830810547, -2.347217559814, -0.503611564636, 0.83494758606, 0.02122657001, -0.037879735231, 0.00035400386, -0.761479736492, -5.12933410588, -1.131382179292, -0.148788337148, 1.380741054924, -0.012931029503, 0.007645723855, 0.073796656681, 1.361745395486, 0.150700793731, 2.452437244444, -1.44883919298, 0.076516270282, 0.087122640348, 0.004623192159, 0.002635233443, -0.079401941141, -0.031023369979, -1.225533436977, 0.657926151362, 0, ],
        [-1.910972595215, 1.713829040527, -0.004005432129, -0.057411193848, 0, 0.013989634812, -0.000906753354, -0.290513515472, -2.060635522957, -0.774845915178, -0.471751979387, -1.213891560083, 5.030515136324, 0.126407660877, 0.113188603433, -2.078420624662, -50.18523312358, 0.340665548784, 0.375863242926, -10.641168797333, -0.003634153255, -0.047962774317, 0.030509705209, 0.027584169642, -10.542357589006, -0.126840767097, -0.391839285172, 0.420788121692, 0, ],
        [0.126296110212, -0.002898250629, -0.319316070797, 0.785201711657, 0.001772374259, 0.00000584372, 0.000005233812, -0.000097899495, -0.072611454126, 0.001666291957, 0.195701043078, 0.517339177294, 0.05236528267, -0.000003359731, -0.000003009077, 0.000056285381, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        [-0.018114066432, 0.077615035084, 0.710897211118, 2.454275059389, -0.012792968774, 0.000040510624, 0.000036282541, -0.000678672106, 0.010414324729, -0.044623231468, 0.564308412696, -1.507321670112, 0.066879720068, -0.000023290783, -0.00002085993, 0.000390189123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        [-0.019957254425, 0.007108972111, 122.639137999354, 1.791704310155, 0.138329792976, 0.000000726169, 0.000000650379, -0.000012165459, -8.481152717711, -37.713895394132, -93.658221074435, -4.801972165378, -2.567389718833, 0.034138340146, -0.038880106034, 0.044603217363, 0.946016722396, 1.708172458034, 18.369114490772, 4.275967542224, 0.624449778826, 0.738801257357, 0.036936909247, 0.020437742859, 0.176759579388, -0.261128576436, -9.971904607075, -0.063549647738, 0, ],
        [0.007852964982, 0.003925745426, 0.287856349997, 58.053471054491, 0.030698062827, -0.000006837601, -0.000006123962, 0.000114549925, -17.580742026275, 0.55713614874, 0.205946900184, -43.230778067404, 0.004227082975, 0.006053854501, 0.006646690253, -0.009138926083, -0.248663457912, 3.325105302428, -0.276578605231, -0.455150962257, -0.005997822569, -0.002738986905, 0.082855748293, 0.070563187482, -0.101597078067, 1.596654829885, 0.065879787896, 0.017442923517, 0, ],
        [0.011497315687, -0.012583019909, 13.848373855148, 22.28881517216, 0.042287331657, 0.000197558695, 0.000176939544, -0.003309689199, -1.742140233901, -5.959510415282, -11.333020298294, -14.216479234895, -3.944800806497, 0.001304578929, -0.005139259078, 0.08647432259, 2.589998222025, 0.358614863147, 2.970887395829, 4.39160430183, 0.111893402319, 0.140739944934, 0.003938671797, 0.001185537435, 1.045176603318, -0.037531801533, -1.744525005833, -0.972957942438, 0, ],
        [-16.939142002537, 0.618053512295, 107.92089190414, 204.524147386814, 0.204407545189, 0.004742101706, 0.004247169746, -0.079444150933, -2.048456967261, -0.931989524708, -66.540858220883, -116.470289129818, -0.561301215495, -0.022312225275, -0.019484747345, 0.243518778973, 4.462098610572, -3.839389874682, 0.285714413078, 1.40736916669, 0.007176864388, 0.007131419303, -0.097503691021, -0.083171197416, 0.993922379938, -1.819432085819, -0.042893874898, -0.055015718216, 0, ],
        [-0.542809857455, 7.081822285872, -135.012404429101, 460.929268260027, 0.036498617908, 0.006937238413, 0.006213200589, -0.116219147061, -0.827454697348, 19.622217613195, 78.553728334274, -283.23862765888, 3.065444785639, -0.003847616297, -0.028984525722, 0.187507140282, 2.220506417769, 0.245737625222, 3.99902408961, -2.362524402134, 0.124769923797, 0.142065016461, 0.007538727793, 0.004297097528, -0.129475392736, -0.050587718062, -1.998394759416, 1.072835822585, 0, ],
        [-1.286456393795, 0.142279456389, -1.265748910581, 65.74306027738, -1.320702989799, -0.061855995532, -0.055400100872, 1.036269854556, -4.531489334771, 0.368539277612, 0.002487097952, -42.326462719738, 8.96223401238, 0.255676968878, 0.215513465742, -4.275436802385, -81.833676543035, 0.555500345288, 0.612894852362, -17.351836610113, -0.005925968725, -0.078209662789, 0.049750119549, 0.044979645917, -17.190711833803, -0.206830688253, -0.638945907467, 0.686150823668, 0, ],
        [0, 0, 0, 0, 0, -0.009702263896, -0.008689641059, 0.162541456323, 0, 0, 0, 0, 0, 0, 0, 0, -0.012, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        [-8.153162937544, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        [0, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        [0, 0, 0, 0.17441246156, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        [0, 0, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.5, -18, 0, 0, 0, 0, 0, 0, 0, ],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ],
        [0, 0, 0, -8.153162937544, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.5, -18, 0, 0, 0, 0, 0, ],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, ],
        [0, 0, 0, 0, 0, 0, 0, 0, 0.699960862226, 0.262038222227, 0.159589891262, 0.41155156501, -1.701619176699, -0.0427567124, -0.038285155304, 0.703045934017, 16.975651534025, -0.115788018654, -0.127109026104, 3.599544290134, 0.001229743857, 0.016223661959, -0.01033400498, -0.00934235613, -6.433934989563, 0.042639567847, 0.132540852847, -0.142338323726, 0, ],
        [0, 0, 0, 0, 0, 0, 0, 0, -37.001496211974, 0.783588795613, -0.183854784348, -11.869599790688, -0.106084318011, -0.026306590251, -0.027118088888, 0.036744952758, 0.76460150301, 7.002366574508, -0.390318898363, -0.642631203146, -0.005701671024, 0.003522251111, 0.173867535377, 0.147911422248, 0.056092715216, -6.641979472328, 0.039602243105, 0.026181724138, 0, ],
        [0, 0, 0, 0, 0, 0, 0, 0, 1.991401999957, 13.760045912368, 2.53041689113, 0.082528789604, 0.728264862053, 0.023902766734, -0.022896554363, 0.015327568208, 0.370476566397, -0.412566245022, -6.70094564846, -1.327038338854, -0.227019235965, -0.267482033427, -0.008650986307, -0.003394359441, 0.098792645471, 0.197714179668, -6.369398456151, -0.011976840769, 0, ],
        [0, 0, 0, 0, 0, 0, 0, 0, 1.965859332057, -3.743127938662, -1.962645156793, 0.018929412474, 11.145046656101, -0.03600197464, -0.001222148117, 0.602488409354, 11.639787952728, -0.407672972316, 1.507740702165, -12.799953897143, 0.005393102236, -0.014208764492, -0.000915158115, -0.000640326416, -0.03653528842, 0.012458973237, -0.083125038259, -5.472831842357, 0, ],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        ])
    ,
        npmatrix([1.0 if d == 28 else 0.0 for d in xrange(29)])
    )

if __name__ == "__main__":
    main()

Example Output
Here's an example of the output that demonstrates the problem (each run is slightly different). Notice the large variability in execution times (over two orders of magnitude!). Again, this all goes away if I either use a pool of size 1 (or run the code without a pool), or if I don't use an explicit jacobian in the call to integrate.

*

*times: 5847ms, 5760ms

*times: 4177ms, 3991ms

*times: 229ms, 36ms

*times: 1317ms, 1544ms

*times: 87ms, 100ms

*times: 113ms, 102ms

*times: 4747ms, 5077ms

*times: 597ms, 48ms

*times: 9ms, 49ms

*times: 135ms, 109ms

A: Based on the variability of the execution times you posted for the machine showing the problem, I wonder what else that computer is doing at the time you are running your test.  Here are times I saw when I ran your code on an AWS r3.large server (2 cores, 15 GB of RAM) that normally runs interactive R sessions but is currently mostly idle:

*

*times: 11ms, 11ms

*times: 9ms, 9ms

*times: 9ms, 9ms

*times: 9ms, 9ms

*times: 10ms, 10ms

*times: 10ms, 10ms

*times: 10ms, 10ms

*times: 11ms, 10ms

*times: 11ms, 10ms

*times: 9ms, 9ms

Is it possible your machine is swapping and you do not know it?  vmstat 5 will give you a lot of information about swap in and outs, but not about cache evictions.
Intel makes some very nice tools for monitoring--two at a time--thousands of different types of operations and errors going on in a processor--including L2 cache evictions--but they are a bit of a firehose: there is information generated every microsecond--or more frequently--and you have to decide what you are going to monitor and how often you want an interrupt to deliver the numbers into your software.  Likely it will take many runs just to narrow down the stats you want to track and you still have to filter out the noise generated by the operating system and everything else running at the time.  It is a time consuming process, but if you follow it to the end and run many different tests you will come to understand what is going on.
But is this--shared cache resources in a processor--really your question?  It seems more like you just want to figure out why you have variable run times on one machine and, second, why multi-threaded is slower on both machines than single threaded.  Do I have it right?  If not I will edit my answer and we can talk about processor cache, cache snooping and cache coherency.
So, as to the variability on the i7-2670QM CPU machine, I would start with htop, vmstat 5 and iostat 5 to see if the machine is doing something you didn't realize.  That much variability says the executable is getting stalled because the processor is busy doing something else: going off to the network and not finding a share it expects, unable to connect to a DNS server, getting kerbios failures: it could be a lot of things including hardware failures from a hard disk that is being continually reset.  Oh, and move your program to /dev/shm and cd there before you start it.  That won't help you if there are Python libraries in a bad place on a disk, but at least you won't have issues with your local directory.  Report back what you find and we can make further suggestions.
Your second question as I see it, which is perhaps where you started, is why is your program slower when run multi-threaded than single-threaded.  This is a big subject that will come a lot more in focus if we can see how you multi-threaded it.  But even before we do you have to realize that there are several things that can cause a multi-threaded program to run slower than a single-threaded program, and it can have as much to do with the support infrastructure around your program--libraries and operating system calls you make--as your program.  Just because you do not need mutexes does not mean the libraries and operating system do not need them when they are being called from a multi-threaded application.  Locking a mutex is an expensive operation, especially as different threads are rotated between different cores.
On top of that, since the vode is not re-entrant, if you called it from multiple threads it is possible that it is having trouble finding convergence and having to recalculate the same values many times before it "gets lucky" and has enough processor time to complete an iteration before it is swapped out and intermediate results are overwritten.  Give us the code you are using for your multi-threaded runs and I will add to this answer.

A: This is intended as a formatted comment regarding the mathematical background raised in a comment by @Dietrich. As it doesn't address the programming question, I intend to delete this answer in a little while until the bounty blows over.
As @Dietrich noted, you can solve your ODE exactly, since if
x' = A*x,

then the exact solution is
x(t) = exp(A*t)*x0

Already I'd say that an exact solution is always superior than a numerical approximation, but this can indeed be faster than a numerical integration. As you noted in a comment, you're worried about efficiency. So don't compute the matrix exponential for each t: compute the eigensystem of A only once:
A*v_i = L_i*v_i

then
x(t) = sum_i c_i*v_i*exp(L_i*t),

and the coefficients c_i can be determined from the linear equations
x0 = sum_i c_i*v_i.

Now, having an inhomogeneous term doesn't change much, as long as your matrix is not singular:
x' = A*x + b
(x - A^(-1)*b)' = A*(x - A^(-1)*b)

so we can solve the homogeneous equation for y = x - A^(-1)*b and in a final step recover x = y + A^(-1)*b.
This all works nicely while the matrix is regular, but in your specific case it's singular. But it turns out that this is due to your final dimension:
>>> np.linalg.det(A)
0.0
>>> np.linalg.det(A[:-1,:-1])
1920987.0461154305

And also note that the final row of A is all zeros (this is the reason for the singularity of A). So the last dimension of x is constant (or changes linearly due to b).
I suggest eliminating this variable, rewriting your equation for the rest of the variables, and solving the non-singular inhomogeneous linear system of ODEs using the above procedure, exactly. It should be faster and precise.

The following will be a bit speculative, see also the caveat at the end.
In case of user-input A and b, things might get trickier. Finding a zero row/column in your matrix would be easy, but A can be singular even though none of its rows/columns are fully zero. I'm not an expert in the subject, but I think your best bet is using something akin to principal component analysis: transforming your system of equations according to the eigensystem of A. My following thoughts will still assume that A is diagonalizable, but mostly because I'm unfamiliar with singular value decomposition. In realistic cases I'd expect your matrices to be diagonalizable, even if singular.
So I'll assume that the matrix A can be decomposed as
A = V * D * V^(-1),

where D is a diagonal matrix containing the eigenvalues of A, and columns of V are the eigenvectors of A corresponding to each respective eigenvalue. The very same decomposition can be obtained in numpy using
DD,V = np.linalg.eig(A)
D = np.asmatrix(np.diag(DD))

I usually prefer using ndarrays instead of matrices, but this way V*D*np.linalg.inv(V) would really correspond to the matrix product of the three matrices, rather than calling np.dot twice.
Now, rewrite your equation again:
x' = A*x + b
x' = V*D*V^(-1)*x + b
V^(-1)*x' = D*V^(-1)*x + V^(-1)*b

By defining the auxiliary variables
X = V^(-1)*x
B = V^(-1)*b

we obtain
X' = D*X + B

i.e. the usual inhomogeneous form, but now D is a diagonal matrix containing the eigenvalues of A in the diagonal.
Since A is singular, some of the eigenvalues are zero. Look for zero elements in D (well, you can do that already with DD from eig()), and you'll know that they behave trivially during time-evolution. The remaining variables behave well, although at this point we see that the equations for X are decoupled due to D being diagonal, so you could integrate each independently and analytically. For this you need to first go from your initial condition x0 to X0 = np.linalg.inv(V)*x0, then after solving the equations, back to x = V*X.
Caveat: as I said, I'm not an expert in this subject. I can easily imagine that the inversions involved in the diagonalization can be a numerical issue in practical applications. So I'd first test if the matrix is singular, and only carry on with this procedure if it is (or nearly is). It's possible that the above carries a lot of error, in which case numerical integration might be better (I really can't tell).

A: on my compiled linux kernel :

*

*times: 8ms, 7ms

*times: 5ms, 4ms

*times: 4ms, 4ms

*times: 8ms, 8ms

*times: 4ms, 4ms

*times: 5ms, 4ms

*times: 4ms, 8ms

*times: 8ms, 8ms

*times: 8ms, 8ms

*times: 4ms, 5ms

Intel(R) Core(TM) i5-4300U CPU @ 1.90GHz
be sure your processor runs at fixed speed, noswap.
/tmp is mounted in RAM.


text:
Q: Java Verifying in Separate Classes Sorry for bad title, but I don't know how to phrase simple problem.
I have inside a class, a static function that returns an array of that class.
E.g
//returns CustomStack[]
CustomStack.createCustomStacks({{1,2},{3,4}})

Then I have a separate class that wants to use this static function for some other purpose.  The problem I'm having is deciding how I should handle errors and exceptions.
So given this function in another separate class:
public boolean StackConfirmer (CustomStack[] myCustomStacks) {
    ....
}

How do I change this function/the output of the CustomStack.createCustomStacks so that I can also handle errors?  I can clarify/edit as needed if I'm still unclear.  Apologies English is not my first language.  Like do I use null?  Do I use -1?
EDIT:  Here's a bit more elaborated code:
public class CustomStack {
    ...constructors and other irrelevant functions...

    public static CustomStack[] createCustomStacks (some_input) {
        if some_input is valid -> return CustomStack[] with Stacks inside
        if some_input isn't valid -> I'm not sure what to do.  Raise exception?
    }
}

public class ProgramThatUsesCustomStacks {
    ...
    private boolean StackConfirmer (CustomStack[] myCustomStacks) {
        // How should I be checking if there was a valid input in the other class?
        ....
}

A: I would suggest using -1 as your first element in the array (assuming it would never have -1 without an error). This will be your flag that an error occurred, then you can pad the array to a particular length to communicate the nature of the error. i.e an array consisting of {-1, 0} if you got bad data, {-1, 0, 0} if you got too much, etc.

A: You can try creating your own Exception class and then throw it in your static method, for example:
"CustomStackException extends Exception" and then handle the specific potential issues inside of that. Just a suggestion, it would be clean.

A: From your description I imagine you have a code like this
class SeparateClass{
    public boolean StackConfirmer (CustomStack[] myCustomStacks) {
        int[][]x={{1,2},{3,4}};
        CustomStack.createCustomStacks(x);
        return true;
    }
}

class CustomStack{
    static CustomStack[] createCustomStacks(int[][]x){
        return null;
    }
}

Say that in your createCustomStacks method you want to make sure that no null value is passed as function input. You can throw an exception to be handled by the caller SeparateClass.StackConfimer().
To give you an idea, this is how you should update your code
class SeparateClass{
    public boolean StackConfirmer (CustomStack[] myCustomStacks) {
        int[][]x={{1,2},{3,4}};
        try {
            CustomStack.createCustomStacks(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}

class CustomStack{
    static CustomStack[] createCustomStacks(int[][]x) throws Exception{
        if(x==null)throw new Exception();
        return null;
    }
}

Note that I decided to throw a generic Exception object just because that's a sample code to give you a first idea. There are a lot of more specific exceptions you can use, or you can define your owns by extending Exception class


text:
Q: How to Post image or Text in Tumblr Android     I am Working on Tumblr integration in Android but not able to login

Downloded the SDK from following Url:-
http://www.tumblr.com/tagged/android-sdk

now i need to login and post image or text in Tumblr.

A: Download Tumblr Example
Set CONSUMER_KEY and CONSUMER_SECRET and Get Started!
About posting text and photos see Tumblr API #Posting

Text Post

API Url : http://api.tumblr.com/v2/blog/blogname.tumblr.com/post
Replace blogname with your BlogName.
Params : 1) type = "text" 2) title = "MyTitle" 3) body = "My Message"

Photo Post with text

API Url : http://api.tumblr.com/v2/blog/blogname.tumblr.com/post
Params : 1) type = "photo" 2) caption = "Text with Image"
3) source = "http://www.gstatic.com/webp/gallery/1.jpg"
If any doubt's, feel free to ask.
Hope this will help you out.


text:
Q: Continuity of outer product Given $u, v\in \mathbb R^d$, I am trying to figure out the factor $M(u,v)$ in the bound
$$\|u\otimes u - v\otimes v\| \leq M(u,v) \cdot \| u - v\|_2,$$
if that's possible. The first norm is the standard operator norm. I think it must be something like $M(u,v) = \|u\| + \|v\|$ but I'm having trouble not getting bogged down in the battle with the indices. I suppose that this is a fairly standard result but I couldn't find it so far.
I'm also interested in the generalization the Hilbert space case with
$(u \otimes v)(w) := u \cdot \langle v, w\rangle.$

A: The way I see it $$\|u\otimes u - v\otimes v\|=\sup_{||x||=1}\|\langle x,u\rangle u-\langle x,v \rangle v \|=\sup_{||x||=1}\|\langle x,u\rangle u-\langle x,u\rangle v+\langle x,u\rangle v-\langle x,v \rangle v \| \le \sup_{||x||=1}\|\langle x,u\rangle u-\langle x,u\rangle v\|+\sup_{||x||=1}\|\langle x,u\rangle v-\langle x,v \rangle v \| \le \|u-v\|\|u\|+\|u-v\|\|v\|$$
$$=(\|u\|+\|v\|)\|u-v\|$$


text:
Q: Itertools groupby to group list using another list In pandas you can use an equivalent in length Series to GroupBy another one, for example:
s = pd.Series([1,1,1,-2,-4,-3,1,2])
g = np.sign(s).diff().fillna(0).abs().cumsum()
s.groupby(g).count()

0.0    3
2.0    3
4.0    2
dtype: int64

Is it possible to do the same using itertools.groupby? Thus using another list to create groups from the current one? Or perhaps using some key? As long as it gives me an idea of how to solve this case [1,1,1,-2,-4,-3,1,2] to create groups according to the sings would be great.
Expected output:
[3,3,2]

A: You could do the following:
from itertools import groupby

data =  [1,1,1,-2,-4,-3,1,2]

result = [sum(1 for _ in group) for _, group in groupby(data, lambda x: x<= 0)]
print(result)

Output
[3, 3, 2]

The statement: sum(1 for _ in group) counts the number of elements in the group. The key lambda x: x<= 0 is the sign function.

A: For the general case of grouping one iterable based on the matching value in another iterable, you can just make a cheaty key function that iterates the other iterable, e.g. using your original s and g:
>>> from itertools import groupby
>>> print([(k, len(list(grp))) for k, grp in groupby(s, key=lambda _, ig=iter(g): next(ig))])
[(0.0, 3), (2.0, 3), (4.0, 2)]

The key function accepts the value from s and ignores it, instead returning the matching value from iterating g manually (the defaulted second argument caches an iterator created from g, then next is used to manually advance it each time; pass a second argument to next to silently ignore mismatched lengths and simply substitute in a default value).
Obviously, for this specific case there are better approaches, but I'm answering the general question asked, not the specific example.


text:
Q: ampy no longer connecting I had ampy working for a while. It was intermittent after that, and now it doesn't work most of the time. I'm able to run esptool.py --port COM3 flash_id and esptool.py --port COM3 chip_id, but when I try to run ampy --port COM3 ls or ampy --port COM3 run test.py it just hangs.
I've tried:

*

*Restarting computer

*Shutting down computer

*Different USB ports

*Different ESP32s and ESP8266s

Any ideas?

A: I learned that different devices in the same family need to be flashed differently. I was flashing MicroPython with ESP-Now on a Wemos D1 Mini using:
esptool.py --chip esp8266 --port COM11 write_flash -z 0x1000 C:\Users\Main\Downloads\firmware-esp8266-GENERIC.bin

and it should have been:
esptool.py --port COM11 --baud 1000000 write_flash --flash_size=4MB -fm dio 0 C:\Users\Main\Downloads\firmware-esp8266-GENERIC.bin


text:
Q: How to end android Subscription when a certain condition is met? I have a dictionary android app where a user purchases a subscription after the user queries a certain number of words suppose say 1000, I want the subscription to end, do I need a server to verify this? google play console does not seem to have this option.

A: A subscription is for a certain period of time, and you cannot cancel it early.  Even if the user cancels the subscription, that only cancels the auto renew, and the subscription actually remains active until it expires.  If you want the user to buy a certain number of searches, then use a consumable product.  After purchase, record the purchase server-side and consume the product.  Then deduct as appropriate when the user takes actions.


text:
Q: How to disable textbox focusing C# i have a application where
Scenario :
when i click on that textbox the cursor should not point the textbox it should be disabled
how do i achieve this disabling the textbox
textbox1.focus()=false;
textbox1.focused()=false;

A: You can set this.ActiveControl = null; with this is your Form
This code no control is active and your textbox lost focus too.
private void YourForm_Load(object sender, EventArgs e)
{
    this.ActiveControl = null;
}

A: To disable a textbox:
textBox.IsEnabled = false;

To not focus the textBox just focus on an other element.
For example on a Forms class:
this.Focus();


text:
Q: Java replacing an Icon Image after X time passes IN SHORT: I want to execute a new command 3 sec after the former command had been issued.
THE STORY:
I have an action button that once pressed sets (replaces) an Icon Image (an animaition) on one of the Jlabels.
JLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iamg/slash.gif")));

All I want is to replace the Icon back to the former one after X time passes. In other words I want the new animaition to finish (which is about 4 sec long) and after those 4 sec pass I could set a new Icon.
I realize this can be done with threads unforutly I have no idea how, since all I know is stopping the whole program using something like this:
try
{
    Thread.sleep(3000);
}
catch (InterruptedException ex)
{

}

Which is stopping the animation it self as well, instead of waiting till 3 sec pass before executing the new command.. Help please?

A: You should use a Timer. See this tutorial for how to use them. Basically you need to add an action listener to the timer, so that when it fires you can replace the icon.


text:
Q: Proof of the Greatest Denominator Can someone help me prove this. It is a proof of the sum and difference of the greatest common denominator.
Given: x and y are integers with a GCD of 1.
Prove: that the GCD of x + y and x − y is either 1 or 2.

A: $\gcd(a+b,a-b)=\gcd(a+b, a+b+a-b)=\gcd(a+b,2a)$ which divides $2a$, but any divisor of $a$ does not divide $b$, so it divides $2$, so it is equal (modulo multiplication by $\pm 1$) to $1$ or $2$.

A: Since $\mathbf{GCD}(x,y)=1$ these two $\Bbb Z$ are coprime.
$$\gcd(x+y,x-y)=\gcd(x+y, x+y+x-y)=\gcd(x+y,2x)$$
This divides $2x$, and since any divisor of $x$ does not divide $y$, it must be that it divides $2\implies$ it is either $1$ or $2$


text:
Q: Maximum principle of eigenvalue-like problem for harmonic equation I am trying to identify for which $\lambda$ so that I can obtain the Maximum principle, that is, $$\sup_{\overline{\Omega}}u\leq \sup_{\partial \Omega}u$$ for equation $-\triangle u = \lambda u$, where the domain $\Omega$ is open bounded.
I tried to mimic the prove in Evans book. Indeed, by assuming that $\lambda\leq 0$, I have
$$-\triangle u \leq 0$$
in the set $V:=\{x,\,\,u(x)>0\}$. Then I can apply the Maximum principle for $u$ in $V$ and obtain that
$$\sup_{\overline{V}}u = \sup_{\partial V}u =  \sup_{\partial \Omega}u^+\Rightarrow \sup_{\overline{\Omega}}u \leq \sup_{\partial \Omega}u^+$$
However, I can not replace $u^+$ by $u$ above. Any hints will be really welcome!

A: The obstacle that you encountered is real. Consider one-dimensional situation: for every $\lambda<0$, the function $u(x) = - \cosh (\sqrt{-\lambda} x)$ satisfies $-u''=\lambda u$ and
$$\sup_{[-1,1]} u = -1 > -\cosh (\sqrt{-\lambda}) = \max(u(1),u(-1))$$
For eigenfunctions with $\lambda<0$ we have maximum principle for $u^+$, $u^-$, and consequently for $|u|$; but not for $u$ itself.
For eigenfunctions with $\lambda>0$ there is no maximum principle at all.


text:
Q: header not redirecting This file is supposed to redirect to the URl specified in the header but displays blank page.
It displays expected values if you un-comment some of the results.
<?php
sendReceiveOrder($Amnt);

    function sendReceiveOrder($Amnt) {
        //$ch = curl_init ();

        $description = $_POST['gtpay_tranx_memo'];

        $receivedXML = "";
        $receivedXML .= "<?xml version='1.0' encoding='UTF-8'?>";
        $receivedXML .= "<TKKPG>";
        $receivedXML .= "<Request>";
        $receivedXML .= "</Request>";
        $receivedXML .= "</TKKPG>";

        // Define POST URL and also payload
        //
        define ( 'XML_POST_URL', 'http://127.0.0.1:5555/Exec' );

        // Initialize handle and set options

        $ch = curl_init ();
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch,CURLOPT_MAXREDIRS,50);
        if(substr($url,0,8)=='https://'){
        // The following ensures SSL always works. A little detail:
        // SSL does two things at once:
        //  1. it encrypts communication
        //  2. it ensures the target party is who it claims to be.
        // In short, if the following code is allowed, CURL won't check if the
        // certificate is known and valid, however, it still encrypts communication.
        curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);

    }
        curl_setopt ( $ch, CURLOPT_URL, XML_POST_URL );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 500 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $receivedXML );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, array ('Connection: close' ) );

        //---Additional stuff

    curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/tdpayment/cert/ETECHNOL.pem");

    //----------

        /**
         * Execute the request and also time the transaction
         */
        $start = array_sum ( explode ( ' ', microtime () ) );
        $result = curl_exec ( $ch );
        $stop = array_sum ( explode ( ' ', microtime () ) );
        $totalTime = $stop - $start;

        /**
         * Check for errors
         */
        if (curl_errno ( $ch )) {
            $result = 'cURL ERROR -> ' . curl_errno ( $ch ) . ': ' . curl_error ( $ch );
        } else {
            $returnCode = ( int ) curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
            switch ($returnCode) {
                case 200 :
                    break;
                default :
                    $result = 'HTTP ERROR -> ' . $returnCode;
                    break;
            }

        }

        /**
         * Close the handle
         */
        curl_close ( $ch );

        /**
         * Output the results and time
         */

        //echo 'Total time for request: ' . $totalTime . "\n";
        //echo $_SESSION ['Amt'];
        //echo $result ;

        //echo "<br>";

    $_SESSION['store_result'] = $result;

        //echo $Amnt;
        //echo $description;
        //return $result;

        /**
         * Exit the script
         */
         $result2 = <<<XML
    <?xml version='1.0' standalone='yes'?>
    $result
    XML;

    $TKKPG = new SimpleXMLElement($result2);
    $orderid =  $TKKPG->Response->{'Order'}->OrderID;
    $sessionid =  $TKKPG->Response->{'Order'}->SessionID;
    $url = $TKKPG->Response->{'Order'}->URL;

    $_SESSION['ordersessionid'] = $orderid.$sessionid;

    $header = $url."?sessionid=".$sessionid."&orderid=".$orderid;

    header ("Location: ".$header);

        exit ( 0 );
    }
    ?>


text:
Q: Sort files in Terminal like finder Is it possible in the command line to have the same sort order for files/folders as Finder. If I run find . -type d, I get as output:
./Folder 1
./Folder 10
./Folder 11
./Folder 2
./Folder 3
...

I tried find -s . -type d, and also added some sort options. No luck.
What I want is this:
./Folder 1
./Folder 2
./Folder 3
...
./Folder 10
./Folder 11

A: If you look at what find says about sorting:
 -s   Cause find to traverse the file hierarchies in
lexicographical order, i.e., alphabetical order within each directory.
Note: `find -s` and `find | sort` may give different results.
This means we need to pipe it to sort so that we can manipulate it a bit more.
As you have already seen, a simple alphanumeric sort won't work because it's comparing everything as an ANSI character not as numbers.  What we need to do is just compare the numbers.  We can do this with the -k option of sort
find . -type d | sort -k2.3
What the sort -k2.3 command is doing is sorting on the second field (delimited by the space) ending at the 3rd position.  This is the result using your folder naming convention1:
.
./Folder 1
./Folder 2
./Folder 3
./Folder 4
./Folder 5
./Folder 6
./Folder 7
./Folder 8
./Folder 9
./Folder 10
./Folder 11
./Folder 12
./Folder 13
./Folder 14
./Folder 15

1 To create this folder structure, I used the command in my home folder:
mkdir test; cd test; for n in {1..15}; do mkdir "Folder $n"; done

A: Can also do
ls -v

which sorts files by version numbers in names by natural order.
From man ls
-v     natural sort of (version) numbers within text


text:
Q: Authenticating with WCF I have a WCF application which I'd like to expose to some people, but for them to use the service I'd like to authenticate them somehow, is it possible to create my own membership provider which would check if the user is validated by calling the ValidateUser method? Also how would I then tell my bindings/behaviours to use this Membership Provider?
Edit
I have some queries about this too. For example: If I call a method on my webservice called QueryStock from my client. Does it first validate the user using my membership provider BEFORE firing the method or do I have to put pass the username and password as parameters and then do Membership.ValidateUser(username, password) before executing the code in my method?

A: Yes it is possible. Take a look at this article, it shows a sample using a custom provider.

A: This is all possible to do with WCF, I'm using it now for a WCF service we have.
You can create your own membership provider (just as you woud for an asp.net application), and then plumb that into WCF too. There's tonnes of information on this if you google for "WCF Membership provider". This post may help you too: WCF Authentication using SQL Membership Provider

A: You need to define a behaviour in teh config, for example:
<behaviors>
  <serviceBehaviors>
    <behavior name="Framework.Services.FrameworkBehaviour">
      ...
      <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="CustomProvider" />
      <serviceCredentials>
        <serviceCertificate ... />
        <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="...." />
      </serviceCredentials>
    </behavior>

This is the binding snippet:
   <binding name="userNamePassOverSsl" ...>
      <security mode="TransportWithMessageCredential">
        <transport  />
        <message clientCredentialType="UserName" />
      </security>
    </binding>

A: I had this question too:
Authentication in WCF for every call
As you can see, you may use ASP.NET authentication.
If you have your own method to validate users, I'd try to use a kind of façade to call every service method with user + token and keep a kind of "async session".
So you can create a new token the first time the users login and then in each call and then use it in the next call. Use just a table with user + token to secure all your calls.


text:
Q: Get path as shown to user (as opposed to path used by C#) When connecting an Android device to a PC, the path to a file is not the path we use in Xamarin.
For example, the path we use is /storage/emulated/0/somePath, but the path shown to a user is something like phone/card/somePath.
How do we get the path that the user sees? Even if we don't know the drive letter, that's fine.


text:
Q: A non-null string must be provided to a text widget. 'package:flutter/src/widgets/text.dart': Failed assertion: line 378 pos 10: 'data != null'
A non-null string must be provided to a text widget.
'package:flutter/src/widgets/text.dart': Failed assertion: line 378
pos 10: 'data != null'

I'm getting errors while streaming data from firestore.
child: StreamBuilder<QuerySnapshot>(
                  stream:
                      FirebaseFirestore.instance.collection('user').snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) return CircularProgressIndicator();

                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Text("Loading");
                }

                return ListView.builder(
                    //scrollDirection: Axis.horizontal,
                    itemCount: snapshot.data!.docs.length,
                    itemBuilder: (context, index) {
                      DocumentSnapshot currentdoc =
                          snapshot.data!.docs[index];
                      return Container(
                        height: 300,
                        width: MediaQuery.of(context).size.width,
                        color: Colors.black,
                        child: Column(
                          children: [
                            Text(
                              currentdoc.data()['description'],
                              style: TextStyle(color: Colors.white),
                            ),
                            Text(
                              currentdoc.data()['name'],
                              style: TextStyle(color: Colors.white),
                            ),
                            Image(
                              height: 180,
                              width: 180,
                              image: NetworkImage(currentdoc.data()['url']),
                              fit: BoxFit.cover,
                            ),
                          ],
                        ),
                      );
                    });
              },

A: it seems that the provided varibale for TextView has null value. use this code instead:
Text(
                              currentdoc.data()['description']??"",
                              style: TextStyle(color: Colors.white),
                            ),
                            Text(
                              currentdoc.data()['name']??"",
                              style: TextStyle(color: Colors.white),
                            ),

also, I suggest to use null safety for your currentdoc as follows:
currentdoc?.data()...

A: It is not possible to provide a null value to a Text widget, so you need to make sure it is not null.
You can chose to either omit the widget if the value is null, or provide a default value. To omit the widget if the value is null:
Column(
  children: [
    if (currentdoc.data()['description'] != null)
      Text(
        currentdoc.data()['description'],
        style: TextStyle(color: Colors.white),
      ),
    if(currentdoc.data()['name'] != null)
      Text(
        currentdoc.data()['name'],
        style: TextStyle(color: Colors.white),
      ),
    Image(
      height: 180,
      width: 180,
      image: NetworkImage(currentdoc.data()['url']),
      fit: BoxFit.cover,
    ),
  ],
),

To provide a default value:
Column(
  children: [
    Text(
      currentdoc.data()['description'] ?? "default description",
      style: TextStyle(color: Colors.white),
    ),
    Text(
      currentdoc.data()['name'] ?? "default name",
      style: TextStyle(color: Colors.white),
    ),
    Image(
      height: 180,
      width: 180,
      image: NetworkImage(currentdoc.data()['url']),
      fit: BoxFit.cover,
    ),
  ],
),

Here you can of course change "default description" and "default name" to any default value of your choice.


text:
Q: What is the extra cost of overloading placement new operator? We want to overload placement new operator just to verify that used memory size is enough for the given class. We know this size. The construction is more or less in this way:
template <size_t MAXSIZE>
class PlacementNewTest {
public:
  void* operator new (size_t size, void* where)
  {
     if (size > MAXSIZE) {
        throw bad_alloc();
     }
     return where;
  }
};

Let say used in such simplified context:
char buffer[200];

class A : public PlacementNewTest<sizeof buffer> {
public:
   char a[100];
};

class B : public A {
public:
   char b[200];
};

int main() {
   A* a = new (buffer) A; // OK
   a->~A();
   B* b = new (buffer) B; // throwed bad_alloc
   b->~B();
}

During testing phase I have this PlacementNewTest<> class used, but in the release code I consider to remove it. Do you think, basing on your experience, how much this will cost our performance, not to remove this extra test class? Is this only cost of this verification if (size > MAXSIZE)?
In other words, what is performance penalty for such redefinition:
class PlacementNewNOP {
public:
  void* operator new (size_t size, void* where)
  {
     return where;
  }
};

Maybe it is not important in this question - but:
This is, and must be, C++03. We cannot upgrade to C++11. And boost is not an option too, just C++03.

A: There shouldn't be any overhead apart from the comparison, unless you are using virtual methods, the binding is static.
Of course there is the exception overhead, but since that is something that shouldn't happen, you should be safe to ignore it.