text:
Q: Add string after a certain string in the same line in a text file I have been trying to add a string in the same line in a text file. I have used following method.
sed -i "s/\bmembers\b/& \t$host,/" printer.cfg

It will add a string after members string and also it will add tab in order to make it proper.
I will get result like this,
define hostgroup{
hostgroup_name  HOSTGROUP ONE
alias       Host Group 1 Printers
members     foo0, foo1, bar2, foo2, bar3
}

Where foo0 is my added string using above sed.
But the problem is there is one text file, that contains many "members" string.
e.g.
define hostgroup{
hostgroup_name  HOSTGROUP ONE
alias       Host Group 1 Printers
members     foo1, bar2, foo2, bar3
}

define hostgroup{
hostgroup_name  HOSTGROUP TWO
alias       2nd Host Group
members     example1, example3, example2
}

In this above example, I want to add string ONLY in first para (hostgroup_name HOSTGROUP ONE). In this case, How can I refer hostgroup_name and add text after "members" string with one tab?

A: Two approaches:
sed approach:
sed "0,/members/{s/\bmembers */&$host, /}" printer.cfg

*

*0,/members/ - address range occupying a range of lines starting from the 1st line till the first occurrence of members pattern

awk approach:
awk -v h=$host '!f && /members /{ $2=sprintf("%8s, %s",h,$2); f=1 }1' printer.cfg

The output (for both approaches):
define hostgroup{
hostgroup_name  HOSTGROUP ONE
alias       Host Group 1 Printers
members     foo0, foo1, bar2, foo2, bar3
}

define hostgroup{
hostgroup_name  HOSTGROUP TWO
alias       2nd Host Group
members     example1, example3, example2
}

A: Follow the 3-step process of selecting, storing, and shaping the range of interest data. The final task of printing to stdout is an autotask of sed.
host='Foo_0';
sed -Ee '

   # Step-1: SELECT RANGE
   /^define hostgroup[{]/,/^[}]/!b

   # Step-2: SAVE RANGE DATA
   H; /^define hostgroup[{]/h; /^[}]/!d

   # Step-3: SHAPE RANGE DATA
   g;/\nhostgroup_name\s+HOSTGROUP ONE/s/\nmembers\s+/&'"${host}"', /

' printer.cfg


text:
Q: How to make lines symmetrical in PIL? I have been working on these lines, and I want to create it like in picture, but I got complicated. How do I get line symmetrical like in picture below?
This is what I tried so far, not much :/
from PIL import Image, ImageDraw

img = Image.new('RGB', (1000, 1000), (255, 255, 255))
draw = ImageDraw.Draw(img)

for y in range (-4000, 2000, 200):
    draw.line(((y, img.size[0]+img.size[0]),
               (img.size[1]+img.size[1]+img.size[1], y)), (0, 0, 0), 20)

for x in range (-2000, 1000, 100):
    draw.line(((x,-x),(x+img.size[0], -x+img.size[1]+img.size[1])), (0, 0, 0), 20)

I want to create lines like this...

A: I think you created too complicated calculations and this made problem
Symmetrical lines should have similar calculations but with different sign.
Both should have y from 0 to height
from PIL import Image, ImageDraw

img = Image.new('RGB', (1000, 1000), (255, 255, 255))
draw = ImageDraw.Draw(img)

w = img.size[0]
h = img.size[1]

offset = 400
step = 100

for x in range(-offset, w+offset, step):
    draw.line(((x, 0), (x+offset, h)), (0, 0, 0), 20)
    draw.line(((x, 0), (x-offset, h)), (0, 0, 0), 20)

img.show()

Gives

And for offset = image_width (offset = 1000) it gives rectangles

EDIT:
Version which use move_x, move_y to move lines.
Because after moving lines it shows end of lines so I use line_width to start and end line outside window.
from PIL import Image, ImageDraw

img = Image.new('RGB', (1000, 1000), (0, 200, 0))
draw = ImageDraw.Draw(img)

w = img.size[0]
h = img.size[1]

line_width = 10 #

move_x = 10
move_y = 50

offset = w # 400
step = 200

for x in range(-offset, w+offset, step):
    x1 = x  + move_x - move_y - line_width
    x2 = x1 + offset          + line_width*2

    x3 = x  + move_x + move_y + line_width
    x4 = x3 - offset          - line_width*2

    draw.line(((x1, 0-line_width), (x2, h+line_width)), (0, 0, 0), line_width)
    draw.line(((x3, 0-line_width), (x4, h+line_width)), (0, 0, 0), line_width)

img.show()
img.save('output.png')

redpajama_set_name: RedPajamaStackExchange


text:
Q: FirebaseUI iOS remove cancel button I'm new in iOS development. I wanna build authorization with Firebase. I'm using FirebaseUI-iOS. I wanna hide Cancel button from the initial screen. Do you have any ideas how to do it?
I create Firebase authViewController programmatically:
import UIKit
import Firebase
import FirebaseAuthUI
import FirebaseGoogleAuthUI

class AuthViewController: UIViewController {

fileprivate var _authHandle: FIRAuthStateDidChangeListenerHandle!
var user: FIRUser?

override func viewDidLoad() {
    super.viewDidLoad()
    configureAuth()
}

func configureAuth() {
    let provider: [FUIAuthProvider] = [FUIGoogleAuth()]
    FUIAuth.defaultAuthUI()?.providers = provider
    FUIAuth.defaultAuthUI()?.isSignInWithEmailHidden = true

    // listen for changes in the authorization state
    _authHandle = FIRAuth.auth()?.addStateDidChangeListener { (auth: FIRAuth, user: FIRUser?) in
        // check if there is a current user
        if let activeUser = user {
            // check if the current app user is the current FIRUser
            if self.user != activeUser {
                self.user = activeUser
                let name = user!.email!.components(separatedBy: "@")[0]
                print(name)
            }
        } else {
            // user must sign in
            self.loginSession()
        }
    }
}

func loginSession() {
    let authViewController = FUIAuth.defaultAuthUI()!.authViewController()
    present(authViewController, animated: true, completion: nil)
}

deinit {
    FIRAuth.auth()?.removeStateDidChangeListener(_authHandle)
}
}

A: You should set
FUIAuth.defaultAuthUI()?.shouldHideCancelButton = true

A: For that you can set the leftBarButtonItem to nil in viewDidLoad or in viewWillAppear.
self.navigationItem.leftBarButtonItem = nil

A: Extend the VC and add it in the viewWillAppear
extension FUIAuthBaseViewController{
  open override func viewWillAppear(_ animated: Bool) {
    self.navigationItem.leftBarButtonItem = nil
  }
}

A: In Objective C, simply extend the FUIAuthPickerView Controller.
In ViewDidLoad of this extended picker view, add these two lines:
self.navigationController.navigationItem.hidesBackButton = NO;
[[self navigationItem] setLeftBarButtonItem:nil];

Please note that in the file where you instantiate the Auth UI, you'll need this method:
- (FUIAuthPickerViewController *)authPickerViewControllerForAuthUI:(FUIAuth *)authUI {
return [[FUICustomAuthPickerViewController alloc] initWithAuthUI:authUI];
}


text:
Q: How do I create an Apache Ambari view using existing source code? I'm currently a developer working on a project to better visualize big data analytics in Apache Ambari views.
I read through the documentation here: https://cwiki.apache.org/confluence/display/AMBARI/Views
I have some existing source code written in HTML, CSS, and PHP and need some help in compiling the compatible jar file that is compatible with Ambari Views.
I see the source tree and understand that I need to use Maven to compile my source into the jar file utilizing the proper XML
In the documentation there are multiple examples that do not compile with Maven. I receive the error, "The goal you specified requires a project to execute but there is no POM in this directory (PRIVATE). Please verify you invoked Maven from the correct directory. -> [Help 1]"
Even if I change the view.xml to a pom.xml it still produces errors.
How can I compile it correctly and display as an Ambari View?

A: view.xml documentation: https://cwiki.apache.org/confluence/display/AMBARI/View+Definition
for compiling Maven you need a seperate pom.xml file. The main difference is that instead of <project> you might want to use <view>
Here's an example of the pom.xml file I used that compiled it correctly:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <version>1</version>
</project>

NOTE: This is not the proper way to make a POM file but it will compile and help you find the right direction
My file tree is as follows:
view-folder
|
|_docs
  |
  |-readme.txt
|
|-pom.xml
|
|_src
  |
  |_main
    |
    |_resources
      |
      |{source: included the view.xml here}

There is probably a more elegant answer, but I'm doing something related so if I find a better answer as I'm developing I'll update this.
I also suggest using jQuery or AJAX instead of PHP since some builds of Ambari might not support PHP but I think most browsers natively support javascript.


text:
Q: Using GPU with Pytorch I am confused on the usage of .to(device) in pytorch. I know that it loads the variables to the GPU. But after that, lets say we multiply two gpu tensors together, will our computer know to use the gpu to do that? Or will it cast it back to CPU and preform the computation? I guess I am just confused on when and how our computer will know to use gpu outside of us telling it to hold some variable in its memory.

A: All operations on tensors that are e.g. in the GPU memory will be performed on the GPU. Furthermore if multiple tensors are involved in some operation, all of them need to be set to the same .device.
The way this is done is that no matter what operation we do to tensors, we'll always call methods of the torch.Tensor class. So adding two tensors a + b does actually call torch.Tensor.add, so whenever some operation is executed, it is always done with the knowledge of what device is used.


text:
Q: How to remove a created li by clicking on button with JQuery? Right now, my code allows someone to create an li by submitting a movie title and its rating. A remove button also appears at the end of this li. I want this li to be removed once the remove button is clicked on. I understand how to do this with Javascript, however how do you do this with jQuery? The ways I have attempted this are:
$('li button').click( function(e) {
    e.target.closest('.li').remove();
})

$('li').on("click", "button", function() {
    $(this).remove()
})

I know there are other ways in Jquery to remove the li, but what is wrong with the above two methods? is it how I selected the items? My entire HTML and JS are below. Thanks in advance!

$('#movieForm').submit(function(event) {
    event.preventDefault();

    let movieInput = $("#movieTitle").val();
    let ratingInput = $("#rating").val();

    $('#movieList').append("
" + movieInput + " " + ratingInput + "<button>Remove</button>
");
    })

$('li button').click( function(e) {
    e.target.closest('.li').remove();
})
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Movies App!</title>
  <link rel="stylesheet"
        href="https://unpkg.com/bootstrap/dist/css/bootstrap.css">

Movies App!

<form id="movieForm">
  <input id="movieTitle" placeholder="Movie Title">
  <input id="rating" placeholder="Rating">
  <input type="submit" id="submit"></button>
</form>

A: Your use of on() is almost correct, there's just two flaws. Firstly the primary selector should be the closest parent element to the target which exists in the DOM when the page loads, in this case the ul. You also need to remove the entire li when the event happens, not the button, so use closest(). Try this:

jQuery($ => {
  $('#movieForm').submit(e => {
    e.preventDefault();
    let movieInput = $("#movieTitle").val();
    let ratingInput = $("#rating").val();
    $('#movieList').append(`<li>${movieInput} ${ratingInput}<button>Remove</button></li>`);
  })

  $('ul').on("click", "li button", e => $(e.target).closest('li').remove());
});
<link rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.css">

Movies App!

<form id="movieForm">
  <input id="movieTitle" placeholder="Movie Title">
  <input id="rating" placeholder="Rating">
  <input type="submit" id="submit" />
</form>

Note that I used arrow functions and template literals in the above example. Neither are relevant to the issue you had, they're just some syntactic sugar to make the logic more succinct.


text:
Q: Error while loading shared libraries: libreadline.so.5: I'm trying to run the command sudo pip install --upgrade virtualenv, but I keep receiving the following error:
/opt/bitnami/python/bin/.python2.7.bin: error while loading shared libraries:
libreadline.so.5: cannot open shared object file: No such file or directory

I've attempted to use the recommendation on this link [Bitnami - /opt/bitnami/python/bin/.python2.7.bin: error while loading shared libraries: libreadline.so.5](Bitnami - /opt/bitnami/python/bin/.python2.7.bin: error while loading shared libraries: libreadline.so.5 and no prevai), but it was not helpful.
Why do I receive the error?

A: I figured this out.

*

*You have to be in the root level by issueing the sudo su command.

*Now while in root level run the following command . /opt/bitnami/scripts/setenv.sh

*I'm loggin into my server using SSH, apparently I have to follow the same steps every session.

A: installing virtualenv using pip installs it in bitnami stack
hence to use virtualenv we need to execute setenv.sh shell script
this script gives powers to virtualenv but we need to run it everytime
so better to install virtualenv in root of the system using sudo apt-get
install virtualenv in root
sudo apt-get install python-virtualenv

A: So while maplesyrup's answer is good, I have found a solution that works better in practice.
Run sudo echo '. /opt/bitnami/scripts/setenv.sh' >> /opt/bitnami/.bitnamirc
This will append the script call in maplesyrup's answer, but then it will be called at every logon. The only downside is you have to enter your password immediately after logging in through ssh, but it is much better than having to manually call the script each time you login.

A: The required file is not in directory. usually this happened because the update which replaced the certain version of the file and with the newer version (e.g. libreadline.so.5 replaced by libreadline.so.8). to fix this, first you should check the library directory (/usr/lib) if a version version of the file is exist then you can create a link to that that file named with the file that is missing.
the following example is creating a link named with the missing file (libreadline.so.5) that linked to libreadline.so.8. but be CAREFULL because this might cause your terminal unable to get input if the certain libreadline.so.* is lost
cd /usr/lib
ln -sf libreadline.so.8 -T libreadline.so.5

this solution works for me.


text:
Q: Chernoff-type bound over sums of the whole sequence Let $X_1, X_2, X_3, \ldots, X_n$ be a sequence of i.i.d. Bernoulli independent random variables each being 1 with probability $p$. For each $t \geq 0$ define
$$
S_t := \sum_{i=1}^t X_i.
$$
Is my intuition correct that
$$
\Pr\left[\exists t : |S_t - pt| \geq \lambda \right] \leq e^{-\frac{C\lambda^2}{pn}}?
$$
Note that a simple application of Chernoff bound only gives
$$
\Pr\left[|S_n - pn| \geq \lambda \right] \leq e^{-\frac{C\lambda^2}{pn}}.
$$

A: Since
$$P(\exists t : |S_t - pt| \ge \lambda) \ge P(|X_1 - p| \ge \lambda) = \begin{cases}0 & \lambda > \max\{p, 1-p\} \\ p & 1-p \ge \lambda > p \\ 1-p & p > \lambda \ge 1-p\\ 1 & \lambda \le \min\{p, 1-p\}\end{cases}$$
you cannot expect your claim to hold without further assumptions (such as a restriction on $\lambda$).


text:
Q: django blog zinnia - NoReverseMatch at /blog/ My current project uses django blog zinnia and when I open /blog it gives the following error:
Reverse for 'zinnia_entry_add' with arguments '()' and keyword arguments '{}' not found.

I tried creating a separate test project and it is working without any problems. In this test project, I tried this in shell   :
reverse("admin:zinnia_entry_add") which is returning '/admin/zinnia/entry/add/'

But, when I check the same thing in my current project it's throwing above error. I have enabled admin, I am able to access /admin too. What could be the problem?

A: Along with other steps described in docs you have to extend Entry model. On this step don't forget to register your new admin class, see section Updating the admin interface.

A: Have you added url(r'^weblog/', include('zinnia.urls')), in urls.py? Documentation is here.


text:
Q: Writing to a log, inside a timer, that's inside a thread, from another thread I'm working on writing an application that scans an imageboard for images, then downloads them. Ofcourse this has to be threaded, because multiple boards could be scraped at once. I've got the basic funcionality done already, but now I'm hitting a wall.
Currently I start threads by giving an url, then press a button, this button starts a thread which points to a class.
My problem resides inside this class, as I'm using a timer there.
Currently the data gets pushed to the log at one go, but should be pushing the data as it is set.
Currently this is my function that is bound to the tick event of my timer:
    public void scanForImages(object s, ElapsedEventArgs e)
    {

        if (status != 1 && status != 4)
        {
            status = 1;
            int i = 0;
            while (status == 1)
            {
                main.updateLog(th.Name + ": Blaat\n");
                i++;
                if (i > 50)
                {
                    status = 4;
                    t.Stop();
                    main.updateThreads("Aborting: " + th.Name, th);

                    th.Abort();
                }
            }
        }
        else
        {
            t.Stop();
        }
    }

It is returning output in my textbox, but it's pushing everything at once( All the th.Name + ": Blaat\n"
updateLog:
public void updateLog(string txt)
        {
        if (InvokeRequired)
        {
            Action action = () => textBox2.AppendText(txt);
            textBox2.Invoke(action);
        }
        else
        {
            textBox2.AppendText(txt);
        }

    }

What am I doing wrong? (More code can be supplied, if neccessary)

A: you do not give the .updatelog code so we can answer correctly
so...
either you must flush the file inside that function or you must initiate a dispatcher
Dispatcher.Invoke(DispatcherPriority.Normal,
                      new Action<string>(main.updateLog),
                      th.Name + ": Blaat\n");


text:
Q: Sample Selection Model: MLE vs. Two-Step Estimation and Panel Data I am studying the relatively classical model of selection to estimate the union wage premium, with two equations of salary and one two step equation of selection
$\ln(w_{1it}) = X^{'}_{it} \beta_1  + \epsilon_{1it}$
$\ln(w_{0it}) = X^{'}_{it} \beta_0  + \epsilon_{0it}$
$union^*_{it} = \gamma X^{'}_{it} + \epsilon_{2it} $
$union_{it} = \mathbb{I}(union^*_{it}>0)$
I have two different questions:
1) When I implement it as a cross section estimate in Stata (with the heckman command), I have very different results whether I estimate it by Heckman two step method or by MLE.
Is that normal? In which case what is the theoretical reasons?
2) As noted in my equations, I have panel data.
Does the Heckman procedure still apply to it? Or does the within estimation remove endogeneity and solve it all?
I would say it still applies, but I did not find relevant literature and my courses only cover cross section data.

A: If I understand correctly, you are "tricking" the Heckman selection model to estimate a endogenous switching regression model, also known as the Roy model and Tobit Type 5. This trick is explained in Lee, Lung-Fei (1978) "Unionism and Wage Rates: A Simultaneous Equations Model with Qualitative and Limited Dependent Variables", International Economic Review, Vol. 19(2), pp. 415-433. You're interested if worker characteristics are rewarded differently in the two regimes/sectors ($\beta_0 - \beta_1 \ne 0$) and the correlation parameter $\rho$ tells you about the effect of self-selected union membership on wages in the two sectors. You do, however, may need to adjust the standard errors if the Heckman technique is to be used, or you loose consistency.
Alternatively, since you have an exclusion restriction, you can get the causal effect of union membership on wages using instrumental variables: treatreg/etregress for cross sectional data, and all kinds of panel IV methods like xtivreg.
Some observations. First, there's is a user-written Stata command called movestay designed to estimate the endogenous switching regression model with cross sectional data. It is a full information ML approach, which relies on the multivariate normality of the the error terms assumption, as does the Heckman MLE method. If this is satisfied, both will be consistent, though the movestay will be somewhat more efficient than doing it in two parts.
The Heckman Two Step limited information ML estimator relies only on univariate normality of the marginal distribution, so it is expected to be more robust since that is a lower hurdle to clear. But if you do have joint normality, the Two Step is still consistent, but no longer efficient, especially relative to movestay. However, if you only have univariate normality, then the Two Step remains consistent while the FIML approaches are not.
In short, FIML and LIML approaches will usually differ since they have different information to work with, as I show below with an example. I think this explains question (1).
Now for (2). As far as I know, there is no off-the-shelf panel version of heckman or movestay, though both allow you to cluster the standard errors on the panel id. That's not strictly correct, but may be good enough. There might also be a way to hack it using gllamm, though I have never done this myself since it appears non-trivial. Some notes on that here and Statalist threads here.
I am not really answering the second part of (2) since it is not clear to me how the fixed effects enter the model and how they are related to union membership. With panel methods I suggested above, you give up estimating different parameters in the two regimes/sectors. Depending on the details of your model, you may not even need to instrument if you can difference away the pesky effect. The details depend on your data and models.
Finally, you might consider changing your notation to add instrument(s) Z (something that alters union membership, but is not related to wages directly) and the fixed effects.
Here's some code showing the movestay and Heckman MLE equivalence, along with the problem you have in (1). I am modeling wages with endogenous participation in public/union and private sectors. My instruments are marital status and number of job holders in the household. They are likely to be not very good.
Here's the output:
. #delimit;
delimiter now ;
. use "http://www.adeptanalytics.org/download/ado/movestay/movestay_example.dta", clear;
(Sample dataset to illustrate the use of movestay procedure)

. capture ssc install movestay;

. /* Switcing Regression */
> movestay lmo_wage age age2 edu13 edu4 edu5 reg2 reg3 reg4
> , select(private =age age2 edu13 edu4 edu5 reg2 reg3 reg4 m_s1 job_hold);

Fitting initial values .....
initial:       log likelihood = -2615.3274
rescale:       log likelihood = -2615.3274
rescale eq:    log likelihood = -2504.2563
Iteration 0:   log likelihood = -2504.2563
Iteration 1:   log likelihood = -2478.8632
Iteration 2:   log likelihood = -2472.9261
Iteration 3:   log likelihood = -2471.4714
Iteration 4:   log likelihood =  -2470.979
Iteration 5:   log likelihood =   -2470.94
Iteration 6:   log likelihood = -2470.9304
Iteration 7:   log likelihood = -2470.9304

Endogenous switching regression model             Number of obs   =       2094
                                                  Wald chi2(8)    =     742.40
Log likelihood = -2470.9304                       Prob > chi2     =     0.0000

------------------------------------------------------------------------------
             |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
lmo_wage0    |
         age |  -.0370404   .0111445    -3.32   0.001    -.0588832   -.0151976
        age2 |   .0003735   .0001285     2.91   0.004     .0001216    .0006255
       edu13 |  -.5066122   .0885002    -5.72   0.000    -.6800694    -.333155
        edu4 |   -.410602   .0507909    -8.08   0.000    -.5101502   -.3110537
        edu5 |  -.2973613   .0391875    -7.59   0.000    -.3741673   -.2205552
        reg2 |  -.3780673   .0420359    -8.99   0.000    -.4604562   -.2956784
        reg3 |   .7053256   .0532104    13.26   0.000     .6010351    .8096162
        reg4 |  -.2355433   .0474621    -4.96   0.000    -.3285672   -.1425193
       _cons |   9.322335   .2377244    39.21   0.000     8.856404    9.788266
-------------+----------------------------------------------------------------
lmo_wage1    |
         age |   .0423454   .0291869     1.45   0.147      -.01486    .0995507
        age2 |  -.0005007   .0003227    -1.55   0.121    -.0011332    .0001319
       edu13 |    .343707   .2793213     1.23   0.219    -.2037528    .8911667
        edu4 |  -.1578067   .1608107    -0.98   0.326    -.4729898    .1573764
        edu5 |  -.1640915   .1300285    -1.26   0.207    -.4189427    .0907598
        reg2 |  -.2864992     .10977    -2.61   0.009    -.5016445    -.071354
        reg3 |   .7076898   .1427077     4.96   0.000     .4279879    .9873917
        reg4 |  -.1383784   .1414154    -0.98   0.328    -.4155475    .1387908
       _cons |   7.415708   .4807955    15.42   0.000     6.473366     8.35805
-------------+----------------------------------------------------------------
select       |
         age |  -.1455147   .0258919    -5.62   0.000     -.196262   -.0947674
        age2 |   .0013623   .0003045     4.47   0.000     .0007655    .0019592
       edu13 |   .0761837   .2457816     0.31   0.757    -.4055394    .5579067
        edu4 |   .0690438   .1415167     0.49   0.626    -.2083237    .3464114
        edu5 |   .2351347   .1063559     2.21   0.027      .026681    .4435883
        reg2 |  -.4401673   .0958095    -4.59   0.000    -.6279506   -.2523841
        reg3 |  -.5960666    .118727    -5.02   0.000    -.8287672   -.3633661
        reg4 |  -.6010511   .1127811    -5.33   0.000    -.8220979   -.3800043
        m_s1 |   .1569937   .0921423     1.70   0.088    -.0236019    .3375893
    job_hold |   .0551942    .036172     1.53   0.127    -.0157017      .12609
       _cons |   2.505468   .5789885     4.33   0.000     1.370672    3.640265
-------------+----------------------------------------------------------------
       /lns0 |  -.4220208   .0186565   -22.62   0.000    -.4585869   -.3854546
       /lns1 |  -.5903419    .056246   -10.50   0.000     -.700582   -.4801018
         /r0 |   1.353758   .0813975    16.63   0.000     1.194222    1.513295
         /r1 |   .1457211   .3195399     0.46   0.648    -.4805656    .7720077
-------------+----------------------------------------------------------------
      sigma0 |   .6557204   .0122335                      .6321763    .6801414
      sigma1 |   .5541378    .031168                      .4962964    .6187204
        rho0 |   .8749375   .0190865                      .8318838     .907522
        rho1 |   .1446983   .3128495                     -.4466964    .6480954
------------------------------------------------------------------------------
LR test of indep. eqns. :            chi2(2) =    86.94   Prob > chi2 = 0.0000
------------------------------------------------------------------------------

The $\rho$s are the union effects. $\rho_0$ is positive and significant, so folks who choose to work in the public sector earn lower wages in that sector than a random individual from this sample. Those working in the private sector fare no better or worse than a random individual. The signs are a tad counterintuitive, but the authors of the Stata code parameterized $\rho$ as negative (see the conditional expectations part of the movestay paper). The likelihood-ratio test for joint independence of the three equations is reported in the last line of the output. The "frontslashed" parameters are ancillary. Some folks prefer to multiply $\rho$ and $\sigma$ to get $\lambda$, with standard errors estimated using the delta method.
Now you can get the same estimates using heckman (though the sign on $\rho$ and the two instruments flips since the command is parameterized a bit differently). You see the same negative effect:
. /* regime 0 by hand */
> gen wage0=lmo_wage;

. replace wage0=. if private==1;
(261 real changes made, 261 to missing)

. heckman wage0 age age2 edu13 edu4 edu5 reg2 reg3 reg4
> , select(age age2 edu13 edu4 edu5 reg2 reg3 reg4 m_s1 job_hold) nolog;

Heckman selection model                         Number of obs      =      2094
(regression model with sample selection)        Censored obs       =       261
                                                Uncensored obs     =      1833

                                                Wald chi2(8)       =    742.40
Log likelihood = -2256.833                      Prob > chi2        =    0.0000

------------------------------------------------------------------------------
       wage0 |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
wage0        |
         age |  -.0370977   .0111445    -3.33   0.001    -.0589405   -.0152549
        age2 |   .0003741   .0001285     2.91   0.004     .0001221     .000626
       edu13 |  -.5064365   .0885104    -5.72   0.000    -.6799137   -.3329593
        edu4 |  -.4106208   .0507949    -8.08   0.000    -.5101769   -.3110647
        edu5 |  -.2973453   .0391905    -7.59   0.000    -.3741573   -.2205333
        reg2 |  -.3781878    .042037    -9.00   0.000    -.4605788   -.2957968
        reg3 |   .7051728   .0532121    13.25   0.000     .6008791    .8094666
        reg4 |  -.2356527   .0474641    -4.96   0.000    -.3286807   -.1426247
       _cons |   9.323934   .2377026    39.23   0.000     8.858045    9.789822
-------------+----------------------------------------------------------------
select       |
         age |   .1466592    .025787     5.69   0.000     .0961176    .1972007
        age2 |  -.0013735   .0003037    -4.52   0.000    -.0019687   -.0007783
       edu13 |   -.076687    .245785    -0.31   0.755    -.5584168    .4050427
        edu4 |  -.0686979   .1415071    -0.49   0.627    -.3460467    .2086509
        edu5 |  -.2348396   .1063477    -2.21   0.027    -.4432772    -.026402
        reg2 |   .4412484   .0957427     4.61   0.000     .2535961    .6289006
        reg3 |   .5975879   .1186466     5.04   0.000     .3650448    .8301309
        reg4 |   .6023803   .1127047     5.34   0.000     .3814832    .8232775
        m_s1 |  -.1501144   .0912879    -1.64   0.100    -.3290354    .0288066
    job_hold |  -.0528969   .0360066    -1.47   0.142    -.1234687    .0176748
       _cons |  -2.540299   .5744352    -4.42   0.000    -3.666172   -1.414427
-------------+----------------------------------------------------------------
     /athrho |  -1.354341   .0813714   -16.64   0.000    -1.513826   -1.194856
    /lnsigma |  -.4219375   .0186557   -22.62   0.000     -.458502   -.3853731
-------------+----------------------------------------------------------------
         rho |  -.8750741   .0190609                     -.9076157   -.8320789
       sigma |    .655775   .0122339                        .63223    .6801968
      lambda |  -.5738517   .0197394                     -.6125403   -.5351632
------------------------------------------------------------------------------
LR test of indep. eqns. (rho = 0):   chi2(1) =    86.73   Prob > chi2 = 0.0000

Using the two step just kills the results:
. heckman wage0 age age2 edu13 edu4 edu5 reg2 reg3 reg4
> , select(age age2 edu13 edu4 edu5 reg2 reg3 reg4 m_s1 job_hold) twostep nolog;

Heckman selection model -- two-step estimates   Number of obs      =      2094
(regression model with sample selection)        Censored obs       =       261
                                                Uncensored obs     =      1833

                                                Wald chi2(8)       =    785.30
                                                Prob > chi2        =    0.0000

------------------------------------------------------------------------------
       wage0 |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
wage0        |
         age |  -.0167191   .0266711    -0.63   0.531    -.0689936    .0355553
        age2 |   .0001794   .0002634     0.68   0.496     -.000337    .0006957
       edu13 |  -.5359287   .0884772    -6.06   0.000    -.7093407   -.3625166
        edu4 |  -.4296174   .0519778    -8.27   0.000    -.5314921   -.3277427
        edu5 |  -.3262479   .0496997    -6.56   0.000    -.4236576   -.2288383
        reg2 |  -.3635313   .0522697    -6.95   0.000     -.465978   -.2610847
        reg3 |   .7009662   .0576929    12.15   0.000     .5878902    .8140422
        reg4 |  -.2060982   .0685499    -3.01   0.003    -.3404535    -.071743
       _cons |   8.780537   .7149883    12.28   0.000     7.379185    10.18189
-------------+----------------------------------------------------------------
select       |
         age |   .1470191   .0276835     5.31   0.000     .0927603    .2012778
        age2 |  -.0013161   .0003254    -4.05   0.000    -.0019538   -.0006784
       edu13 |  -.3523344   .2632156    -1.34   0.181    -.8682275    .1635588
        edu4 |  -.2549107   .1524679    -1.67   0.095    -.5537422    .0439209
        edu5 |  -.4061875   .1181928    -3.44   0.001    -.6378411   -.1745339
        reg2 |   .3442086   .1039805     3.31   0.001     .1404105    .5480066
        reg3 |   .2811355   .1316528     2.14   0.033     .0231009    .5391702
        reg4 |    .543206   .1233285     4.40   0.000     .3014866    .7849253
        m_s1 |  -.1963717   .1067202    -1.84   0.066    -.4055396    .0127961
    job_hold |  -.0330325   .0426152    -0.78   0.438    -.1165567    .0504917
       _cons |  -2.355134   .6282926    -3.75   0.000    -3.586565   -1.123703
-------------+----------------------------------------------------------------
mills        |
      lambda |  -.3120253   .3390203    -0.92   0.357    -.9764929    .3524424
-------------+----------------------------------------------------------------
         rho |   -0.50931
       sigma |  .61264749
------------------------------------------------------------------------------

Now we replicate the second equation, with similar results:
. /* regime 1 by hand */
> gen wage1=lmo_wage;

. replace wage1=. if private==0;
(1833 real changes made, 1833 to missing)

. heckman wage1 age age2 edu13 edu4 edu5 reg2 reg3 reg4
> , select(age age2 edu13 edu4 edu5 reg2 reg3 reg4 m_s1 job_hold) nolog;

Heckman selection model                         Number of obs      =      2094
(regression model with sample selection)        Censored obs       =      1833
                                                Uncensored obs     =       261

                                                Wald chi2(8)       =    108.61
Log likelihood = -876.2178                      Prob > chi2        =    0.0000

------------------------------------------------------------------------------
       wage1 |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
wage1        |
         age |    .042193   .0292471     1.44   0.149    -.0151304    .0995163
        age2 |  -.0005043    .000317    -1.59   0.112    -.0011255    .0001169
       edu13 |   .3623925   .2845064     1.27   0.203    -.1952298    .9200149
        edu4 |  -.1449537   .1640929    -0.88   0.377    -.4665699    .1766624
        edu5 |  -.1525098   .1380139    -1.11   0.269    -.4230121    .1179925
        reg2 |  -.2824625   .1046311    -2.70   0.007    -.4875357   -.0773894
        reg3 |   .7258022   .1227223     5.91   0.000      .485271    .9663334
        reg4 |  -.1366248   .1385823    -0.99   0.324    -.4082412    .1349916
       _cons |   7.405325   .4670327    15.86   0.000     6.489958    8.320692
-------------+----------------------------------------------------------------
select       |
         age |  -.1454229   .0278551    -5.22   0.000    -.2000179   -.0908278
        age2 |   .0013006   .0003267     3.98   0.000     .0006602    .0019411
       edu13 |    .350613   .2632322     1.33   0.183    -.1653127    .8665387
        edu4 |    .255408   .1524632     1.68   0.094    -.0434144    .5542305
        edu5 |   .4065948    .118201     3.44   0.001      .174925    .6382645
        reg2 |  -.3430896   .1040295    -3.30   0.001    -.5469838   -.1391955
        reg3 |  -.2792558   .1317203    -2.12   0.034    -.5374229   -.0210887
        reg4 |  -.5416784   .1233898    -4.39   0.000     -.783518   -.2998389
        m_s1 |     .20616     .10797     1.91   0.056    -.0054572    .4177772
    job_hold |   .0366664   .0430434     0.85   0.394    -.0476972      .12103
       _cons |   2.305788   .6356115     3.63   0.000     1.060013    3.551564
-------------+----------------------------------------------------------------
     /athrho |    .148785   .3219452     0.46   0.644     -.482216     .779786
    /lnsigma |  -.5899825   .0569334   -10.36   0.000    -.7015699   -.4783951
-------------+----------------------------------------------------------------
         rho |   .1476968   .3149222                     -.4480166    .6525839
       sigma |    .554337   .0315603                      .4958063    .6197772
      lambda |   .0818738    .177591                     -.2661982    .4299457
------------------------------------------------------------------------------
LR test of indep. eqns. (rho = 0):   chi2(1) =     0.21   Prob > chi2 = 0.6457

. heckman wage1 age age2 edu13 edu4 edu5 reg2 reg3 reg4
> , select(age age2 edu13 edu4 edu5 reg2 reg3 reg4 m_s1 job_hold) twostep nolog;

Heckman selection model -- two-step estimates   Number of obs      =      2094
(regression model with sample selection)        Censored obs       =      1833
                                                Uncensored obs     =       261

                                                Wald chi2(8)       =     77.71
                                                Prob > chi2        =    0.0000

------------------------------------------------------------------------------
       wage1 |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
wage1        |
         age |  -.0364796   .0793241    -0.46   0.646     -.191952    .1189928
        age2 |   .0001722   .0007224     0.24   0.812    -.0012437    .0015881
       edu13 |   .5644776   .3613607     1.56   0.118    -.1437764    1.272732
        edu4 |  -.0199007    .215083    -0.09   0.926    -.4414556    .4016542
        edu5 |   .0559729   .2429543     0.23   0.818    -.4202087    .5321545
        reg2 |  -.4796038   .2147622    -2.23   0.026    -.9005299   -.0586776
        reg3 |   .5580965   .2076475     2.69   0.007     .1511148    .9650782
        reg4 |  -.4331516   .3103303    -1.40   0.163    -1.041388    .1750847
       _cons |   8.310527   .9964926     8.34   0.000     6.357438    10.26362
-------------+----------------------------------------------------------------
select       |
         age |  -.1470191   .0276835    -5.31   0.000    -.2012778   -.0927603
        age2 |   .0013161   .0003254     4.05   0.000     .0006784    .0019538
       edu13 |   .3523344   .2632156     1.34   0.181    -.1635588    .8682275
        edu4 |   .2549107   .1524679     1.67   0.095    -.0439209    .5537422
        edu5 |   .4061875   .1181928     3.44   0.001     .1745339    .6378411
        reg2 |  -.3442086   .1039805    -3.31   0.001    -.5480066   -.1404105
        reg3 |  -.2811355   .1316528    -2.14   0.033    -.5391702   -.0231009
        reg4 |   -.543206   .1233285    -4.40   0.000    -.7849253   -.3014866
        m_s1 |   .1963717   .1067202     1.84   0.066    -.0127961    .4055396
    job_hold |   .0330325   .0426152     0.78   0.438    -.0504917    .1165567
       _cons |   2.355134   .6282926     3.75   0.000     1.123703    3.586565
-------------+----------------------------------------------------------------
mills        |
      lambda |   .7462884   .6279665     1.19   0.235    -.4845034     1.97708
-------------+----------------------------------------------------------------
         rho |    0.87902
       sigma |   .8489974
------------------------------------------------------------------------------

A: You may want to try the approach as mentioned in this paper. http://www.bls.gov/osmr/pdf/ec050130.pdf


text:
Q: How to run a kubernetes job with a temporary help database I am creating a Kubernetes Job, which needs a temporary database for processing its tasks. i am having 2 docker images. 1 which is the job and 1 which is a mysql database containing already the database and the data needed for the job
I want to do something like this:
apiVersion: batch/v1
kind: Job
metadata:
  name: afmigration
spec:
  backoffLimit: 3
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: afmigration
        image: migrate-job:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 8080
        env:
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: postgres-credentials
              key: user

        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: postgres-credentials
              key: password

        - name: POSTGRES_HOST
          value: postgres-service
        - name: MYSQL_ROOT_PASSWORD
          value: root
        - name: MYSQL_DATABASE
          value: tmpdb
      - name: migration-test-data
        image: migration-test-data:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 3306
        env:
        - name: MYSQL_ROOT_PASSWORD
          value: root
        - name: MYSQL_DATABASE
          value: tmpdb

The problem here is that the database is first not being started. Also I probably need to define a service to get access to the database from the job. But my biggest question is how can I then stop the database, when the job finishes?
Here is the dockerfile of the migration-test-data:
FROM mysql:8.0
COPY ./*.sql /docker-entrypoint-initdb.d/

Here is the dockerfile for the afmigration, which is the job:
FROM frolvlad/alpine-oraclejdk8:slim

ARG JAR_FILE

COPY target/${JAR_FILE} /app/afmigration.jar

WORKDIR /app

ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app/afmigration.jar"]

A: MySQL database should start normally so it's possible that you have some problem in your docker image. As you are within the same POD you can access your MySQL using localhost as all containers within the same POD share the same network stack.
So making sidecar containers in jobs is not supported now in Kubernetes as you can see in this issue: https://github.com/kubernetes/kubernetes/issues/25908
but I would suggest to take a look on that bash-magic pointed in this comment:
https://github.com/kubernetes/kubernetes/issues/25908#issuecomment-308569672
containers:
  - name: main
    image: gcr.io/some/image:latest
    command: ["/bin/bash", "-c"]
    args:
      - |
    trap "touch /tmp/pod/main-terminated" EXIT
    /my-batch-job/bin/main --config=/config/my-job-config.yaml
    volumeMounts:
      - mountPath: /tmp/pod
    name: tmp-pod
  - name: envoy
    image: gcr.io/our-envoy-plus-bash-image:latest
    command: ["/bin/bash", "-c"]
    args:
      - |
    /usr/local/bin/envoy --config-path=/my-batch-job/etc/envoy.json &
    CHILD_PID=$!
    (while true; do if [[ -f "/tmp/pod/main-terminated" ]]; then kill $CHILD_PID; fi; sleep 1; done) &
    wait $CHILD_PID
    if [[ -f "/tmp/pod/main-terminated" ]]; then exit 0; fi
    volumeMounts:
      - mountPath: /tmp/pod
    name: tmp-pod
    readOnly: true
volumes:
  - name: tmp-pod
    emptyDir: {}

So it simply run non-ending program in background (this example is envoy) and look into shared directory where batch job will write information that it's ended. So sidecar will react on that information and kill non-ending process.


text:
Q: How to see complete process name that is running using prstat command on solaris I am running command "prstat -v" on Solaris but it is showing very short process name as below: (see last column values under PROCESS/NLWP). Which option in prstat gives me complete process name that is running?
 PID USERNAME USR SYS TRP TFL DFL LCK SLP LAT VCX ICX SCL SIG PROCESS/NLWP

  2709 root     0.0 0.0 0.0 0.0 0.0 0.0 100 0.0   0   0   0   0 sshd/1

  2624 root     0.0 0.0 0.0 0.0 0.0  50  50 0.0   0   0   0   0 in.rarpd/3

  2648 root     0.0 0.0 0.0 0.0 0.0 0.0 100 0.0   0   0   0   0 sendmail/1

 24429 root     0.0 0.0 0.0 0.0 0.0  98 2.5 0.0   1   0   1   0 java/807

A: You have to fall back on other utilities to get full process names.
For example:
$ pargs -l $$
/usr/bin/bash

A: I don't see any way to do that.

A: prstat on its own will not give you what you want. However if you use ps and awk you can often get enough. For example to check on the rss values for each process I use the command
ps -ef -o rss -o args |  awk '{ hr=$1/1024 ; printf("%13.6f Mb ",hr) } { for ( x=2 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | sort -n -r

A: Another option is to use the 'ww' argument with the bsd ps:
# /usr/ucb/ps -aguxww
root      1177  0.0  0.0    0    0 ?        S   Dec 13  0:00 zsched
root      1189  0.0  0.1 1868 1260 ?        S   Dec 13  0:00 /sbin/init
root      1208  0.0  0.211072 9144 ?        S   Dec 13  0:04 /lib/svc/bin/svc.startd
root      1239  0.0  0.21308811908 ?        S   Dec 13  0:18 /lib/svc/bin/svc.configd
root      1326  0.0  0.0 1592  852 ?        S   Dec 13  0:00 /sbin/sh /lib/svc/method/svc-dlmgmtd
root      1538  0.0  0.1 6972 4216 ?        S   Dec 13  0:30 /usr/sbin/nscd
root      1886  0.0  0.1 1956 1248 ?        S   Dec 13  0:00 /usr/sbin/cron
root      2045  0.0  0.1 2296 1312 ?        S   Dec 13  0:00 /usr/lib/saf/sac -t 300
root      2082  0.0  0.1 2476 1408 ?        S   Dec 13  0:00 /usr/lib/saf/ttymon
root      2118  0.0  0.1 3824 1764 ?        S   Dec 13  0:03 /usr/sbin/syslogd
root      2119  0.0  0.0 1572  844 ?        S   Dec 13  0:00 /usr/lib/utmpd
root      2132  0.0  0.1 6112 3468 ?        S   Dec 13  0:39 /usr/lib/inet/inetd start
root      2222  0.0  0.1 1872 1304 console  S   Dec 13  0:00 /usr/lib/saf/ttymon -g -d /dev/console -l console -m ldterm,ttcompat -h -p mail
root      2257  0.0  0.1 4124 1788 ?        S   Dec 13  0:00 /usr/lib/ssh/sshd
root      2489  0.0  0.1 2280 1324 ?        S   Dec 13  0:00 /usr/sadm/lib/smc/bin/smcboot
root      2491  0.0  0.0 2280  980 ?        S   Dec 13  0:00 /usr/sadm/lib/smc/bin/smcboot
root      2539  0.0  0.0 2280  976 ?        S   Dec 13  0:00 /usr/sadm/lib/smc/bin/smcboot
root      2854  0.0  0.1 5936 2620 ?        S   Dec 13  0:07 /usr/lib/sendmail -bl -q15m
root      3277  0.0  0.1 7784 2096 ?        S   Dec 13  0:00 /usr/dt/bin/dtlogin -daemon -udpPort 0
root     13216  0.0  0.1 6944 4188 ?        S   Dec 15  0:00 /usr/lib/ssh/sshd
root     13245  0.0  0.1 6944 4188 ?        S   Dec 15  0:00 /usr/lib/ssh/sshd
root     27680  0.0  0.0 1504  892 ?        S 12:35:21  0:00 sleep 3600
root     28311  0.0  0.1 6944 4220 ?        S 12:59:01  0:00 /usr/lib/ssh/sshd
#


text:
Q: Highcharts categories months don't add I want to display the months from Jan - Dec, but the data in series are steady. What happened, is that the months that only display in charts are from Jan - May. How will I do it? Please see below code,
function getchart2()
{

$('#container2').highcharts({
    chart: {
        type: 'column',
                renderTo: 'container'
    },
title: {
            text: 'Daily Events',
            style: {
                'color': '#06F',
                'font-family': 'Roboto',
                'font-size': '16px',
                'font-weight': 'bold'

            },
            useHTML: true
        },
    xAxis: {

       categories: [
            'Jan',
            'Feb',
            'Mar',
            'Apr',
            'May',
            'Jun',
            'Jul',
            'Aug',
            'Sep',
            'Oct',
            'Nov',
            'Dec'
        ],
        crosshair: true
    },

    yAxis: {
        min: 0,
        title: {
            text: 'No. of Events'
        },

        stackLabels: {
            enabled: true,
            style: {
                fontWeight: 'bold',
                color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
            }
        }
    },
  legend: {
            itemStyle: {

                'color': '#666',
                'font-family': 'Roboto',
                'font-weight': 'normal',
                'font-size': '11px'

            },

            useHTML: true
        },
     tooltip: {
        formatter: function() {
                return ''+ this.series.name +'
'+
                this.x +': '+ this.y;
        }
    },
    plotOptions: {
        column: {
        pointWidth: 30,
            stacking: 'normal',
            dataLabels: {
                enabled: true,
                color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
                style: {
                    textShadow: '0 0 3px black'
                }

            }
        }
    },

    series: [{
         name: 'Incoming',
        data: [
         {y: 10.4, color: '#FAA961'},  //incoming
          {y: 15.4, color: '#FAA961'},
          {y: 20.4, color: '#FAA961'},
          {y: 12.4, color: '#FAA961'},
          {y: 30.4, color: '#FAA961'},
        ],
        color: '#FAA961'
    }, {
        name: 'Ongoing',
        data: [
         {y: 10.4, color: '#438EF7'},  //incoming
          {y: 15.4, color: '#438EF7'},
          {y: 20.4, color: '#438EF7'},
          {y: 12.4, color: '#438EF7'},
          {y: 30.4, color: '#438EF7'},
        ],
        color: '#438EF7'
    }, {
        name: 'Finished',
        data: [
         {y: 34.4, color: '#43F752'},  //incoming
          {y: 35.4, color: '#43F752'},
          {y: 40.4, color: '#43F752'},
          {y: 42.4, color: '#43F752'},
          {y: 20.4, color: '#43F752'},
        ],
        color: '#43F752'
    }]
});

}

A: The answer to this would be same as this.
You only need to change the 'max' value to 11.


text:
Q: Can't change Bootstrap 5 carousel indicator border radius I'm using carousel component of Bootstrap 5.1. I realized that no matter what i do i cannot add border-radius to the carousel indicators. They are always rectangle and not accepting border radius. But in inspector it curiously shows indicators (html buttons) do have a border radius but not displayed. I'm so confused. I tried to style .carousel-indicators [data-bs-target] in css, added inline border-radius styling in html. None of them worked.

A: Try
.carousel-indicators [data-bs-target] {
  border-top: none;
  border-bottom: none;
  border-radius: 5px;
  height:6px;
}

The elements have a transparent border which are being styled with a border radius, but can not be seen because they are transparent.


text:
Q: Building your own camera module I would like to know how difficult it is to build your own camera module. For instance, how difficult would it be to assemble the Raspberry Pi camera module from scratch?
The reason I'm interested in this, is that camera modules for high quality image sensors often come with horrendous price-tags, and I would like to know why.
.
An anonymous example [to not shit-talk a specific seller :S]:
You can buy a camera modules for a quite good image sensor for 200 bucks + shipping costs online. However, the image sensor cost ~10$ in mass production, and probably ~20$ in smaller bulk orders. If we then factor in the price for some lenses ~35$ and lens holders ~5$, we come to a total component price of 50-60$.
--> So why is the selling price so high? Do I forget important parts? :S

A: There is much else at play in a commercial product other than just parts, cost to manufacture/assemble, cost of packaging, cost of advertising, payroll and facility overheads, repayment of investment development costs and on and on, plus ultimately a reasonable profit margin the market will tolerate.
Is it difficult to develop your own... well that depends on how much quality of image you want. You can throw the parts together fairly easily, but any graphics device is extremely susceptible to noise interference. It can take many design cycles to get an image that has the sustained quality you would expect.


text:
Q: jquery: chained crossfading for several elements I'm having several elements (PNG images containing text) which I'd like to animate/crossfade like a trailer.
It should be like this:

*

*element1 fades in - shows ~2 seconds, fades out, and at ~20% opacity.

*element2 should start fading in and so on.

So the difficult thing is, how can I use .animate() for chained crossfading?
Any ideas what's the best method?
Thanks


text:
Q: How to add a delay to confirm box? How can I add a delay on the return statement of a confirm box? I have tried using setTimeout but it doesn't work.
My idea is to display a modal for 5 seconds and then take the user to the signout page.
 Sign Out

 function singOutConfirm(){
      var c = confirm("Confirm Sign Out!");
      var modal = document.getElementById('myModal');
      console.log(c);
      if(c == true ) {
         setTimeout(function(){
            return c;
        }, 5000);
      }
      return c;

A: You sir, need a Promise.
But two things

*

*They are not supported in ie https://caniuse.com/#feat=promises. You might want to use Babel or Typescript to polyfill them. If you don't want to compile you JS consider using Bluebird for promises.

*Specifically in your example you are expecting to navigate to a URL on click. You are going to want to change the browsers location when the promise resolves. window.location.href = 'signout.cgi?id=$key'

function signOutConfirm (e) {
  e.preventDefault()
  const c = confirm("Confirm Sign Out!");
  const modal = document.getElementById('myModal');
  console.log(c);
  if(c) {
    return new Promise((resolve) => {
      setTimeout(() => {
        window.location.href = 'signout.cgi?id=$key'
        resolve(c)
      }, 5000);
    })
  }
  return Promise.resolve(c);
}

console.time('Signing out')
signOutConfirm()
  .then(c => {
    console.timeEnd('Signing out')
    console.log(c)
  })


text:
Q: What was the most dangerous programming mistake you have made in C? I am an intermediate C programmer. If you have made any coding mistake that you came to know later that it was the most hazardous / harmful to the total application please share that code or description. I want to know this because in future I may come across such situations and I want to have your advice to avoid such mistakes.

A: for(int i = 0; i<10; ++i)
  //code here
  //code added later

Note that the later added code is not in the for loop.

A: Uninitialized data.

A: The most dangerous thing I ever did in C was trying to write code which managed my own memory.  Effectively, this means the most dangerous thing I ever did in C was write C code.  (I hear that you can get around it these days.  Hip hip for sanity.  Use those approaches whenever appropriate!)

*

*I don't write paging algorithms -- OS geeks do that for me.

*I don't write database caching schemes -- database geeks do that for me.

*I don't build L2 processor caches -- hardware geeks do that for me.

And I do not manage memory.
Someone else manages my memory for me -- someone who can design better than I can, and test better than I can, and code better than I can, and patch when they make critical security-compromising mistakes which only get noticed 10 years later because absolutely everyone who attempts to allocate memory fails some of the time.

A: system() with some user-supplied string in the argument.  Same goes for popen().
Use exec*() instead.
Of course, this is not unique to C.

A: You should worry more about little mistakes. Big/spectacular mistakes are usually documented in books (with reasons why they are bad, alternative approaches etc.).
It's the little design/coding mistakes that get to you, because they tend to add up.
So my advice is to try and read the books Kernighan wrote or co-authored ("The C Programming Language", "Practice of Programming" etc.) because they are full of common-sense (common for experienced C programmers) advice and list principles that are very useful in avoiding both small and big mistakes.
They also list many potential big mistakes, so they answer your initial question.

A: I take the definition of dangerous as "we may ship with that bug and discover only years later when it's to late":
char* c = malloc(...);
.
.
.
free(c);
.
.
.
c[...] = ...;

or
// char* s is an input string
char* c = malloc(strlen(s));
strcpy(c, s);

But if you write multiplatform (not limited to x86/x64) this is also great:
char* c = ...;
int i = *((int*)c); // <-- alignment fault

And if your buffer comes from an untrusted source.. basically most code around is dangerous.
But, anyway, in C it's so easy to shoot yourself in the foot, that a topic about shot feet could go around the thousands of pages.

A: I'm in agreement with Pat Mac here (despite his downvoting). The most dangerous thing you can do in C is simply to use it for something important.
For example, a sensible language would by default check array bounds and stop your program immediately (raise an exception or something) if you try to wander outside of it. Ada does this. Java does this. Tons of other languages do this. Not C. There are entire hacking industries built around this flaw in the language.
One personal experience with this. I worked with a company that ran a network of flight simulators, tied together with reflective (shared) memory hardware. They were having a nasty crash bug they couldn't track down, so our two best engineers got sent up there to track it down. It took them 2 months.
It turned out that there was an off-by-one error in a C loop on one of the machines. A competent language would have stopped things right there of course, but C let it go ahead and write a piece of data in the next location past the end of the array. This memory location happened to be used by another machine on the network which passed it to a third machine, which used the (garbage) value as an array index. Since this system was also coded in C, it didn't care either that it was indexing way outside of its array, and trashing semi-random memory locations in its program.
So, due to a lack of array bounds checking, a simple easy to make off-by-one bug caused random crashes in a computer two entire hops away from the source of the bug! Cost to the company: 4 man-months of their best engineers' time, plus however much was spent by other engineers and support personnel, plus all the downtime from the simulators in question not working right.

A: if (c = 1) // insert code here

A: if(a == true);
{
  //Do sth when it is true. But it is allways executed.
}

Edit: Another variant of the same mistake.
for(i=0; i<max_iterations;i++);
{
  //Do sth but unexpectedly only once
}

A: When a pointer is first allocated, it does not have a pointee.
The pointer is "uninitialized"
A dereference operation on a bad pointer is a serious runtime error.
If you are lucky, the dereference operation will crash or halt immediately (Java behaves this
way). If you are unlucky, the bad pointer dereference will corrupt a random area of
memory, slightly altering the operation of the program so that it goes wrong some
indefinite time later. Each pointer must be assigned a pointee before it can support
dereference operations.

A: while(a)
{
   // code - where 'a' never reaches 0 :(
}

A: Two things comes to mind.
Ths first was a function in embedded C (MCU) i tried to have some restrictions on an timer value as a entered a function. so I wrote
if(55000 < my_var < 65000)

My ida was to check like this:
if( (55000<my_var) < 65000)

But this is the equivilant or the result
if( (55000<my_var) || (my_var<65000))

and the result ended up that the if test was always true.
The secound was a pointer mistake. (simplyfied presented here)
get_data(BYTE **dataptr)
{
  ubyte* data = malloc(10);
  ... code ...
  *dataptr = &data[1];
}

 main()
 {
   BYTE *data
   get_data(&data);
   free(data);
 }

Thus resulting in a loss of 1 byte of memory for each time the get_data() function was called

A: This is a famous historical example (not something I did), but
double d;      // d gets populated with a large number from somewhere
short s = d ;  // overflow

led to the explosion and total loss of an Ariane V rocket.

A: Few years ago I've got a call from my ex-colleague telling me about the problem he had to fix with my code, which was a router for credit card transactions.
Card number prefix consists of 6-digit BIN (Bank Identification Number) and extra few digits that banks use at own discretion, e.g. bank has BIN for Visa Classic card 456789, and reserve 2 extra digits to indicate sub-product, like 01 for student's card, 02 for co-branded card with local department store and so on. In this case card prefix, which is basically product identifier, becomes 8 digits long. When I coded this part, I decided that 9 digits "ought to be enough for everyone". It was running ok for 2 years until one day bank make a new card products with 10-digit-long prefix (have no idea why they needed it). Not too hard to imagine what has happened - router segfaulted, the whole system halted because it cannot function without transaction router, all ATMs of that bank (one of the biggest in the country) became non-operational for few hours, until problem was found and fixed.
I cannot post the code here firstly because I don't have it and secondly it is copyrighted by the company, but it is not hard to imagine the strcpy() without checking size of target buffer.
Just like man strcpy says:

If the destination string of a
strcpy() is not large enough  (that
is, if  the  programmer  was  stupid
or lazy, and failed to check the size
before copying) then anything might
happen.  Overflowing  fixed  length
strings is a favorite cracker
technique.

I was very embarrassed. But I've learned the lesson and do not forget (usually :) ) to check size of target buffer. I wouldn't recommend you to learn it the hard way - just develop a habit to check target buffer before strcpy() and strcat().
Edit: good suggestion from Healthcarel - use strncpy() rather than strcpy(). It doesn't add trailing 0 but I usually use following macro to get around it:
#define STRNCPY(A,B,C) do {strncpy(A,B,C); A[C] = 0; } while (0)

A: It has been a long time, but some things you never forget ;-).

*

*forget the \0 at the end of a string.

*allocate n characters for a string with n characters.

*forgetting the break in a switch statement.

*'creative' macro use.

A: Using non-limited string functions such as strcpy() or strcmp(), instead of safe versions like strncpy() and strncmp().

A: Passing virtual address to the DMA engine was a worst one, not exactly C related, but i assume that 99% of DMA related stuff written in C so it's kind of match.
This small error lead to memory corruption that took me 1.5 month to find.

A: switch case with no break.

A: Having been a Lisp programmer, I was used to indenting closing braces, as in:
(cond
    ((eq a foo)(bar ...
        ....
        ))
    )

and I carried this into C programming:
if (a == foo){
    bar(...);
    ....
    }

Then I got on a good-size project in C, and another programmer had to make changes in the vicinity of my code. He mis-read my closing brackets, and freed some memory too early. This caused an extremely subtle bug that happened at crunch time. When it was found, he got blamed, badly. But you could say it was my fault. That was not fun, to say the least.

A: Forgetting architecture constraints and happily memcpy()ing into the memory mapped I/O area on a microcontroller. The magic smoke was released from the test rig.

A: I was dealing with dynamically allocated 2D arrays and I instead of free()'ing N rows, I decided to free M columns. This was fine for smaller inputs where N == M but on large inputs, I only free()'d 50% of what I allocated.
shrug
Live and learn.

A: One thing to look after are array bounds. If you go out of bounds, with bad luck you may end up overwriting memory that is used for other data.
One nasty bug related to this was going out of bounds for a static array variable in a function. That ended up as a function changing values of the local variables of the calling function. That wasn't so straight-forward to debug..

A: I remember two blunders:

*

*returning address of an auto variable from within a function in which it was created;

*copying string to an uninitialised and unallocated pointer to char.

A: #include <string>

Me thinking C supports string natively (using Metroworks codewarrior, about 8 years ago).
I did this, for a final project of about 15,000 lines of code. I used this library to do everything relating to strings(appending, splitting, etc.) Only to have the TA's not able to compile any bit of my assignment(using GCC.)
Little did i learn that metroworks had created their own string library. I failed that class.

A: if (importantvar = importantfunction() == VALID_CODE)

This is when I meant this:
if ((important var = importantfunction()) == VALID_CODE)

This led to many hours of debugging troubles when I assumed it worked like the latter.

A: Forgot to put ; at the end.
 Excess }.
 Mistakenly typed a ,
These makes me go nuts for hours finding what stuffs have gone wrong with my codes.


text:
Q: Is there a way in moshi to mark a field in the response body template as optional? I am currently working on an android app where I am using moshi to parse the response from retrofit as json. But I have the problem that one or more fields in the response body are sometimes included and sometimes not, based on what data you are getting back.
For example:
sometimes you get back this (case 1):
{
   "fieldAaa": 33,
   "fieldBee": 2
}

and sometimes this (case 2):
{
   "fieldAaa": 33
}

My data class for the request body would currently look like this
data class RequestBodyTemplate(
        val fieldAaa: Int,
        val fieldBee: Int
)

so there is no distinction between the 2 cases mentioned above, which results in a crash when case 2 is present (meaning fieldBee is missing in the response)
Is there a way in moshi to mark this field as optional maybe(or other solution), or is there a solution in retrofit?


text:
Q: nested forms in Rails 4 doesn't seem to work I've been looking at this for far too long so here goes.

*

*Trying to do a simple nested form (have done it before many times in Rails 3) but I can't seem to get the nest fields to render in HTML.

*As you can see, I'm trying to build 3 'collection components' (my model) with 3.times { @collection.collections_components.build }. I do get one field but the 3.times is ignored.

*Seems as though f.fields_for :collection_components is ignored. It can be changed to f.fields_for :xyz and it executes the same one field.

Following this here: http://guides.rubyonrails.org/form_helpers.html#nested-forms
Here's some code:
collection.rb
class Collection < ActiveRecord::Base
    has_many :collections_components, dependent: :destroy
    accepts_nested_attributes_for :collections_components, allow_destroy: true
end

collections_component.rb
class CollectionsComponent < ActiveRecord::Base
    belongs_to :collection
end

_form.html.erb
<%= form_for @collection do |f| %>
  <% if @collection.errors.any? %>

<%= pluralize(@collection.errors.count, "error") %> prohibited this collection from being saved:

      <% @collection.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :name %>

    <%= f.text_field :name %>

  <%= f.fields_for :collection_components do |collection_components_form| %>

Collection

    <%= collection_components_form.label :text %>
    <%= collection_components_form.text_field :text %>
  <% end %>

    <%= f.submit %>

<% end %>

collections_controller.rb
class CollectionsController < ApplicationController
  before_action :set_collection, only: [:show, :edit, :update, :destroy]

  def index
    @collections = Collection.all
  end

  def show
  end

  def new
    @collection = Collection.new
    3.times { @collection.collections_components.build }
  end

  def edit
  end

  def create
    @collection = Collection.new(collection_params)

    respond_to do |format|
      if @collection.save
        format.html { redirect_to @collection, notice: 'Collection was successfully created.' }
        format.json { render :show, status: :created, location: @collection }
      else
        format.html { render :new }
        format.json { render json: @collection.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @collection.update(collection_params)
        format.html { redirect_to @collection, notice: 'Collection was successfully updated.' }
        format.json { render :show, status: :ok, location: @collection }
      else
        format.html { render :edit }
        format.json { render json: @collection.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @collection.destroy
    respond_to do |format|
      format.html { redirect_to collections_url, notice: 'Collection was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_collection
      @collection = Collection.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def collection_params
      params.require(:collection).permit(:name, collections_components_attributes: [:text])
    end
end

A: i think this could be the problem, you are calling the resource as a singular instead of plural in the _form (at the middle of the name for collection)
<%= f.fields_for :collection_components do |collection_components_form| %>

instead of this:
<%= f.fields_for :collections_components do |collection_components_form| %>

Also like i've been using nested_forms before i know that you will need to pass the "id" and only if you are allowing to destroy an attribute a "_destroy" param to the strong_parameters, so it will be good for you to add it
def collection_params
  params.require(:collection).permit(:name, collections_components_attributes: [:text])
end

So you should have something like this:
def collection_params
  params.require(:collection).permit(:name, {collections_components_attributes: [:id, :text, :_destroy]})
end

Also i would recommend this railscasts for future research and an excelent gem called cocoon to make nested_forms with ease
I hope it helps!

A: You need to show forms for all the collections_components. Change:
<%= f.fields_for :collection_components do |collection_components_form| %>

Collection

  <%= collection_components_form.label :text %>
  <%= collection_components_form.text_field :text %>
<% end %>

to:
<% @collection.collection_components.each do |collections_component| %>
  <%= f.fields_for :collection_components, collections_component do |collection_components_form| %>

Collection

    <%= collection_components_form.hidden_field :id %>
    <%= collection_components_form.label :text %>
    <%= collection_components_form.text_field :text %>
  <% end %>
<% end %>

The id's hidden field is necessary for updating. Also make sure it's included in the strong parameters.
EDIT:
I came across this problem with Rails 4.0.8. The version's document suggests this solution with each. Rails 4.2.0's document started suggesting only using fields_for. I suspect that fields_for started handling collection directly in 4.2.0, though I could not find any change log for it.


text:
Q: parse json string using simple-json I have read the posts that appeared to be the same as my question but I must be missing something.  My environment is Eclipse Mars.  My JAVA is 1.7 and I have imported json-simple.  I simply wish to parse the json that is returned from my web service.  I control the web service if I need to modify its output.  I see the json in arg[0] as noted below however the Object obj is null as of course is the JSONArray array.  I know that I am missing something basic but I am stumped and a bit tired.
Here is the returned json:
[{"$id":"1","NumberID":121183,"PortfolioID":718,"PropertyID":14489,"Adsource":17287,"PlanTypeID":1,"GreetingFile":"HolidayGreeting.wav","PromptFile1":"senior.leasing.first.wav","Accepts1":2,"PromptAction_ID1":1,"PromptFile2":"Default.wav","Accepts2":2,"PromptAction_ID2":1,"PromptFile3":"Default.wav","Accepts3":2,"PromptAction_ID3":1,"PromptFile4":"Default.wav","Accepts4":2,"PromptAction_ID4":1,"PromptFile5":"Default.wav","Accepts5":2,"PromptAction_ID5":1,"HoldMsgFile1":"SpectrumHold.wav","HoldMsgFile2":"Default.wav","Destination1":15197,"Destination2":15024,"Destination3":0,"UIType_ID":16,"RingCount":0,"Enabled":true,"Spanish":false,"HoldMusicFile":"Hold_Music.wav","Template_ID":41,"FrontLineForward":true,"DisclaimerFIle":"1Silence.wav"}]

Here is the parse code employing json-simple:
package parser;
import org.json.simple.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.*;

public class JsonParser
{
    private static JSONObject _jsonInput;

    public static void main(String[] args)
    {
        //TODO

       try{
           JSONParser parser = new JSONParser();
           Object obj = JSONValue.parse(args[0]);
           JSONArray array=(JSONArray)obj;
           String name = array.get(3).toString();
           System.out.println(obj);
       }
       catch(Exception e){
           e.printStackTrace();
       }
    }

}

A: The size of the array different than the index used
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(args[1]));
JSONArray array=(JSONArray)obj;
if (array.size() > 3)
  String name = array.get(3).toString();


text:
Q: Is it possible to have conditional options in ~/.ssh/config based on the calling application (ssh or sshfs)? In my ~/.ssh/config file I have the following option:
RemoteCommand /bin/sh -c 'tmux has-session && exec tmux attach || exec tmux'
This automatically starts tmux and connects to an existing session if possible when connecting via ssh.
This causes sshfs to fail to connect with the error read: Connection reset by peer.
Is there a way to apply this options selectively only when connecting with ssh and not when attempting to mount a filesystem with sshfs?
Note that I still want to load the remainder of the options in that file for sshfs, since they are still relevant.  Using sshfs -F /dev/null is not an option.
I could of course create two separate configuration files for ssh and sshfs, but that would require a bunch of duplication that seems unecessary.

A: Suppose you used a different hostname when you want to use tmux eg
for sshfs :
ssh user@remotehost

but for tmux
ssh user@remotehost_tmux

and then in your ~/.ssh/config have a section specific for the host remotehost_tmux
eg.
# Global Options
#UseRoaming no

# Hostname specific options
Host <hostname>_tmux
     RemoteCommand /bin/sh -c 'tmux has-session && exec tmux attach || exec tmux'
Hostname <hostname>
#


text:
Q: Run Instruments and Debug Console simultaneously How can I make an app "Run with performance tool" and at the same time Run the Debug Console in XCode?

A: You can use "Console" application on the mac itself. Any NSLog and several types of warnings/errors will show up in the "Console messages" section.
This is of course just logging, interactive debugging is not an option.

A: Just show the debug console  + MAJ + r or simply go to XCode preferences, Debuging section and set Show console on start.


text:
Q: Handling many text input fields in Django? I'm using Django 3 (still) on my resume website. I'm working on a Sudoku Solver as an example personal project, so I have 81 text input fields in a grid. I'm trying to find the least painful way to handle up to 81 inputs in Django, so I can pass the inputs to my Python function(s) that handle the sudoku logic. How would I go about getting the user input into my views.py and handling all of them?
I'm wanting to take whichever cells in which the user inputs numbers, process them through my Python function(s), and then send the full puzzle back into the cells once processed. I'm not super experienced with forms and form data in HTML just yet. For reference, here is my HTML that handles the grid. I know I'll need to add in maximum text length for the input fields, to ensure the user can only enter 1 digit per cell.

            <input type="text" size="3" id="cell1">
            <input type="text" size="3" id="cell10">
            <input type="text" size="3" id="cell19">
            <input type="text" size="3" id="cell28">
            <input type="text" size="3" id="cell37">
            <input type="text" size="3" id="cell46">
            <input type="text" size="3" id="cell55">
            <input type="text" size="3" id="cell64">
            <input type="text" size="3" id="cell73">

            <input type="text" size="3" id="cell2">
            <input type="text" size="3" id="cell11">
            <input type="text" size="3" id="cell20">
            <input type="text" size="3" id="cell29">
            <input type="text" size="3" id="cell38">
            <input type="text" size="3" id="cell47">
            <input type="text" size="3" id="cell56">
            <input type="text" size="3" id="cell65">
            <input type="text" size="3" id="cell74">

            <input type="text" size="3" id="cell3">
            <input type="text" size="3" id="cell12">
            <input type="text" size="3" id="cell21">
            <input type="text" size="3" id="cell30">
            <input type="text" size="3" id="cell39">
            <input type="text" size="3" id="cell48">
            <input type="text" size="3" id="cell57">
            <input type="text" size="3" id="cell66">
            <input type="text" size="3" id="cell75">

            <input type="text" size="3" id="cell4">
            <input type="text" size="3" id="cell13">
            <input type="text" size="3" id="cell22">
            <input type="text" size="3" id="cell31">
            <input type="text" size="3" id="cell40">
            <input type="text" size="3" id="cell49">
            <input type="text" size="3" id="cell58">
            <input type="text" size="3" id="cell67">
            <input type="text" size="3" id="cell76">

            <input type="text" size="3" id="cell5">
            <input type="text" size="3" id="cell14">
            <input type="text" size="3" id="cell23">
            <input type="text" size="3" id="cell32">
            <input type="text" size="3" id="cell41">
            <input type="text" size="3" id="cell50">
            <input type="text" size="3" id="cell59">
            <input type="text" size="3" id="cell68">
            <input type="text" size="3" id="cell77">

            <input type="text" size="3" id="cell6">
            <input type="text" size="3" id="cell15">
            <input type="text" size="3" id="cell24">
            <input type="text" size="3" id="cell33">
            <input type="text" size="3" id="cell42">
            <input type="text" size="3" id="cell51">
            <input type="text" size="3" id="cell60">
            <input type="text" size="3" id="cell69">
            <input type="text" size="3" id="cell78">

            <input type="text" size="3" id="cell7">
            <input type="text" size="3" id="cell16">
            <input type="text" size="3" id="cell25">
            <input type="text" size="3" id="cell34">
            <input type="text" size="3" id="cell43">
            <input type="text" size="3" id="cell52">
            <input type="text" size="3" id="cell61">
            <input type="text" size="3" id="cell70">
            <input type="text" size="3" id="cell79">

            <input type="text" size="3" id="cell8">
            <input type="text" size="3" id="cell17">
            <input type="text" size="3" id="cell26">
            <input type="text" size="3" id="cell35">
            <input type="text" size="3" id="cell44">
            <input type="text" size="3" id="cell53">
            <input type="text" size="3" id="cell62">
            <input type="text" size="3" id="cell71">
            <input type="text" size="3" id="cell80">

            <input type="text" size="3" id="cell9">
            <input type="text" size="3" id="cell18">
            <input type="text" size="3" id="cell27">
            <input type="text" size="3" id="cell36">
            <input type="text" size="3" id="cell45">
            <input type="text" size="3" id="cell54">
            <input type="text" size="3" id="cell63">
            <input type="text" size="3" id="cell72">
            <input type="text" size="3" id="cell81">

A: Modify your input field by adding name attribute to input element:
sudoku.html:
<form method="POST">
{% csrf_token %}
...
<input type="text" size="3" id="cell1" name="grid">
...
</form>

views.py:
def sudoku(request):
    grid = []
    if request.method == 'POST':
        grid = request.POST.getlist('grid')
    context = {'grid': grid}
    return render(request, 'sudoku.html' context=grid)

grid is a list of 81 elements. Now you can handle the interaction with simple HTML using form element or use ajax to query your view method.


text:
Q: Periodically fetch data and display it with Django I would like to implement a kind of "real-time" notification system in my Django application.
I would store some messages destined to a specific user in my database.
When a user is logged in the application, if there is a notification for him in the database, then the application displays it using the messages framework.
When he clicks on the message, it is deleted from the database.
I am a bit stuck on the "fetch the data every minute" thing. I heard of celery (http://docs.celeryproject.org/en/latest/#), but I would like to be sure it is the way to go there before diving in, because it seems a bit complicated to set up and use.
If there is an easy way to daemonise a django fonction, or if something similar to what I want to do already exist, I would appreciate any hint !

A: Here are some options to consider:

*

*celery. Yes, it's not that trivial to set up, but it's very easy to configure and use from your python/django side via django-celery. Also take a look at celery periodic tasks.

*rq (Redis Queue). Simple job queue that is easy to set up.

*django-cronograph. Creating and running cron jobs easily from admin commands.
Also see:

*

*Examples of Django and Celery: Periodic Tasks

*Django - Set Up A Scheduled Job?

A: If is just a simple task, you may do with Ajax.
Just declare one URL for the ajax query:
#urls.py

...
url(r'^ajax/my_query$', my_app.views.ajax_processor)
...

then in your my_app/views.py:
#views.py

def ajax_processor(request):

    ... do the processing you want as if it is a normal web request.
    ... like querying the database
    ... you can return a `json` dictionary
    ... or a normal `render_to_response` template with html

That should do on the server side. On the client side it would be lovely to use jQuery with the $.ajax function and do this:
$.ajax({
    url:'/ajax/my_query',  // a normal get request
    success:function(data){  // success is the callback when the server responds
        /* if is json what you decided to return then process the json dict
           if is normal html render it wherver you want
        */
    }
});

Is just a simple set up, a bit of code in server-side and a bit of code in client-side.
If you are planning to develop a heavily real-time based application then you should rely on a better library, but if you only need to do a little query asynchronous then you may consider this way.
Here is a good and simple ajax tutorial provided by the W3Schools to help you understand Ajax, and here you can find useful information about polling with ajax/jquery.
Good luck!


text:
Q: I cant add ssh to update-rc.d, says mismatch stop runlevel Im trying to get ssh start as the system start so I can putty my way into it remotly.
I've tried sudo update-rc.d ssh defaults but ut says
update-rc.d: using dependency based boot sequencing
update-rc.d: warning: ssh stop runlevel arguments (0 1 6) do not match LSB Default-Stop values (none)

Could anyone tell me what the right command would be?

A: You should use the following command to to that:
$ ln -s /etc/init.d/ssh /etc/rc2.d/S18ssh

This creates a symlink from /etc/init.d/ssh to /etc/rc2.d/S18ssh so the computer will start the ssh server during boot.


text:
Q: Auditing for Security and Events in multiple architecture system We have an application that uses various technologies and frameworks. It is 3 tier, uses Datasets, Object Mapping, MVC, inline SQL with Parameters, Various .NET There is lots going on  some third party and lots custom stuff of five years of development with many different developers thru the years. We use Log4Net for logging but want to move some stuff to an auditing system and begin robust auditing in that system. Stuff we are looking to audit is:

*

*Authentication events like attempted login, sucessfull

*Password changes and failures

*Links clicked

*Location of user

*IP Address

*Certain DML events

*Etc.

Is there any good way to accomplish this that is somewhat efficient? I was thinking of having a Domain Business Object that we can send the events to via certain functions. We could pass the data as the object like userchanges -> toXML(). Right now we are just looking at the new values and not old+new. There were ideas of adding method attributes and use reflection but I think that will slow things down too much. I think SQL auditing is not in my scope, they do their own thing and my scope is to do app auditing.
We are open to third party solutions and open to other ideas.
Thanks


text:
Q: Open Data Table in new Tab I have a Lightning Data table in my LWC. It is populated with line item data from an external source through apex. I want the data table to open in a new tab when a button is clicked.
Currently it is opening a new tab with the salesforce url and gives a message "This page is not available in Lighting...". The line items are not records but just text.
I have tried the following. I don't need a specific url as its just a tab to show the data table which is populated by apex callout:
<lightning-button label="google" title="Non-primary action" onclick={handleClick} class="slds-align_absolute-center"></lightning-button>

handleClick() {
    var url = "www.google.com";
    window.open(url, "_blank");
}

I have also tried with _blank and _parent:
Go to Site

A: In a browser, if you do not make it an absolute URL, it is presumed to be a relative URL. You can use either:
//www.google.com/

Or:
https://www.google.com/

The former tells the browser that this is a TLD (top level domain), using the current protocol (https), while the latter also explicitly specifies that https should be used.
Also, if you need a blank tab, just ask for it:
about:blank


text:
Q: How to be protected against power outages when writing app state to disk I have an application state which should be stored to a file. Each time it makes a new file with different name (like "data.bin.new") and then after writing deletes the original "data.bin" and renames "data.bin.new". Recently I had a power surgery and the data file was corrupted. How it could happened and how to protect against it?
    public void SaveData()
    {
        string newName = _dataFile + ".new";
        string bckName = _dataFile + ".bck";
        string normalName = _dataFile;

        using (var f = File.Create(newName))
        {
            f.SetLength(0);
            AqlaSerializer.Serializer.Serialize(f, V);
        }

        var test = LoadData(newName);
        if (!typeof(T).IsValueType && ReferenceEquals(test, null)) throw new Exception("Can't load what's been saved");

        if (File.Exists(bckName)) File.Delete(bckName);
        if (File.Exists(normalName)) File.Move(normalName, bckName);
        File.Move(newName, normalName);
    }


text:
Q: modernizr.js a little questions about it I wanna use the www.modernizr.com project for my site and run into a little question.
A comment in the very beginning of the modernizr.js tells me:

Modernizr tests which native CSS3 and HTML5 features are available in
   the current UA and makes the results available to you in two ways:
   as properties on a global Modernizr object, and as classes on the
   html element. This information allows you to progressively enhance
   your pages with a granular level of control over the experience.

So what means "as classes on the html element" ?
I tested it and just use the header element (which is HTML5) in my document and manipulate it via css.
After that i opened it with IE6 and ......YEA it shows correct!
So:
I thought header is and "element" of html not a class of html!? So is this comment in the modenizr.js correct?
Hope you understand my little (or maybe hard to understand) question :)
Regards

A: What modernizr does is, depending on what your browser support, add classes to the <html> element to let you know (mostly via CSS or even JS) what exactly seems to work properly.
That means, that if my browser doesn't support javascript, I'll get something like this if I inspect the DOM (using, for example, Chrome's profiler)
<html class="no-js ...">...</html>

Hope this helps.


text:
Q: How to copy the primary key from another table as my form's field default value in APEX? I got a "user" table and a "student" table, in user table there are some attributes such as user_id, lname, fname and gender, in student table there are some other attribute such as course, WAM and user_id as foreign key to join student table with user table.
Now I am creating a form for user to register account.
I created a form for user to insert data into user table, after clicking the "next" button it will come to another form to let user insert data into student table.
How can I bring the user_id from the previous form into the second form as default value so data in both table can join together?
For example in first form the user got his user_id as 10002, and I want to bring this value into second form's user_id field as default value.

A: Two pages, right?
Page 1, user data:

*

*create a button ("Next", as you said)

*in its "Behavior" section, set action to Redirect to page in this application

*click the "Target" button and

*

*set it to go to page 2

*set items: name = P2_ID, value = &P1_ID. (pay attention to leading ampersand and trailing dot)

Page 2, student data:

*

*it should contain the P2_ID item which will accept value transferred from page 1

*use that value while storing student's data into the table


text:
Q: Time complexity of the following Prim's algorithm implementation What is the time complexity of the following code? I'm implementing prim's algorithm with adjacency matrix representation of the graph and priority queue. In my opinion, the time complexity is: the heap can grow at most to the size of (n-1), when the source is connected to every other node, and in the inner loop, the adjacency matrix is costing O(n), so in total: its O((n-1) * n) -> O(n^2), where n is the number of nodes. Is that calculation correct? So the heap is not improving my worst case runtime because of the adjacency matrix?
from graph import adj_mtx, AP
import heapq as hq

lv, visited, h = float('inf'), {}, []  # lv stands for 'large_value', h is the heap

def prims_mst(adj_matrix, src):
    hq.heappush(h, (0, (src, None)))  # O(logn)
    curr_dist = {item.value: lv if item.value != src else 0 for item in AP}  # AP is the enumeration of nodes

    while len(h) != 0:
        curr_nd = hq.heappop(h)[1][0]  # first element of the tuple is the value, second is the node  # O(1)
        visited[curr_nd] = True  # O(1)
        for nd, dst in enumerate(adj_matrix[src]):  # O(n) -> n is the number of nodes
            if nd not in visited and curr_dist[nd] > curr_dist[curr_nd] + adj_matrix[curr_nd][nd]:
                curr_dist[nd] = curr_dist[curr_nd] + adj_matrix[curr_nd][nd]
                hq.heappush(h, (curr_dist[nd], (nd, curr_nd)))  # O(logn)
        print h

A: It depends on what the len(h) does, what values it returns, and how the while behaves. When you find this out you multiply it with o(n) from the for and o(log n) from hq.headpush and you get your complexity
It's something like O(x*nlog n) where X is the steps it takes for the while to finish.


text:
Q: Drawing lines with opengl in Haskell I'm trying to create a go board using opengl. To do this, I'm trying to draw a bunch of lines to create the grid. However, every tutorial site (including opengl's) has the examples in C++ and the Haskell wiki doesn't do a good job of explaining it. I'm new to opengl and would like a tutorial.

A: I'll assume that you want to use OpenGL 2.1 or earlier. For OpenGL 3.0, you need different code.
So, in C you would write this:
glBegin(GL_LINES);
glVertex3f(1, 2, 3);
glVertex3f(5, 6, 7);
glEnd();

You write the equivalent in Haskell like this:
renderPrimitive Lines $ do
  vertex $ Vertex3 1 2 3
  vertex $ Vertex3 5 6 7

With this code, since I used e.g. 1 instead of some variable, you might get errors about ambiguous types (So you should replace 1 with (1 :: GLfloat)), but if you use actual variables that already have the type GLfloat, you shouldn't have to do this.
Here's a complete program that draws a white diagonal in the window:
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT

main :: IO ()
main = do
  -- Initialize OpenGL via GLUT
  (progname, _) <- getArgsAndInitialize

  -- Create the output window
  createWindow progname

  -- Every time the window needs to be updated, call the display function
  displayCallback $= display

  -- Let GLUT handle the window events, calling the displayCallback as fast as it can
  mainLoop

display :: IO ()
display = do
  -- Clear the screen with the default clear color (black)
  clear [ ColorBuffer ]

  -- Render a line from the bottom left to the top right
  renderPrimitive Lines $ do
    vertex $ (Vertex3 (-1) (-1)  0 :: Vertex3 GLfloat)
    vertex $ (Vertex3   1    1   0 :: Vertex3 GLfloat)

  -- Send all of the drawing commands to the OpenGL server
  flush

The default OpenGL fixed-function projection uses (-1, -1) for the bottom left and (1, 1) for the top right of the window. You need to alter the projection matrix to get different coordinate spaces.
For more complete examples like this, see the Haskell port of the NEHE tutorials. They use the RAW OpenGL bindings, which are more like the C bindings.

A: A quick google turned up this:
http://www.haskell.org/haskellwiki/OpenGLTutorial1
In any case, since OpenGL is originally a C library, you may want to get your feet wet in C (or C++) first, since you'll be able to use the original OpenGL documentation as-is; after that, you may want to dig into the Haskell bindings and see how you use the same OpenGL calls in Haskell.


text:
Q: JSON delete specific keys from nested objects without knowing key names I have a json file and want to delete some subkeys i don't need. Here is some part of the JSON file :
{
  "peers":{
    "swp1":{
      "hostname":"Spine-01",
      "remoteAs":65001,
      "version":4,
      "msgRcvd":452,
      "msgSent":459,
      "tableVersion":0,
      "outq":0,
      "inq":0,
      "peerUptime":"00:19:15",
      "peerUptimeMsec":1155000,
      "peerUptimeEstablishedEpoch":1635674862,
      "prefixReceivedCount":30,
      "pfxRcd":30,
      "pfxSnt":43,
      "state":"Established",
      "idType":"interface"
    },
    "swp2":{
      "hostname":"Spine-02",
      "remoteAs":65001,
      "version":4,
      "msgRcvd":452,
      "msgSent":459,
      "tableVersion":0,
      "outq":0,
      "inq":0,
      "peerUptime":"00:19:14",
      "peerUptimeMsec":1154000,
      "peerUptimeEstablishedEpoch":1635674863,
      "prefixReceivedCount":30,
      "pfxRcd":30,
      "pfxSnt":43,
      "state":"Established",
      "idType":"interface"
    }
  }
}

for example, i want to delete the "version" subkey, and i already tried this command
del(.peers.swp1.version, .peers.swp2.version)

and it worked well. But the thing is, the "swp1" and "swp2" are the interfaces and are something that can change their name, increase or decrease. So I need a command that works to delete the "version" subkeys no matter what the interface name is.

A: All you need is map_values and del.
.peers |= map_values(del(.version))

demo in jqplay

A: You can also use this syntax :
del(.peers[].version)|del(.memory)