text:
Q: How can I provide configuration variables to a Sass/SCSS file before including it? I'm migrating a Stylus library to SCSS since Angular 12 has deprecated Stylus and I'm in that impacted 0.3%. I've run into something we were doing that I'm not sure how to convert to SCSS—maybe it's impossible.
Let me lay this out simply: I work on several projects that all use loads of the same styles, so we put those styles together into one style sheet in its own NPM package. We can then just grab @import '@company/design/styles'; and suddenly we've got all of our regular styles and variables and mixins available in the project, or we can import @import '@company/package/styles/common'; for just the variables and mixins.
The thing is, our projects might need to configure the library before we import it. Suppose the library contains this bit:
// @company/package/styles/_forms.scss
input:invalid {
  background: url('/assets/input-error.svg') no-repeat center right;
}

Not every project will have /assets/input-error.svg at that exact location. Maybe one of my projects has to use /subfolder/static/input-error.svg.
I could include this then overwrite input:invalid { background-image: url(...) } to supply it with the correct location, but there may be many references to this particular file and many other assets on top of that to correct. So we instead, in our Stylus library, we introduced an $asset-input-error variable that points to /assets/input-error.svg by default and did something like this:
// @company/package/styles/_forms.scss
input:invalid {
  background: url($asset-input-error) no-repeat center right;
}

// the local project
$asset-input-error: '/subfolder/static/input-error.svg';
@import '@company/package/styles';

The above is heavily simplified and isn't actually legitimate SCSS, but I hope it conveys what we're trying to do: we want to set up what are effectively environment variables in our SCSS, include the common style sheet, and have it use those variables.
The thing is, I'm not sure what the legitimate or idiomatic approach is to do this in SCSS. Unlike Stylus, which has a global scope for its variables, SCSS would have me @use '../config'; and reference config.$asset-input-error, and from outside the library there's no way I see to change the configuration to point that asset to a different location. I'm sure SCSS has a way for me to do this, but I'm not sure what it is. Do I convert the entire library into a giant mixin to which I pass optional configuration? Do I do something with global variables? Something else?
How can I provide variables to my SCSS style sheet to configure it as part of including it in a project?
Ultimately the end goal here is just to be able to say to the library things like: "the assets to reference are here" (very important) or "the error color is this in this particuilar project" (less important).

A: Using @import
You can use global variables declared before the @import as you stated.
SCSS Documentation for this method
@company/package/styles/_forms.scss
$asset-input-error: '/subfolder/static/input-error.svg' !default;

input:invalid {
  background: url($asset-input-error) no-repeat center right;
}

@company/package/styles/styles.scss
@import 'forms';

local.scss
$asset-input-error: '/different/path/input-error.svg';
@import '@company/package/styles';

CodeSandbox Demo
Using @use [...] with
You can also hop aboard the @use train if you prefer to future-proof your library.
SCSS Documentation for this method
SCSS Documentation for using mixins
SCSS Documentation for configuring forwards
@company/package/styles/_forms.scss
$asset-input-error: '/subfolder/static/input-error.svg' !default;

input:invalid {
  background: url($asset-input-error) no-repeat center right;
}

@company/package/styles/styles.scss
@forward 'forms';

local.scss
@use 'styles' with (
  $asset-input-error: '/different/path/input-error.svg'
);

Sadly CodeSandbox and StackBlitz don't support dart-sass, so I don't have a live demo for this but I tested it on the latest version of sass from npm.


text:
Q: backward elimination/forward selection in multilinear regression in Julia I'm quite new to Julia.
Is there a package in Julia which helps in automating the backward or forward elimination of features for a multiple linear regression problem.
I have found the code in python here and here but not able to find any in Julia.
Thanks in advance !

A: Given no response there is probably no support :). The reason is most likely that typically Lasso etc. are preferred to forward/backward selection. And you have support for regularization e.g. in Regression.jl.
However, it is pretty simple to write your own step-wise selection:
using DataFrames
using RDatasets
using StatsBase
using GLM

function compose(lhs::Symbol, rhs::AbstractVector{Symbol})
    Formula(lhs, Expr(:call, :+, [1;rhs]...))
end

function step(df, lhs::Symbol, rhs::AbstractVector{Symbol},
              forward::Bool, use_aic::Bool)
    options = forward ? setdiff(names(df), [lhs; rhs]) : rhs
    fun = use_aic ? aic : bic
    isempty(options) && return (rhs, false)
    best_fun = fun(lm(compose(lhs, rhs), df))
    improved = false
    best_rhs = rhs
    for opt in options
        this_rhs = forward ? [rhs; opt] : setdiff(rhs, [opt])
        this_fun = fun(lm(compose(lhs, this_rhs), df))
        if this_fun < best_fun
            best_fun = this_fun
            best_rhs = this_rhs
            improved = true
        end
    end
    (best_rhs, improved)
end

function stepwise(df, lhs::Symbol, forward::Bool, use_aic::Bool)
    rhs = forward ? Symbol[] : setdiff(names(df), [lhs])
    while true
        rhs, improved = step(df, lhs, rhs, forward, use_aic)
        improved || return lm(compose(lhs, sort(rhs)), df)
    end
end

Two key parameters above are forward (do we do forward or backward selection) and use_aic (do we use AIC or BIC). Of course all this can be easily changed. The implementation is not optimized for speed, but should be good enough in simple cases.
Here is how can you use it:
df = dataset("datasets", "swiss")[2:end]
stepwise(df, :Fertility, true, false)
stepwise(df, :Fertility, true, true)
stepwise(df, :Fertility, false, true)
stepwise(df, :Fertility, false, false)

(all options return the same model and are consistent with a reference example in R)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Instance variable used while 'self' is not set to the result of '[(super or self) init...]' - (id)init{
    if(![super init]){
        return nil;
    }
    _rssItems = [[NSMutableArray alloc]init];
    return self;
}

If I analyze my project I get this warning:

Instance variable used while 'self' is not set to the result of
  '[(super or self) init...]'

What do I have to change?
Thanks!

A: Nowadays, Apple's official recommendation is:
- (id)init{
    self = [super init];
    if(self){
        _rssItems = [[NSMutableArray alloc]init];
    }
    return self;
}

The idea is that init (in particular, in this case, [super init]) is allowed to return an object other than self, and the expected behavior in that case is to work with that object instead--the easiest way to deal with this is to just set self to whatever super returns. Also note that return self; works fine whether self is nil or not, hence the reversal of your if.
Of course, most classes don't perform this switching trick--but this is good practice anyway because Apple expects everyone to be using this exact pattern for their init, so even if your subclass currently works without assigning to self, they could easily change that behavior in the future without warning.


text:
Q: Angular ErrorHandler http error I'm using angular (4.x.x) and I'm struggling with error generated with http requests.
In this plnkr I tried to summarize a case. I'm generating some errors and trying to record them. When I generate an error due to an http call the angular change detection seems to break and I miss the first http error.
I'm using an ErrorHandler implementation to intercept the error
@Injectable()
export class CustomExceptionHandler extends ErrorHandler {

  constructor(private errMsgService: ErrorMessageService) {
    super();
  }

  public handleError(err: any): void {
    let localErr = err;
    if (err.originalException) {
      localErr = err.originalException;
    }
    if (localErr instanceof CustomException) {
      console.log(`Handling CustomException`);
      // stream errors through the service
      this.errMsgService.addError(localErr);
    } else {
      super.handleError(err);
    }
  }
}

and record it in a service:
@Injectable()
export class ErrorMessageService {
  private errorMessagesEmitter:ReplaySubject<CustomException> = new ReplaySubject<CustomException>();
  errorMessages = this.errorMessagesEmitter.asObservable();

  public addError(err: any) {
    this.errorMessagesEmitter.next(err);
  }
}

In the plunker I'm simply listening to the ErrorMessageService and printing the generated error. When the error start from an Http I miss an error.
If I un-commment app.ts line 36, where I force a tick(), the error is visualized correctly.
this.errMsgService.errorMessages.subscribe(e => {
  this.errorCount++;
  this.errors.push({ 'error': e, 'count': this.errorCount});
  this.errorToConsole(e);

  // this.appRef.tick();
});

Is this the expected behaviour? otherwise what am I doing wrong?
update
Looking at recent angular changes, I focused on this: [https://github.com/angular/angular/commit/a1bb9c2].
I decided to try launching my example error handling inside the NgZone and I modified the plnkr
  this.ngZone.run(() => {
    // stream errors through the service
    this.errMsgService.addError(localErr);
  });

With this modification it's working.


text:
Q: Fabricjs: Load svg from local folder I need to load 1.svg from a local folder. In the following code, when I replace fabric.loadSVGFromURL("http://fabricjs.com/assets/1.svg" with fabric.loadSVGFromURL("1.svg", the image no longer displays in canvas. What am I doing wrong? What is the correct code?
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border: 1px solid red; }
</style>
<script>
    $(function(){
        var canvas = new fabric.Canvas('canvas');
        var group = [];
        fabric.loadSVGFromURL("http://fabricjs.com/assets/1.svg",function(objects,options) {
            var loadedObjects = new fabric.Group(group);
            loadedObjects.set({
                left: 100,
                top: 100,
                width:175,
                height:175
            });
            canvas.add(loadedObjects);
            canvas.renderAll();
        },function(item, object) {
                object.set('id',item.getAttribute('id'));
                group.push(object);
        });
    }); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width="900" height="900"></canvas>
</body>
</html>

A: Chrome's security model doesn't allow it. You can run with the command line option --allow-file-access-from-files to override this.

A: Is this file hosted on a server ? If its not, once you host the html file in a server it will display the svg image. The svg file need to be in the same folder under the website where you place the html file.


text:
Q: Is there any way to pause a HTTP request using chrome.webRequest without locking the entire browser? I'd like to display headers intercepted with chrome.webRequest.onBeforeSendHeaders to the user for editing, preferably using chrome.tabs.executeScript. However, chrome.tabs.executeScript is asynchronous and I can't find a way to wait for it to return without freezing the entire browser.
In other words, I'm aiming for what the code below gives, except with a HTML UI and without freezing any unrelated tabs.
chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
    for (var i = 0; i < details.requestHeaders.length; ++i) {
      if (details.requestHeaders[i].name === 'User-Agent') {
          var foo = prompt('User-Agent', details.requestHeaders[i].value);
          // chrome.tabs.executeScript(details.tabId,{code:""});
          //^create a nice HTML overlay & pass the user input back
          details.requestHeaders[i].value = foo;
         break;
      }
    }
    return {requestHeaders: details.requestHeaders};
  },
  {urls: ["http://*/*"], types: ["main_frame"]},
  ["blocking", "requestHeaders"]);

If it's impossible that'd be nice to know too, since I could file a feature request.

A: EDIT: Promises are only supported by Firefox's webRequest API.
You should use promises, you can (for example) create a sleep command that holds up the current thread until a promise value is returned after X seconds (or when you are done editing the headers):
const sleep = async seconds => {
    return new Promise(async(resolve)=>{
        setTimeout(resolve, seconds * 1000);
    });
}

Please note that asynchronous functions must be called on an asynchronous thread, so you should initiate your app (or just your listener function) inside an asynchronous function. This can be an anonymous function if you like (a function with no name):
(async()=>{
    await sleep(2);
    // do something after waiting 2 seconds.
})();

A working example in your case would be to declare your blocking listener function as asynchronous, like so:
const promptUserToEditHeaders = async details => {
    return new Promise(async(resolve)=>{
        // prompt the user to edit the request headers
        // then call resolve() when you are done editing headers
    });
}

chrome.webRequest.onBeforeSendHeaders.addListener(
    async details => {
        await promptUserToEditHeaders(details);
    },
    {urls: ["http://*/*"], types: ["main_frame"]},
    ["blocking", "requestHeaders"]
);

Read more about JavaScript promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Read more about async and await: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

A: I am not sure if this will work, but worth a shot.
You could set up a while loop that holds the return until your executed scripts returns a message via Message Passing. Also, you will need to use the webRequestBlocking permission in your manifest (which you probably already have).
chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
        var holdReturn = false;

        for (var i = 0; i < details.requestHeaders.length; ++i) {
            if (details.requestHeaders[i].name === 'User-Agent') {
                holdReturn = true;
                chrome.extension.onRequest.addListener(
                    function(request, sender, sendResponse) {
                        if (request.userAgentOverride) {
                            details.requestHeaders[i].value = request.userAgentOverride;
                            holdReturn = false;
                        }
                    });

                chrome.tabs.executeScript(details.tabId,{file: "user-agent-dialog.js"});
                break;
            }
        }

        while (holdReturn) {
            // waiting...
        }

        return {requestHeaders: details.requestHeaders};
     },
  {urls: ["http://*/*"], types: ["main_frame"]},
  ["blocking", "requestHeaders"]);

The user-agent-dialog.js file would then have:
function onFormSubmit() {
    chrome.extension.sendRequest(null, {
        userAgentOverride: userAgentValueFromInput
    });
}

// code to create the dialog and form, this will call
// onFormSubmit() when the form is submitted to send a
// message back to the background page.


text:
Q: what does python really do when it starts to run? I learned that the SyntaxError is the only error that can not be caught.
for example:
if __name__ == "__main__":
    print "main running"
    try:
        for i in range(3):
    except SyntaxError,e:
        print "error caught"
    finally:
        print "i am here"

well, I expect print "main running" could be displayed, well it doesn't
so does python check all the syntax before it runs?

A: Python compiles the code to bytecode first. If that fails, a SyntaxError is raised, indicating a failure to compile.
As such you cannot catch a SyntaxError exception from within the module that has a syntax error itself. Since Python compiles files as needed, you can catch SyntaxError exceptions for modules you import.
The following prints Failed to import test:
test.py
print,

catchsyntaxerror.py
try:
    import test
except SyntaxError:
    print 'Failed to import test'

then run python catchsyntaxerror.py.

A: It is impossible to detect SyntaxError at runtime because invalid syntax compromises the validity of the whole module, not only of the specific line where the author perceives to have made a mistake. Since the interpreter doesn't understand the author's intentions, the only thing it can do after failing to read the source is raise the error.
As Martin Pieters answered, the failure occurs at the compilation step at which Python reads the whole module and compiles it to memory before running it. However, even without a separate compilation step, the underlying problem with catching inline syntax errors at run-time would remain.
To catch syntax errors at run-time within the same module, one must isolate the erroneous code from the surrounding code. This can be done using the exec statement or the eval function:
>>> try:
...     exec """
... this doesn't work
... """
... except SyntaxError:
...     print "fail"
...
fail

To catch syntax errors in imported modules, simply put the try/except around the import statement.


text:
Q: Looking for an inequality between Chern and Todd classes (something in style of Bogomolov-Miyaoka-Yau)
*

*Consider a smooth projective surface $S\subset\Bbb P^N_{\Bbb C}$ which is a complete intersection of hypersurfaces of degrees $(d_1,..,d_{k\ge2})$ with $d_i\ge2$ for all i. Is it true that for such surfaces $c^2_1\le 2c_2$?  (i.e. much better than BMY)
At least asymptotically (i.e. for high enough $d_i$'s)?

Let  $td_2$ be the top-dimensional Todd class, i.e. $td_2=\frac{c^2_1+c^2}{12}$. The inequality as above can be written as $c_2\ge 2^2td_2$.

*

*More generally, let $X\subset\Bbb P^N_{\Bbb C}$ be a smooth complete intersection of dimension $n$. Let $c_n$ and $td_n$ be its top-dimensional Chern and Todd classes. What are the known inequalities on $c_n$ and $td_n$?  (I would like to have smth like $c_n\ge 2^n td_n$)

A: By the formulae in [Barth-Peters-Van de Ven, Chapter V] one has, for a surface which is complete intersection of type $(d_1, \ldots, d_{n-2})$ in $\mathbb{P}^n$:
$$c_1^2(X)= \big(\sum d_i-(n+1)\big)^2 \prod d_i,$$
$$c_2(X)=\bigg[\binom{n+1}{2}-(n+1)\sum d_i+\sum d_i^2 +\sum_{i < j} d_id_j \bigg]\prod d_i.$$
Then one obtains that the inequality
$$c_1^2(X) \leq 2 c_2(X)$$
is equivalent to
$$n+1 \leq \sum d_i^2,$$
and this is of course almost always true, since the right-hand term is $\geq 4(n-2)$.
So the answer to $1.$ seems to be yes.
ADDED. Actually, this is also written in the book by Barth-Peters- Van de Ven. In Chapter V, at the beginning of the Section "The Geography of Chern Numbers", they say:

"
  The simplest examples, like complete intersections and double coverings of $\mathbb{P}^2$, pratically always yield a point of $D_1$ [where $D_1$ is the region in the $(c_1, c_2)$-plane given by $c_1^2 \leq 2c_2$]. Indeed, for a long time only few examples were known of surfaces  with Chern pairs $(c_1^2, c_2)$ in $D_2$ [i.e., such that $2c_2 < c_1^2 \leq 3c_2$]."

For your question in the last comment, instead, the answer is clearly no if $S$ is ACM. In fact, every smooth surface $S$ with $H^1(S, \mathcal{O}_S)=0$ is ACM for some embedding in the projective space. Now take for instance a fake projective plane. It satisfies $p_g(S)=q(S)=0$, so it is ACM, but $$c_1^2(S)=3c_2(S).$$


text:
Q: bad hour errors in crontab file, can't install I want my crontab to be every 4 hours but from a certain time 1 pm:
I chose this config:
0 1/4 * * *

but if I save I get the error:
bad hour errors in crontab file, can't install.

This following works perfectly, but then I cannot decide the starting time.
0 */4 * * *

A: You can't have 1/4 as the hours. This means "run at 01:00 (1am), every 4 hours". What you need is "run from 01:00 (1am) until the end of the day, every 4 hours".
0 1-23/4 * * *

You could also write this with the explicit hour numbers listed out, but I personally find this harder to process visually, and it's not so obvious that it means "every four hours from 1am":
0 1,5,9,13,17,21 * * *


text:
Q: htaccess weird revert happening with a url rewrite rule and a 301 redirect I'm having issues trying to do a 301 redirect in my htaccess file. It is having a problem working with a part of my rewrite rules I have created. In summary, the rewrite strips the extension off of the page and replaces the query ?primary-view=city to /city. Here is my htaccess file.
RewriteEngine On
# Redirect /page.php to /page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(page)\.php [NC]
RewriteRule ^ /%1 [R=302,L]
# Internally forward /page to /page.php
RewriteRule ^(page)/?$ /$1.php [L,QSA,NC]
# Redirect /page.php?primary-view=value to /page/value
RewriteCond %{THE_REQUEST} \s/+(page)\.php\?primary-view=([^\s]+) [NC]
RewriteRule ^ /%1/%2? [R=302,L]
# Internally forward /page/value to /page.php?primary-view=value
RewriteRule ^(page)/(.*)/?$ /$1.php?primary-view=$2 [L,QSA,NC]

# Redirect /chicago-downtown to /chicago
Redirect 301 /chicago-downtown to /chicago

So the url after the rewrite will look something like
#Original url
example.com/page.php?primary-view=chicago-downtown
#Url rewritten properly
example.com/page/chicago

If I type in example.com/page/chicago then it works fine. If I type in example.com/page/chicago-downtown its currently redirecting to the following:
#Current bad redirect from example.com/page/chicago-downtown
example.com/page/chicago?primary-view=chicago-downtown
#Desired redirect from example.com/page/chicago-downtown
example.com/page/chicago

I have tried man things and came to the conclusion that it is the following line causing the issue with the 301 redirect.
# Internally forward /page/value to /page.php?primary-view=value
RewriteRule ^(page)/(.*)/?$ /$1.php?primary-view=$2 [L,QSA,NC]

Is there some way I can rewrite my rewrite rules, or is there a rewrite condition I need to use to prevent this from happening?

A: This is probably caused because you're mixing mod_alias directives with mod_rewrite directives. That means both directives get applied to the same request in an unwanted way. Remove the Redirect directive (mod_alias) and user a rewrite rule instead. But you need to add the rule before your other rules (i.e. right after RewriteEngine On)
RewriteRule ^chicago-downtown(.*)$ /chicago$1 [L,R=301]

A: You don't need Redirect rule. Just an additional mod_rewrite rule for chicago-downtown => chicago:
RewriteEngine On

RewriteRule ^(page/chicago)-downtown/?$ /$1 [L,R=302,NC]

# Redirect /page.php to /page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(page)\.php [NC]
RewriteRule ^ /%1 [R=302,L]

# Internally forward /page to /page.php
RewriteRule ^(page)/?$ /$1.php [L,QSA,NC]

# Redirect /page.php?primary-view=value to /page/value
RewriteCond %{THE_REQUEST} \s/+(page)\.php\?primary-view=([^\s]+) [NC]
RewriteRule ^ /%1/%2? [R=302,L]

# Internally forward /page/value to /page.php?primary-view=value
RewriteRule ^(page)/(.*)/?$ /$1.php?primary-view=$2 [L,QSA,NC]


text:
Q: Android studio camera2 eliminate noise I am working with camera in android studio and i have YUV420_888 as output from camera2 via ImageReader. Problem is that i got this strange noise, or whatever it is called. Here is link to a picture. If you look close there are 6-7 circles with different shades of gray. I use only Y channel because i need black and white image and Y channel is exactly that. It is big problem because its interfering with the edge detection algorithm and those "circles" are represented as noise in edge detection. Also they only appear when the surface is plane white. Can anyone tell me why this happen and how to fix it?
EDIT:
So i found out that its something about the code. This is original application where i tried to get camera2 working.
package com.example.nikola.camera2project;
import android.hardware.camera2.CaptureResult;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "AndroidCameraApi";
    private TextureView textureView;
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }
    private String cameraId;
    protected CameraDevice cameraDevice;
    protected CameraCaptureSession cameraCaptureSessions;
    protected CaptureRequest.Builder captureRequestBuilder;
    private Size imageDimension;
    private ImageReader imageReader;
    private File file;
    private static final int REQUEST_CAMERA_PERMISSION = 200;

    private Handler mBackgroundHandler;
    private HandlerThread mBackgroundThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        textureView = (TextureView) findViewById(R.id.texture);
        assert textureView != null;
        textureView.setSurfaceTextureListener(textureListener);
        imageReader = ImageReader.newInstance(640, 480, ImageFormat.YUV_420_888, 1);

    }

    TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            //open your camera here
            openCamera();
        }
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            // Transform you image captured size according to the surface width and height
        }
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            return false;
        }
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        }
    };

    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            //This is called when the camera is open
            Log.e(TAG, "onOpened");
            cameraDevice = camera;
            createCameraPreview();

        }
        @Override
        public void onDisconnected(CameraDevice camera) {
            cameraDevice.close();
        }
        @Override
        public void onError(CameraDevice camera, int error) {
            cameraDevice.close();
            cameraDevice = null;
        }
    };
    protected void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("Camera Background");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }
    protected void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    protected void createCameraPreview() {
        try {
            SurfaceTexture texture = textureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
            Surface surface = new Surface(texture);
            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
             captureRequestBuilder.addTarget(surface);
           cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    //The camera is already closed
                    if (null == cameraDevice) {
                        return;
                    }
                    // When the session is ready, we start displaying the preview.
                    cameraCaptureSessions = cameraCaptureSession;
                    updatePreview();
                }
                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
                }
            }, null);

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private void openCamera() {
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        Log.e(TAG, "is camera open");
        try {
            cameraId = manager.getCameraIdList()[0];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            assert map != null;
            imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
            // Add permission for camera and let user grant the permission
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
                return;
            }
            manager.openCamera(cameraId, stateCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "openCamera X");
    }
    protected void updatePreview() {
        if(null == cameraDevice) {
            Log.e(TAG, "updatePreview error, return");
        }
        captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        try {
            cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private void closeCamera() {
        if (null != cameraDevice) {
            cameraDevice.close();
            cameraDevice = null;
        }
        if (null != imageReader) {
            imageReader.close();
            imageReader = null;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // close the app
                Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        startBackgroundThread();
        if (textureView.isAvailable()) {
            openCamera();
        } else {
            textureView.setSurfaceTextureListener(textureListener);
        }
    }
    @Override
    protected void onPause() {
        Log.e(TAG, "onPause");
        //closeCamera();
        stopBackgroundThread();
        super.onPause();
    }

}

Because i needed to do some working around frames this is change i made
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        assert surfaceView != null;
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        mImageReader = ImageReader.newInstance(480,640, ImageFormat.YUV_420_888,10);
}

private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            //This is called when the camera is open
            Log.e(TAG, "onOpened");
            cameraDevice = camera;
            createCameraPreview();
            mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
                @Override
                public void onImageAvailable(ImageReader reader) {
                    Image image =  reader.acquireLatestImage();
                    if(image != null) {
                        ByteBuffer buffer0 = image.getPlanes()[0].getBuffer();
                        byte[] Y = new byte[buffer0.remaining()];
                        buffer0.get(Y);

                        //I do work here but this is for preview grayscale only

                        byte[] Bits = new byte[Y.length * 4]; //That's where the RGBA array goes.

                        for (int i = 0; i < Y.length; i++) {
                            Bits[i * 4] =
                                    Bits[i * 4 + 1] =
                                            Bits[i * 4 + 2] = Y[i];
                            Bits[i * 4 + 3] = -1;//0xff, that's the alpha.
                        }

                        Bitmap bm = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
                        bm.copyPixelsFromBuffer(ByteBuffer.wrap(Bits));
                        Bitmap scaled = Bitmap.createScaledBitmap(bm, (int) (surfaceView.getHeight() * 1.33333), surfaceView.getHeight(), true);
                        Canvas c;
                        c = surfaceHolder.lockCanvas();
                        c.drawBitmap(scaled, 0, 0, null);
                        surfaceHolder.unlockCanvasAndPost(c);
                        image.close();

                    }

                }
            },mBackgroundHandler);

        }

 protected void createCameraPreview() {
        try {

            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

            captureRequestBuilder.addTarget(mImageReader.getSurface());
            cameraDevice.createCaptureSession(Arrays.asList(mImageReader.getSurface()), new CameraCaptureSession.StateCallback(){
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    //The camera is already closed
                    if (null == cameraDevice) {
                        return;
                    }
                    // When the session is ready, we start displaying the preview.
                    cameraCaptureSessions = cameraCaptureSession;
                    updatePreview();
                }
                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
                }
            }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

And the rest is the same. When i display this i get what you can see on picture, but in first program when i directly display YUV420_888 on TextureView like in first program, everything is OK, but when i do this changes i got those noise. Any idea why?
EDIT 2:
Whole code :
package com.example.nikola.camera2project;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.hardware.camera2.CaptureResult;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {

    private static final String TAG = "AndroidCameraApi";
    private TextureView textureView;
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }
    private String cameraId;
    protected CameraDevice cameraDevice;
    protected CameraCaptureSession cameraCaptureSessions;
    protected CaptureRequest.Builder captureRequestBuilder;
    private Size imageDimension;
    private ImageReader imageReader;
    private File file;
    private static final int REQUEST_CAMERA_PERMISSION = 200;

    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    private Handler mBackgroundHandler;
    private HandlerThread mBackgroundThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        assert surfaceView != null;
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        imageReader = ImageReader.newInstance(480,640, ImageFormat.YUV_420_888,10);

    }

    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            //This is called when the camera is open
            Log.e(TAG, "onOpened");
            cameraDevice = camera;
            createCameraPreview();
            imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
                @Override
                public void onImageAvailable(ImageReader reader) {
                    Image image =  reader.acquireLatestImage();
                    if(image != null) {
                        ByteBuffer buffer0 = image.getPlanes()[0].getBuffer();
                        byte[] Y = new byte[buffer0.remaining()];
                        buffer0.get(Y);
                        byte[] Bits = new byte[Y.length * 4]; //That's where the RGBA array goes.
                        for (int i = 0; i < Y.length; i++) {
                            Bits[i * 4] =
                                    Bits[i * 4 + 1] =
                                            Bits[i * 4 + 2] = Y[i];
                            Bits[i * 4 + 3] = -1;//0xff, that's the alpha.
                        }
                        Bitmap bm = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
                        bm.copyPixelsFromBuffer(ByteBuffer.wrap(Bits));
                        Bitmap scaled = Bitmap.createScaledBitmap(bm, (int) (surfaceView.getHeight() * 1.33333), surfaceView.getHeight(), true);
                        Canvas c;
                        c = surfaceHolder.lockCanvas();
                        c.drawBitmap(scaled, 0, 0, null);
                        surfaceHolder.unlockCanvasAndPost(c);
                        image.close();

                    }

                }
            },mBackgroundHandler);

        }
        @Override
        public void onDisconnected(CameraDevice camera) {
            cameraDevice.close();
        }
        @Override
        public void onError(CameraDevice camera, int error) {
            cameraDevice.close();
            cameraDevice = null;
        }
    };
    protected void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("Camera Background");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }
    protected void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    protected void createCameraPreview() {
        try {
            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
             captureRequestBuilder.addTarget(imageReader.getSurface());
           cameraDevice.createCaptureSession(Arrays.asList(imageReader.getSurface()), new CameraCaptureSession.StateCallback(){
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    //The camera is already closed
                    if (null == cameraDevice) {
                        return;
                    }
                    // When the session is ready, we start displaying the preview.
                    cameraCaptureSessions = cameraCaptureSession;
                    updatePreview();
                }
                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
                }
            }, null);

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private void openCamera() {
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        Log.e(TAG, "is camera open");
        try {
            cameraId = manager.getCameraIdList()[0];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            assert map != null;
            imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
            // Add permission for camera and let user grant the permission
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
                return;
            }
            manager.openCamera(cameraId, stateCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "openCamera X");
    }
    protected void updatePreview() {
        if(null == cameraDevice) {
            Log.e(TAG, "updatePreview error, return");
        }
        captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        try {
            cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // close the app
                Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        startBackgroundThread();
    }
    @Override
    protected void onPause() {
        Log.e(TAG, "onPause");
        //closeCamera();
        stopBackgroundThread();
        super.onPause();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        openCamera();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }
}

A: It could be quantization noise due to the hardware limitations of your camera. If a surface is dimly lit, the camera may use automatic brightness adjustment and/or white balance to make the scene more presentable. If the camera does not have an adjustable aperture, adjustable shutter, or high-resolution ADCs, it would do the adjustment digitally, e.g., by multiplying the "Y" value by an integer coefficient (for each pixel). Thus, quantization noise.
You may obtain better results by adjusting the AWB mode. Better lighting may help. Or, you could adjust the thresholds in your edge detection algorithm.
EDIT
Add a call to surfaceHolder.setFormat(PixelFormat.RGBA_8888) immediately after your addCallback() call.
Turns out this was actually a result of the surface's default internal format, which was something smaller than ARGB_8888. Happened on an S6 as well.


text:
Q: How to read/write "/sys/bus/pci/devices/.../resource2" in linux kernel or kernel module? I am a green hand in linux kernel writing. I have two kvm virtual machines in qemu. I add a ivshmem for each, and they can use open and mmap function to read/write  /sys/bus/pci/devices/0000:00:05.0/resource2 to sync memory. Here is a reference: https://liujunming.top/2021/11/30/QEMU-tutorial-Inter-VM-Shared-Memory-device/
# QEMU parameters:
    -object memory-backend-file,size=4M,share=on,mem-path=/dev/shm/shm1,id=shm1 \
    -device ivshmem-plain,memdev=shm1,addr=0x05,master=on

However, I need to sync memory in kernel but not user space. I use linux kernel 5.10.20. There are two functions kernel_read and kernel_write. I can use the two functions to read/write a normal file such as /home/xxx/a.txt, but I cannot read/write /sys/bus/pci/devices/0000:00:05.0/resource2.
Here is my code to read the first character:
char buf_2[1];

void read_file(const char *filename)
{
    ssize_t i;
    struct file *f = NULL;
    loff_t f_pos = 0;

    f = filp_open(filename, O_RDWR, 0);
    if (IS_ERR(f)) {
        pr_err("open file error!\n");
    }

    memset(buf_2, 0, sizeof(buf_2));
    i = kernel_read(f, buf_2, 1, &f_pos);
    pr_info("f: %p, f_pos: %lld, buf_2: %d, i: %ld", f, f_pos, buf_2[0], i);

    filp_close(f, NULL);
}

When I pass /home/xxx/a.txt and /sys/bus/pci/devices/0000:00:05.0/resource2 to the read_file, it prints this:
[   40.154424] f: 00000000cad673bc, f_pos: 1, buf_2: 115, i: 1
[   40.154457] f: 0000000047ddc318, f_pos: 0, buf_2: 0, i: -5

The first result is corrent. But the second is not. And kernel_read returns a error code -5.
How can I read/write /sys/bus/pci/devices/0000:00:05.0/resource2 in linux kernel?
$ ls /sys/bus/pci/devices/0000:00:05.0/
ari_enabled               driver_override  msi_bus    resource2_wc
broken_parity_status      enable           numa_node  revision
class                     firmware_node    power      subsystem
config                    irq              remove     subsystem_device
consistent_dma_mask_bits  link             rescan     subsystem_vendor
d3cold_allowed            local_cpulist    resource   uevent
device                    local_cpus       resource0  vendor
dma_mask_bits             modalias         resource2

$ cat /sys/bus/pci/devices/0000:00:05.0/resource
0x00000000c1031000 0x00000000c10310ff 0x0000000000040200
0x0000000000000000 0x0000000000000000 0x0000000000000000
0x0000001000000000 0x00000010003fffff 0x000000000014220c
0x0000000000000000 0x0000000000000000 0x0000000000000000
0x0000000000000000 0x0000000000000000 0x0000000000000000
0x0000000000000000 0x0000000000000000 0x0000000000000000
0x0000000000000000 0x0000000000000000 0x0000000000000000


text:
Q: Codeigniter dropdown only retrieve last data from db I use CI form with form_dropdown helper and tried to pull Mysql data into its options, from the below code, its only retrieve the last record from db into the option list?
please advise what is wrong with my code?
Model
 public function getStates() {
    $query = $this->db->get('states');
    $return = array();

    if($query->num_rows() > 0){
        $return[''] = 'please select';
        foreach($query->result_array() as $row){
            $return[$row['state_id']] = $row['state_name'];
        }
    }
    return $return;
}

Controller
$this->load->model('db_model');

$data['options'] = $this->db_model->getStates();

$this->load->view('create_new', $data);

View
$state = array(
'name' => 'state',
'id' => 'state',
//'value' => set_value('state', $state)
);

<?php echo form_label('State', $state['id']); ?>
<?php echo form_dropdown($state['name'], $options); ?>
<?php echo form_error($state['name']); ?>
<?php echo isset($errors[$state['name']])?$errors[$state['name']]:''; ?>

A: send full query result from the model to the view like this
Model
 public function getStates() {
    $query = $this->db->get('states');
    return $query->result();
}

let the controller as it is and now you can populate states in dropdown like this:
View
<?php
foreach($options as $opt){
  $options[$opt->state_id]=$opt->state_name;
}
echo form_dropdown($state['name'], $options);
?>

A: Try this:
function getStates() {
    $return = array();
    $query  = $this->db->get('states')->result_array();
    if( is_array( $query ) && count( $query ) > 0 ){
        $return[''] = 'please select';
        foreach($query as $row){
            $return[$row['state_id']] = $row['state_name'];
        }
    }
    return $return;
}


text:
Q: filter must be an instance of dict, bson.son.SON
TypeError("%s must be an instance of dict, bson.son.SON, or "
TypeError: filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping

prev = {"name", "Amy"}
next_ = {"$set": {"address", "Ahmadabad"}}
collection.update_one(prev, next_)

A: A subtle one, but an easy mistake to make; replace the comma (,) with a colon(:)
prev = {"name": "Amy"}
next_ = {"$set": {"address": "Ahmadabad"}}
collection.update_one(prev, next_)

pymongo typically requires dictionary parameters. If you use a comma, that is the syntax for creating a set; perfectly valid in python, but no use in pymongo.


text:
Q: Add exclusion zone on highchart contour charts Is there any chance to add exclusion zone on highcharts.
In this image green marked area is exclusion zone

A: By using Highcharts.SVGRenderer, you can add any shape to the chart:
    events: {
        load: function() {
            this.zone = this.renderer.path(['M', 100, 100, 'L', 150, 150, 'L', 450, 200, 'L', 450, 100, 'z'])
                .attr({
                    stroke: 'red',
                    fill: '#666666',
                    'stroke-width': 2
                })
                .add();

            this.zone.toFront()
        }
    }

Live demo: https://jsfiddle.net/BlackLabel/dfue2ab4/


text:
Q: how to add queues inside container when spring boot application booting up? Currently, I am listening to new queue created through API call by using spring boot and spring-amqp
this is the piece code  which is successfully working
@RestController
@RequestMapping("/api/register/")
@NoArgsConstructor
public class RegisterQueuesController {
    @Autowired
    SimpleReceiver simpleReceiver;

    @PostMapping(value = "/queues")
    public ResponseEntity<String> addAll(final @RequestBody RegisteringQueues registeringQueues) {
        simpleReceiver.processQueueEvents(registeringQueues);
        return new ResponseEntity<>("SUCCESS", HttpStatus.CREATED);
    }
}

@Component
public class SimpleReceiver {

    @Autowired
    private RabbitListenerEndpointRegistry listenerEndpointRegistry;

    @RabbitListener(id = "qEvent")
    public void processQueueEvents(RegisteringQueues registeringQueues) {
        ((DirectMessageListenerContainer) this.listenerEndpointRegistry.getListenerContainer("queueContainer"))
                .addQueueNames(registeringQueues.getQueue());
        // processBeanQueueEvents();
        System.out.println("Received a message with the new queue name: " + registeringQueues.getQueue());

    }

    @RabbitListener(id = "queueContainer")
    public void processMessages(TestQueues testQueues, @Header(AmqpHeaders.CONSUMER_QUEUE) String queue) {
        System.out.println("Received a message on queue: " + queue + "data: " + testQueues);
        //process testQueues
    }

//postman payload
// http://localhost:8080/api/register/queues

    {

        "queue":[
            "queue1",
            "queue2",
            "queue3"
        ]
    }

`

but if application again boots up again I need to register queues inside container (DirectMessageListenerContainer) and add the queue,say queue1 to the listener container id  "queueContainer" when ever application starts.
Am not able to listen the list of queues and add it  to the listner container on bootup.Can you Please help in this regard

A: You need to persist the queue names someplace (e.g. a db, redis etc) and send new messages to the control listener queue during start up.


text:
Q: How can I get a list of my TFS BackLog Items in a Hierarchical format? I am trying to list out all my backlog items, but some backlog items have children backlog items. I would like to list them out this way: BackLogItemParent/BackLogItemChild1/BackLogItemChild2 etc for however many children each parent item has.
I can get all the backlog items:
public WorkItemCollection BackLogItems()
        {
            WorkItemCollection results = this.tfsWorkItemStore.Query(
                "Select [System.Id], [System.Title] " +
                "From WorkItems " +
                "Where [Work Item Type] = 'Product BackLog Item' " +
                "And [System.Title] <> '<unused>' " +
                "Order By [System.Title] Asc"
                );

            return results;
        }

and potentially doing something like:
 private WorkItem GetChildBackLogItems(WorkItem wi)
        {
            foreach (WorkItemLink wil in wi.WorkItemLinks)
            {
             //some sort of recursive call to get all links if backlog is a parent
             //but may need to filter out by top parent items first.
            }
            return wi;
        }

But am having trouble creating a list in the way I would like as I have not quite got a good grasp on how the linking is denoted in the code. I am suspecting that I may need to use the workitemlinks table instead.
In the team explorer there is a "Tree of Work Items" query type that lists these items in a hierarchical fashion, I guess I am trying to do something similar just a bit more flat.
Any help would be appreciated.

A: If you create a Query in Visual Studio that has what you want you can use "Save as..." To save it to the desktop. This would be a "Hierarchy" query.
You can then get the entire list of workitens as a flat list by passing the query to WorkItemStore.Query().
After that you can iterate and build your tree in code.

A: I based my code on Colin's solution. At the core you need to call Query.RunLinkQuery and then WorkItemStore.GetWorkItem to pull down your work items.


text:
Q: A generalization for Binomial Theorem, Leibniz General Rule other like functions. $n$ & $m :=$ any value in $\{0,1,2\ldots\}$
$\Omega$ & $\beta :=$ any value in $\{1,2,3\ldots\}$
[1] If there is a function $F_\beta$ such that for some value $\Omega$ and some function $T_{n,m}$ that $\text{if } F_1(\sum_{i=0}^{\Omega}T_{i,\Omega-i}) = T_{1,0}+T_{0,1}
\text{ and }
\\F_2(\sum_{i=0}^{\Omega}T_{i,(\Omega-i)}) = T_{2,0}+2T_{1,1}+T_{0,2}\text{ and }
\\F_3(\sum_{i=0}^{\Omega}T_{i,(\Omega-i)})=T_{3,0}+3T_{2,1}+3T_{1,2}+T_{0,3}\text{ and }\\ \ldots\\\text{then }F_\beta(\sum_{i=0}^{\Omega}T_{i,(\Omega-i)})=\sum_{i=0}^\beta\binom{\beta}{i}T_{i,(\beta-i)}$
[2] if $\phi_i$ represents a variation of some function for every value i. $F_\beta(\sum_{i=0}^{k}\phi_i)=\sum_{i=0}^{k}F_\beta(\phi_i)$ AND $F_1(T_{n,m})=T_{n+1,m}+T_{n,m+1}$
$$:.F_\beta(T_{n,m})=\sum_{i=0}^\beta\binom{\beta}{i}T_{(n+i),(m+\beta-i)}$$
example of [1]
If $T_{n,m}:=a^n*e^m$ and $F_\beta(T_{1,0}+T_{0,1})=F_\beta(\sum_{i=0}^{1}T_{i,(i-1)}):=(a+e)^{\beta}$
$F_1(\sum_{i=0}^{1}T_{i,(i-1)})\\=(a^{1}+e^{1})^{1}=a^{1}e^{0}+a^{0}e^{1}=T_{1,0}+T_{0,1}$
$F_2(\sum_{i=0}^{1}T_{i,(i-1)})\\=(a^{1}+e^{1})^{2}=a^{2}e^{0}+2a^{1}e^{1}+a^{0}e^{2}=T_{1,0}+2T_{1,1}+T_{0,2}$
$F_3(\sum_{i=0}^{1}T_{i,(i-1)})=(a^{1}+e^{1})^{3}\\=a^{3}e^{0}+3a^{2}e^{1}+3a^{1}e^{2}+a^{0}e^{3}=T_{3,0}+3T_{2,1}+3T_{1,2}+T_{0,3}\\\ldots$
$:.F_\beta(\sum_{i=0}^{1}T_{i,(i-1)})=(a+e)^{\beta}
\\=\sum_{i=0}^\beta\binom{\beta}{i}a^{i}*e^{\beta-i}=\sum_{i=0}^\beta\binom{\beta}{i}T_{i,(\beta-i)}$
example of [2]
If $T_{n,m}=u^{(n)}v^{(m)}$ and $F_\beta(G):=\frac{d^\beta}{(dx)^\beta}(G)$
$F_1(T_{n,m})=\frac{d}{dx}(u^{(n)}v^{(m)})
\\=u^{(n+1)}v^{(m)}+u^{(n)}v^{(m+1)}=T_{(n+1),m}+T_{n,(m+1)}$
$:.F_\beta(T_{n,m})=\frac{d^\beta}{(dx)^\beta}(u^{(n)}v^{(m)})
\\=\sum_{i=0}^\beta\binom{\beta}{i}u^{(n+i)}v^{(m+\beta-i)}=\sum_{i=0}^\beta\binom{\beta}{i}T_{(n+i),(m+\beta-i)}$
What are these distinct properties called? for when $F_\beta(\sum_{i=0}^{\Omega}T_{i,(\Omega-i)})=\sum_{i=0}^\beta\binom{\beta}{i}T_{i,(\beta-i)}$ or $F_\beta(T_{n,m})=\sum_{i=0}^\beta\binom{\beta}{i}T_{(n+i),(m+\beta-i)}$.
Edit:
I found that $F_\beta(T_{n,m})=\sum_{i=0}^\beta\binom{\beta}{i}T_{(n+i),(m+\beta-i)}$ is shown in for n=0, m=0.

Abstract binomial theorem. Assume that we have:

*

*A vector space (or even a module) $V$.

*A family of "general terms" $(T_{i,j}\in V)_{i,j\in\mathbb N}$.

*A linear operatior $F: V\to V$, such that $F(T_{i,j}) = T_{(i+1),j} + T_{i,(j+1)}$.

  Then $F^n(T_{0,0}) = \sum_{i=0}^n \binom{n}{i} T_{i,(n-i)}$.


text:
Q: Using python logging in reusable Django application: "No handlers could be found for logger" In an open-source Django library I am working on, the logging module is used mainly to notice user for potential errors:
import logging

logger = logging.getLogger(__name__)

def my_wonderful_function():
    # ... some code ...
    if problem_detected:
        logger.error('Please pay attention, something is wrong...')

Since this approach works fine most of the time, if Python 2 users doesn't configure the logging system for my package, they get the error:

No handlers could be found for logger "library.module"

as soon as the logger is used.
This error does not print out to Python 3 user, since there is a fallback mechanism to output messages to a default StreamHandler when no handler can be found for a specific logger (See the code).
My question is:
Is there a good way to report errors and warnings to user, but to print nothing (and in particular no error) when the user don't want to configure logging?

A: I finally found a solution that works well. I added these 2 functiond in my code:
def logger_has_handlers(logger):
    """Since Python 2 doesn't provide Logger.hasHandlers(), we have to
    perform the lookup by ourself."""

    if six.PY3:
        return logger.hasHandlers()
    else:
        c = logger
        rv = False
        while c:
            if c.handlers:
                rv = True
                break
            if not c.propagate:
                break
            else:
                c = c.parent
        return rv

def get_default_logger(name):
    """Get a logger from default logging manager. If no handler
    is associated, add a default NullHandler"""

    logger = logging.getLogger(name)
    if not logger_has_handlers(logger):
        # If logging is not configured in the current project, configure
        # this logger to discard all logs messages. This will prevent
        # the 'No handlers could be found for logger XXX' error on Python 2,
        # and avoid redirecting errors to the default 'lastResort'
        # StreamHandler on Python 3
        logger.addHandler(logging.NullHandler())
    return logger

Then, when I need a logger, instead of calling logging.getLogger(__name__), I use get_default_logger(__name__). With this solution, the returned logger always contains at least 1 handler.
If user configured logging by himself, the returned logger contains references to defined handlers. If user didn't configure logging for the package (or configured it without any handler), the NullHandler instance associated with the logger ensure no error will be printed when it is used.


text:
Q: Reading from configuration file within WCF web service I'm trying to read from Constants.config file within not ASP.NET enabled WCF web service.
Configuration rootWebConfig1 = Configuration.WebConfigurationManager.OpenWebConfiguration("Constants.config");

This call threw an exception, and it's seems like that OpenWebConfiguration tries open the config file in some different location. How can I know where it looks for and how can I specify the target folder?
Thanks a lot.
Ilan.

A: OpenWebConfiguration is intended to open a web configuration file - e.g. a web.config only...
You can't use it to open your own config files, as far a I know.
You can however use the regular Configuration class from the .NET System.Configuration namespace. Check out Jon Rista's three-part series on .NET 2.0 configuration up on CodeProject:

*

*Part 1: Unraveling the mysteries of .NET 2.0 configuration

*Part 2: Decoding the mysteries of .NET 2.0 configuration

*Part 3: Cracking the mysteries of .NET 2.0 configuration
Highly recommended, well written and extremely helpful!
In part 3, Jon shows how you can use your own custom config files and open them with the help of the ExeConfigurationFileMap class:
ExeConfigurationFileMap exeMap = new ExeConfigurationFileMap();
exeMap.ExeConfigFilename = "C:\Application\Constants.config";

Configuration exeConfig =
  ConfigurationManager.OpenMappedExeConfiguration(exeMap, ConfigurationUserLevel.None);

A: You can either do what marc_s said and use the Configuration (depreciated) or ConfigurationManager, or if you want you WCF service to support ASP.NET features you can turn on ASP.NET Compatability by decorating your service implementation with an AspNetCompatibilityRequirementsAttribute.
If the service will be tied to an ASP.NET site, always hosted in IIS, and would be making use of the ASP.NET session, this is probably the way to go. If not use the ConfigurationManager class.


text:
Q: Flume... How to configure source and sink in different VMs? I wish to configure the avro SOurce in VM1 and Sink in VM2.
The Source should be able to connect to the channels in VM2 and channels will send data to sink in VM2. How should I proceed to configure this?
Please help.


text:
Q: Combining multiple data frames from yahoo finance with loop need help to loop over data from yfinance.
I have a list of tickers that like to combine the recommendation data from yfinance but I do not how to loop it.
This is how I have done it for 3 tickers but obviously, I need help to understand how to loop it to run large data.
import pandas as pd
import yfinance as yf
import datetime
from dateutil.relativedelta import relativedelta
to use this to filter out recent 6 months data
df.index = pd.to_datetime(df.index)
today = datetime.date.today()
six_months = today + relativedelta(months=-6)
df_msft = yf.Ticker('MSFT').recommendations[six_months:today]
df_aapl = yf.Ticker('AAPL').recommendations[six_months:today]
df_googl =yf.Ticker('GOOGL').recommendations[six_months:today]
df_msft['Stock'] = ['msft']*df_msft['To Grade'].count()
df_aapl['Stock'] = ['aapl']*df_aapl['To Grade'].count()
df_googl['Stock'] = ['googl']*df_googl['To Grade'].count()
Combine data, but need to know how to use loop instead assuming that I have 500 tickers in a list
pd.concat([df_msft, df_aapl, df_googl])

A: Found a way to do this.
`appended_data =[]`

for ticker in small_list:
table2 = yf.Ticker(ticker).recommendations[six_months:today]
table2['Ticker'] = [ticker]*table2['To Grade'].count()
appended_data.append(table2)
appended_data = pd.concat(appended_data)


text:
Q: Internet Explorer not rendering the leading text in a custom list item This is a follow-up to How to create a custom list style with a dash.
Specifically, my question concerns Internet Explorer 9. (Refer to my sample XHTML document at the end of this question. My sample document includes inline CSS.)
When I view my sample XHTML document as a local file, I see the expected result in IE9:
Here is a list:
- One
- Two
- Three

However, when I view this same XHTML document via IIS, I see something different in IE9:
Here is a list:
  One
  Two
  Three

That is, IE9 is not rendering the dash that is intended to appear at the beginning of each list item.
(Note that Firefox 31 does render the dash when the file is viewed locally as well as via IIS.)
Could this problem be related to the HTTP headers being returned by IIS? Here are the key headers that my instance of IIS is returning:
200 OK
Date: Tue, 09 Sep 2014 18:41:34 GMT
Server: Microsoft-IIS/7.5
Content-Length: 706
Content-Type: text/html
Title: Custom List Item Test
X-Powered-By: ASP.NET

Sample XHTML document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Custom List Item Test</title>

Here is a list:

One

Two

Three

A: @Mr Lister, your comment pointed me to a solution.
I found that my IE9 Compatibility View settings were as follows:
[x] Include updated website lists from Microsoft
[x] Display intranet sites in Compatibility View
[ ] Display all websites in Compatibility View

My web page of interest is being served by IIS on a server that is a member of my intranet. And because the second check box was checked, IE9 rendered the page using Compatibility View settings. After clearing the second check box, the dashes that introduce each list item became visible.
With the settings that I show above, IE9 initially did display the list item dashes when I viewed the document from my local disk. However, when I checked the third check box, the dashes disappeared from the list.
So, that explains the different results that I observed when viewing the document locally vs. viewing it via IIS.


text:
Q: Version control of users' metadata I've got a question that most likely doesn't have a unique and clear answer.
In the team we are using the SVN, many of the people are using the git-svn (treating it as a fancy SVN client).
We're storing some project related publications, reports, documents in the repository under let's say trunk/Documents/*. Each of the users creates his own notes, annotations, etc. related to a given document - let's say trunk/Documents/doc1.txt. Thus in the end we've got N users having doc1.txt.metadata.
What are your recommendations for storing this metadata? Branches for each user metadata?

A: As the files are going to differ by user, the cleanest way I can think of is keeping text files like doc1.txt.metadata.username. Keeping separate branches per user metafile sounds complicated to me, and hard to work with in everyday use.
There would be be the idea of automating this using a pre- and/or post-commit hook, but it is discouraged in the SVN book:

While hook scripts can do almost anything, there is one dimension in which hook script authors should show restraint: do not  modify a commit transaction using hook scripts. ... Instead of modifying the transaction, you should simply validate the transaction in the pre-commit hook and reject the commit if it does not meet the desired requirements. As a bonus, your users will learn the value of careful, compliance-minded work habits.

The simplest thing might be to establish doc1.txt.metadata.username as a rule, and to write a pre-commit script that rejects any commits of .metadata files without the current user name as the extension.


text:
Q: Odd error in SPSS regression when using dummy variables I'm entering 15 dummy variables into a regression analysis to control for the 'effect of experiment'.  There are 16 experiments in total, so 15 should be entered.  So I have 16 columns, with a 1 for each participant from experiment 1 in the column "1_dum", and a 1 for each from participant from experiment 2 in the column "2_dum", and so on.
When I run the analysis, I get the following error message, and am not sure why:  column of experiment 1 correspond "For models with dependent variable XXXX, the following variables are constants or have missing correlations: 7 _dum, 9 _dum, 11 _dum, 12 _dum, 14 _dum. They will be deleted from the analysis."
I've never seen an error like this before and have ran analyses with dummy variables in this fashion several times. There aren't any missing values in these variables, so I'm not sure why this error is showing up.  Does anyone have any insight into this?
Many thanks in advance!

A: Those are not legal variable names (because they start with numbers).  Assuming the actual names are different, what are you entering for the values for each dummy that is not 1?  What do you see if  you run Descriptives on the whole set?


text:
Q: Generic WS client for Weblogic I am running an application on Jboss 7 and Weblogic 12 , when I make a soap call on weblogic is more restrictive than jboss. My client interface has to implements all the methods of the wsdl and the annotation for the method and parameters and return type have to be exactly the same. Jboss is more permissive.
Is there a way to implement a simple generic client for a soap call without have to implements all the methods of the wsdl running on Weblogic? Just with the method i need?
In my specific case I'm implementing a simple client to make a call to only a method of the ws (where the return type is void cos I don't need/want to implement the structure of the returning object and my interface is not implementing all methods of the wsdl), under weblogic I'm getting the following error:

com.sun.xml.ws.api.wsdl.parser.WSDLParserExtensionContext.getWSDLModel()Lcom/sun/xml/ws/api/model/wsdl/editable/EditableWSDLModel;
  java.lang.NoSuchMethodError:
  com.sun.xml.ws.api.wsdl.parser.WSDLParserExtensionContext.getWSDLModel()Lcom/sun/xml/ws/api/model/wsdl/editable/EditableWSDLModel;
          at weblogic.wsee.jaxws.framework.policy.WSDLParserExtension.definitionsElements(WSDLParserExtension.java:541)

A: I resolved using SAAJ
I followed this example http://www.concretepage.com/webservices/java-saaj-web-service-example
But in my pom I had to change javaee-api version from 6.0 to 7.0
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
 </dependency>

I tried to follow this suggestion
Maven tests troubles with SOAP having Java EE 6 dependency
but the solution doesn't work for me


text:
Q: Docker multi-stage builds with images that doesn't coexist I am trying o understand Docker multi-stage builds. I have Docker toolbox 18.03 so I am able to run them. My first attempt after looking at the docs was to build an image with Python 3.7 and Php-apache. So I wrote this Dockerfile:
FROM python:3.7.0-stretch

FROM php:7-apache-stretch

RUN docker-php-ext-install mbstring mysqli pdo pdo_mysql
RUN a2enmod rewrite

# Enable SSL
RUN a2enmod ssl
RUN mkdir /etc/apache2/ssl
ADD server.crt /etc/apache2/ssl/
ADD server.key /etc/apache2/ssl/
ADD default-ssl.conf /etc/apache2/sites-available/
RUN a2ensite default-ssl
EXPOSE 443

RUN echo 'log_errors = On' >> /usr/local/etc/php/php.ini

Then I run docker build . and it built it successfully:
Sending build context to Docker daemon  12.29kB
Step 1/12 : FROM python:3.7.0-stretch
 ---> 825141134528
Step 2/12 : FROM php:7-apache-stretch
 ---> 5e5a59788e34
Step 3/12 : RUN docker-php-ext-install mbstring mysqli pdo pdo_mysql
 ---> Using cache
 ---> bf6b095ac6d3
Step 4/12 : RUN a2enmod rewrite
 ---> Using cache
 ---> d3443d0e8d97
Step 5/12 : RUN a2enmod ssl
 ---> Running in edd0a15406db
Considering dependency setenvif for ssl:
Module setenvif already enabled
Considering dependency mime for ssl:
Module mime already enabled
Considering dependency socache_shmcb for ssl:
Enabling module socache_shmcb.
Enabling module ssl.
See /usr/share/doc/apache2/README.Debian.gz on how to configure SSL and create self-signed certificates.
To activate the new configuration, you need to run:
  service apache2 restart
Removing intermediate container edd0a15406db
 ---> a301c3a3ca78
Step 6/12 : RUN mkdir /etc/apache2/ssl
 ---> Running in 59621555d753
Removing intermediate container 59621555d753
 ---> db74733784c3
Step 7/12 : ADD server.crt /etc/apache2/ssl/
 ---> db3715192748
Step 8/12 : ADD server.key /etc/apache2/ssl/
 ---> f6206d6b2d5e
Step 9/12 : ADD default-ssl.conf /etc/apache2/sites-available/
 ---> 0fa5dd62c854
Step 10/12 : RUN a2ensite default-ssl
 ---> Running in 7ab353bca552
Enabling site default-ssl.
To activate the new configuration, you need to run:
  service apache2 reload
Removing intermediate container 7ab353bca552
 ---> 53336ee4133d
Step 11/12 : EXPOSE 443
 ---> Running in 0530749e96b3
Removing intermediate container 0530749e96b3
 ---> 53b56723dd81
Step 12/12 : RUN echo 'log_errors = On' >> /usr/local/etc/php/php.ini
 ---> Running in 8bd7c50715c3
Removing intermediate container 8bd7c50715c3
 ---> d456abb9ee67
Successfully built d456abb9ee67

Then I created the container for it and run. It started and remained up, so I tried to enter into the bash of the container and there is the surprise, php and apache work fine, python doesn't even exist. What am I missing in the Dockerfile?

A: The last image in multistage build is the target image. In order to combine contents, you need to use copy --from original to target image.
It would be easier and safer installing python on the target image than copying it from the first one (without using multistage build)
Normally multistage builds are used for creating prod ready images, without compile time dependencies (compile on first image, copy executables to the target Image)

A: I took Different example , it might help you to understand multistage Dockerfile
Requirement :- java code should be built using mvn and then deploy .war file to tomcat
Dockerfile
FROM maven as maven
RUN mkdir /usr/src/mymaven
WORKDIR /usr/src/mymaven
COPY . .
RUN mvn install -DskipTests

FROM tomcat
WORKDIR webapps
COPY --from=maven /usr/src/mymaven/target/java-tomcat-maven-example.war .
RUN rm -rf ROOT && mv java-tomcat-maven-example.war ROOT.war

in the above Dockerfile i am copying my java code from local to maven image and then building the mvn project using "mvn install -DskipTests" after that in second stage (Tomcat) copying .war file generated previous image to tomcat image.
so by this I was able to reduce my image size.
if i wouldn't use multistage then I need to take jdk or ubuntu image then on top that need to install maven and tomcat , then the image size would have been doubled.
for simple hello world web java project you can refer https://github.com/DeekshithSN/Java_app
Hope it helps you


text:
Q: Regex to detect consecutive lower and uppercase I have character vectors similar to this one:
test <- "ThisisAtest"

I would like to insert a ; between lowercase and uppercase characters, so that the expected output is:
"Thisis;Atest"

To do so, I need to detect the consecutive lowercase and uppercase characters. I tried to do this (I used str_remove instead str_replace because I don't know the first pattern yet):
stringr::str_remove(test, "^[a-zA-Z]*$")

but it returns an empty character vector. Does anyone know how to do this?
I don't know if there are differences between the regex used by gsub() or stringr::str_* functions but I would prefer the latter.

A: You could also find the position between a lowercase char and an uppercase char using gsub and positive lookarounds without the anchors ^ and $
test <- "ThisisAtest"
gsub("(?<=[a-z])(?=[A-Z])", ";", test, perl=T)

See an R demo
Output
[1] "Thisis;Atest"

A: One more fully Unicode-aware option is
stringr::str_replace_all(test, '(?<=\\p{Ll})(?=\\p{Lu})', ';')

Explanation
--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    \\p{Ll}                Lowercase Unicode letter
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    \\p{Lu}                Uppercase Unicode letter
--------------------------------------------------------------------------------
  )                        end of look-ahead

A: We can use two capture groups here, one with lower case letter and another one which is immediately followed by upper case and put a semicolon in between.
Note that I have changed the string to include two occurrences of the pattern.
test <- "ThisisAtestAnew"

gsub('([a-z])([A-Z])', '\\1;\\2', test)
[1] "Thisis;Atest;Anew"

This is similar to using str_replace_all in stringr :
stringr::str_replace_all(test, '([a-z])([A-Z])', '\\1;\\2')

A: Another take: Upper case letter followed for characters until another upper character, we are adding a ';' between two groups.
> test <- "ThisisAtest"
> gsub('([A-Z].*)([A-Z].*)','\\1;\\2',test)
[1] "Thisis;Atest"
>


text:
Q: StandardAnalyzer, BackSlash and Lucene.net I'm using Lucene.Net 2.9.2.I use StandardAnalyzer with customized stop words list that just including english stop words.My data includes folder path like"questions\text\testing data". It's ok when indexing and searching for that folder path. However, I'm using QueryPaser and make query using with Standard Analyzer with the same in indexing. The query parser strips out backslash and change lower case. So I used escape character '\',it does not work.The following are my testing code.
QueryParser queryParser=new QueryParser("",new StandardAnalyzer(STOP_WORDS));
Query query=queryParser.Parse("+Field1:questions\text\testing data +(Field2:good)");
The query syntax change "+Field1:"questionstexttesting" data+(Field2:good".
folder path=questions\text\testing data
search text =good
In my application,I could not know which fields will come to search. Firstly, I search that a word and save the search with lucene query syntax. Later I reuse the search and pass with QueryParser. Thank in advance for any advice!

A: Index your paths using KeywordAnalyzer, and your data using StandardAnalyzer. You can do this using the PerFieldAnalyzerWrapper.
Build your search query using a BooleanQuery, add a PrefixQuery for your path, and use QueryParser for the user provided search string.
var query = new BooleanQuery();
query.Add(new PrefixQuery("Path", "questions\\text\\testing\\"), BooleanClause.Occur.MUST);

var analyzer = new StandardAnalyzer(STOP_WORDS);
var queryParser = new QueryParser("Data", analyzer);
var parsedQuery = queryParser.Parse("data +Field2:good");
query.Add(parsedQuery, BooleanClause.Occur.MUST);

Change your search interface so that the user never needs to manually input paths.


text:
Q: Timer cannot restart after it is being stopped in Python I am using Python 2.7. I have a timer that keeps repeating a timer callback action until it has been stopped. It uses a Timer object. The problem is that after it has been stopped, it cannot be restarted. The Timer object code is as follows;
from threading import Timer

class RepeatingTimer(object):
    def __init__(self,interval, function, *args, **kwargs):
        super(RepeatingTimer, self).__init__()
        self.args = args
        self.kwargs = kwargs
        self.function = function
        self.interval = interval

    def start(self):
        self.callback()

    def stop(self):
        self.interval = False

    def callback(self):
        if self.interval:
            self.function(*self.args, **self.kwargs)
            Timer(self.interval, self.callback, ).start()

To start the timer, the code below is run;
repeat_timer = RepeatingTimer(interval_timer_sec, timer_function, arg1, arg2)
repeat_timer.start()

To stop the timer, the code is;
repeat_timer.stop()

After it is stopped, I tried to restart the timer by calling repeat_timer.start() but the timer is unable to start. How can the timer be made to restart after it has been stopped?
Thank you.

A: The reason your timer is not restarting is because you never reset self.interval to True before trying to restart the timer.  However, if that's the only change you make, you will find your timer is vulnerable to a race condition that will result in more than one timer running concurrently.

A: Here is a corrected version:
from __future__ import print_function

from threading import Timer

def hello():
    print("Hello World!")

class RepeatingTimer(object):

    def __init__(self, interval, f, *args, **kwargs):
        self.interval = interval
        self.f = f
        self.args = args
        self.kwargs = kwargs

        self.timer = None

    def callback(self):
        self.f(*self.args, **self.kwargs)
        self.start()

    def cancel(self):
        self.timer.cancel()

    def start(self):
        self.timer = Timer(self.interval, self.callback)
        self.timer.start()

t = RepeatingTimer(3, hello)
t.start()

Example Run:
$ python -i foo.py
>>> Hello World!

>>> Hello World!

>>> t.cancel()


text:
Q: How to add textsize for toolbar in the androidManifest inside an Activity? Toolbar title size decreases when screen is change to landscape screen, for that I want to add a textsize in the AndroidManifest Activity. This is my code
<activity android:name=".Transportation"
            android:label="Transportation">
            <intent-filter>
                <action android:name="android.intent.action.TRANSPORTATION" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".Transportation">
            </meta-data>
        </activity>

A: you can not change the toolbar text size in the manifest. you will need to add a style to the toolbar in the activity xml file.
check out this: change toolbar text size


text:
Q: Apache virtualhost permission denied with several different DocumentRoots tried. What should I try next? I have a self compiled version of Apache 2 running under Mac OS X Leopard. It's a default install at /usr/local/apache2 and work fine.
Today I wanted to add a virtual host so I could access a particular folder with the domain name http://binarytales.local
So I added 127.0.0.1 binarytales.local to /etc/hosts, fluch the dns cache and, yey, I could access my server via that address.
I wanted to be able to access, via my newly created local domain name, a subfolder in in my working web server. So I set up the following vhosts file
NameVirtualHost *:80

<VirtualHost *:80>
    DocumentRoot /usr/local/apache2/htdocs
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /usr/local/apache2/htdocs/ProjectX
    ServerName binarytales.local
</VirtualHost>

Browsing to localhost works fine, I get the files I always used to get. Browsing to binarytales.local gives me an internal server error.
I did a bit of investgating and discovered that I had set htdocs to be a symlink to /Users/me/Sites so I tried setting my vhost to
<VirtualHost *:80>
    DocumentRoot /Users/me/Sites/ProjectX
    ServerName binarytales.local
</VirtualHost>

This didn't work either. Now I'm getting Forbidden You don't have permission to access / on this server.
So I tried DocumentRoot /Users/me/Sites and got the same forbidden message.
Finally I have tried

        DocumentRoot /usr/local/apache2/htdocs2
        ServerName binarytales.local

Where /usr/local/apache2/htdocs2 is a symlink to Users/me/Sites/ProjectX. And I also tried it with Users/me/Sites. I'm getting the same "Forbidden" error.
I have checked the user and group settings on everything is root/wheel apart from the stuff in `Users/me/Sites/' which is me/wheel. All the directors are chmod -x for everyone.
I'm totally stuck and don't have a clue what to try next!

My question title is crap. Please do change it to/suggest something better.

A: Okay, so I fixed this about 5 mins later by putting this
<Directory "/usr/local/apache2/htdocs/Binarytales">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

inside my virtualhost declaration. so in the end it read as thus:
NameVirtualHost *:80
<VirtualHost *:80>
    DocumentRoot /usr/local/apache2/htdocs
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /usr/local/apache2/htdocs/Binarytales
    ServerName binarytales.local

    <Directory "/usr/local/apache2/htdocs/Binarytales">
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

I think the magic juice here is Options ... FollowSymLinks but it anyone has a good explanation as to why this works then please let me know, or if there is a better/alternative solutions.

A: I would have tried a bind mount first. Presuming it works on Mac OS X like it does on Linux:
mount --bind /path/one /path/two


text:
Q: Problem nesting boost::lambda::bind-s I have a generic function:
void ImageAlbum::ExpressButtonPressed(
    boost::function<
        void (
            thumb::PhotoPrintThumbnail*,
            thumb::PhotoPrintFormat,
            thumb::PhotoPrintQuantity
        )
    > memberToCall
) {
    ...

    BOOST_FOREACH(thumb::PhotoPrintThumbnail *pThumbnail, m_thumbs.GetSelected()) {
    memberToCall(
            pThumbnail,
            m_expressSel.GetSelectedFormat(),
            m_expressSel.GetSelectedQuantity()
        );
    }

    ...
}

I can successfully call:
ExpressButtonPressed(boost::bind(&thumb::PhotoPrintThumbnail::AddQuantity, _1, _2, _3));

Then, instead of adding a quantity of a certain format to a thumbnail, I need to replace them all with a single format. More precise, with a list of 1 element, like that:
ExpressButtonPressed(
    boost::lambda::bind(
        &thumb::PhotoPrintThumbnail::SetFormats,
        _1,
        boost::lambda::bind(
            boost::lambda::constructor<thumb::PhotoPrintThumbnail::LoadedFormats>(),
            1,
            boost::lambda::bind(
                boost::lambda::constructor<thumb::PhotoPrintThumbnail::LoadedFormat>(),
                _2,
                _3
            )
        )
    )
);

Which results in "boost/lambda/detail/actions.hpp(96) : error C2665: 'boost::lambda::function_adaptor::apply' : none of the 2 overloads could convert all the argument types".
What am I doing wrong here?
BTW
class PhotoPrintThumbnail {
public:
...
    typedef std::pair<PhotoPrintFormat, PhotoPrintQuantity> LoadedFormat;
    typedef std::list<LoadedFormat> LoadedFormats;
    void SetFormats(const LoadedFormats &formats);

A: Do you happen to #include boost/bind.hpp in your lambda-using code? This would cause unqualified use of the placeholders (_1, _2, etc) to resolve to those defined by Boost.Bind, and these don't mix well with Boost.Lambda.
Rewriting your code to explicitly use boost::lambda::_[1,2,3] instead of the unqualified names compiles fine on my VC 7.1 setup.

A: Not sure what version of Boost or what compiler are you using. With boost 1.37 and VS2005 i can get the same error. I suspect it may be that an error at the heart of the template expansion is causing a SFINAE issue.
For instance taking the innermost expression out:
boost::function<
    PhotoPrintThumbnail::LoadedFormat (
            PhotoPrintFormat,
            PhotoPrintQuantity
    )
> func = boost::lambda::bind
                ( boost::lambda::constructor<PhotoPrintThumbnail::LoadedFormat>()
                , _1
                , _2
                );

That looks ok to me yet also fails, albeit with a :
std::pair<_Ty1,_Ty2>::pair' : none of the 3 overloads could convert all the argument types
error.
Of course you could just use:
void func
( PhotoPrintThumbnail* ppt
, const PhotoPrintFormat& ppf
, const PhotoPrintQuantity& ppq
)
{
    ppt->SetFormats (PhotoPrintThumbnail::LoadedFormats (1, PhotoPrintThumbnail::LoadedFormat (ppf, ppq)));
}

ExpressButtonPressed (func);

which is clearer and compiles.

A: I think at the first bind, you should bind the constructed object (resulted from the second bind) as first parameter of the method (it should be the address of the constructed object):
ExpressButtonPressed(
    boost::lambda::bind(
        &thumb::PhotoPrintThumbnail::SetFormats,
        boost::lambda::bind(
                boost::lambda::constructor<thumb::PhotoPrintThumbnail::LoadedFormats>(),
                1,
                boost::lambda::bind(
                        boost::lambda::constructor<thumb::PhotoPrintThumbnail::LoadedFormat>(),
                        _2,
                        _3
                )
        ),
        _1
    )
);

I didn't try to compile the code. One other possible issue is that the second bind functor might return the constructed object by value, and the first bind requires a pointer to object (as this pointer), so you still need a pointer as first bound parameter for SetFormats.


text:
Q: Check Two DataGridViews if both of them are equal or not in c# windows form I have two datagridviews. I want to check if both of them are same or not, the columns are always the same. I just want to check if the rows are same or not.

A: There may be better ways, but ...
    public Form1()
    {
        InitializeComponent();

        dgv1.Columns.Add(new DataGridViewTextBoxColumn());
        dgv1.Columns.Add(new DataGridViewTextBoxColumn());
        dgv1.Columns.Add(new DataGridViewTextBoxColumn());

        dgv1.Rows.Add(1, 2, 3);
        dgv1.Rows.Add(4, 5, 6);

        dgv2.Columns.Add(new DataGridViewTextBoxColumn());
        dgv2.Columns.Add(new DataGridViewTextBoxColumn());
        dgv2.Columns.Add(new DataGridViewTextBoxColumn());

        dgv2.Rows.Add(1, 2, 3);
        dgv2.Rows.Add(4, 5, 6);

        var ar1 = string.Join(",", (from row in dgv1.Rows.OfType<DataGridViewRow>()
                                    from cell in row.Cells.OfType<DataGridViewCell>()
                                    select cell.Value));

        var ar2 = string.Join(",", (from row in dgv2.Rows.OfType<DataGridViewRow>()
                                    from cell in row.Cells.OfType<DataGridViewCell>()
                                    select cell.Value));

        Debug.Print((ar1.Equals(ar2)).ToString());

    }


text:
Q: Creating a Dynamic ojTable Using OJET I have a JSON data with n number of rows and n number of columns. I need to create a table out of it to display the results with pagination.Is there a possibility to create a  ojtable with dynamic number of rows and columns from JSON?

A: The rows will be handled for you by the component based on the number of rows of data in the JSON file.  If you want to limit the number of rows shown at the start, then set the The columns option for the ojTable can be passed an object which would dynamically set the columns that should be displayed.
Something like this:
<table data-bind="ojComponent: {component: 'ojTable',
        data: pagingDatasource,
        columns: dynamicCols}">
</table>

self.getCols = function () {
  var url = getUrl();
  $.getJSON(url).then(function (data) {
    var tempCols = [];
    for (var property in data.items[0]) {
      if (data.items[0].hasOwnProperty(property)) {
        tempCols.push({headerText: property, field: property});
      }
    }
    self.dynamicCols(tempCols);
    self.pagingDatasource(new oj.PagingTableDataSource(new oj.ArrayTableDataSource(data.items, {idAttribute: 'empno'})));
}

Here is a jsFiddle that shows how to do it.  You can (un)comment between the two URL's to see the different generated tables based on the JSON being returned by the REST endpoints. https://jsfiddle.net/peppertech/mdp0xjh3/