text:
Q: How to resize Yuv image on android please tell me how can I resize yuv image on android.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mCameraView.myuvImage.compressToJpeg(new Rect(0, 0, mCameraView.myuvImage.getWidth(), mCameraView.myuvImage.getHeight()), 100, baos);

compressToJpeg method converts yuv image to jpeg. But doesn't resize converted JPEG by compression number when I write
mCameraView.myuvImage.compressToJpeg(new Rect(0, 0, mCameraView.myuvImage.getWidth(), mCameraView.myuvImage.getHeight()), 50, baos);

A: The easiest way would be to create a scaled bitmap. First, convert your bitmap to a bitmap image:
ByteArrayOutputStream out = new ByteArrayOutputStream();
YuvImage yuvImage = new YuvImage(mCameraView.myuvImage, PictureFormat.NV21, width, height, null);
yuvImage.compressToJpeg(new Rect(0, 0, width, height), 50, out);
byte[] imageBytes = out.toByteArray();
Bitmap image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);

Then, you can resize with:
Bitmap resized = Bitmap.createScaledBitmap(image, newWidth, newHeight, true);

A: What I've found is probably not a really good approach, but that at least worked for me:
YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null); //create YuvImage instance with initial size
ByteArrayOutputStream bao = new ByteArrayOutputStream();
image.compressToJpeg(new Rect(0, 0, image.getWidth(), image.getHeight()), jpegQuality, bao);

I have aspect value which is set outside. This value represents multiplier, how much do we decrease the scale, i.g. if aspect == 1, we use same resolution. If aspect == 2 we divide image resolution by 2 and etc. Scaling required only in case if aspect != 1
if (aspect != 1) {
    int newWidth = image.getWidth() / aspect;
    int newHeight = image.getHeight() / aspect;
    byte[] scaledBitmapData = bitmapToByteArray(createScaledBitmap(bao.toByteArray(), newWidth, newHeight));
    bao = new ByteArrayOutputStream(scaledBitmapData.length);
    bao.write(scaledBitmapData, 0 , scaledBitmapData.length);

    image.compressToJpeg(new Rect(0, 0, newWidth, newHeight), jpegQuality, bao);
}

Utility methods:
public static Bitmap createScaledBitmap(byte[] bitmapAsData, int width, int height) {
    Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapAsData, 0, bitmapAsData.length);
    return createScaledBitmap(bitmap, width, height);
}

public static Bitmap createScaledBitmap(Bitmap bitmap, int width, int height) {
    return Bitmap.createScaledBitmap(bitmap, width, height, true);
}

public static byte[] bitmapToByteArray(Bitmap bitmap) {
    ByteArrayOutputStream blob = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, blob);
    return blob.toByteArray();
}

And this should do the trick.


text:
Q: Designing a Licensing Scheme Our startup is creating a product for the SharePoint platform.
I'm wondering, what are some ideas for designing and implementing a licensing scheme for solutions that plug into SharePoint?  How can they be enforced?  I'm realistic enough to understand that most schemes can probably be hacked to some degree, but trust that most enterprises would rather just pay up than resort to hackery so it doesn't have to be a "bulletproof" scheme, just something more than "Scout's Honor".
I'll give an example: in our case, as a part of the provisioning process, our product creates groups of collaborators.  One thought was that we could create a licensing scheme that limited the size of the groups based on which license was purchased.  Such a license would be deployed as a .dll in a .wsp and loaded the value of the size could then be read at runtime by dynamically loading the license .dll.
But this is just one idea.  Are there ways to effectively and unobtrusively enforce software license on a per-server or per-user basis in SharePoint?

A: The best thing I've seen for license enforcement has always been the key pair, as with Microsoft.  Send in Serial Number, get a key and you're good.  This way only half the validation is discoverable.  The trick with SharePoint would be storage of the second key, you have few options with SharePoint that are easy to use and you could get access to consistently.
My thinking you use config files, then give walkthroughs to the end users if the key doesn't store right on how to add permissions, etc.
Registry storage may be doable but may give more permission headaches and SharePoint storage is inconsistent and could vary (Which Site Collection?).
DB Storage might work but would require setup just to store a key.
You could also just grab the key periodically via calling a web service on your end, however that requires an Internet connection where I happen to know many a SharePoint farm is Internet blocked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How are these methods ambiguous? (one takes array, another takes varargs) How are these append() methods ambiguous?
public class Try_MultipleArguments {

    public static void main(String[] args) {

        int array1[] = new int[] {1, 2, 3};

        int array2[] = new int[] {4, 5, 6};

        append(array1, array2);

        append(array1, 4, 5, 6);

    }

    public static int[] append(int[] array1, int[] array2) {
        int[] ans = new int[array1.length + array2.length];
        for(int i=0; i<array1.length; ++i) {
            ans[i] = array1[i];
        }
        for(int i=0; i<array2.length; ++i) {
            ans[i+array1.length] = array2[i];
        }
        return ans;
    }

    public static int[] append(int[] array1, int ... array2) {
        return append(array1,array2);
    }
}

UPDATE
Varargs is equivalent to an array, but this is from inside of the method. From outside of the method it should not be equivalent to it.
UPDATE 2
I see now that I can pass an array to vararg. I didn't knew that. Was always workarounding this need. Hmmm.... Was this from the very beginning of java varargs?

A: The reason is because int... and int[] both accept an array of ints.
Let's take a look at what they accept:
int...

*

*a list of integers (1, 2, 3, 4)

*an array of integers ([1, 2, 3, 4])
int[]

*

*an array of integers ([1, 2, 3, 4])
So the reason Java won't allow this is because both try to accept an array of integers. So it's not that they're the exact same thing.
A quick proof shows that this won't compile:
public static void main (String[] args) throws java.lang.Exception {
    test(1, 1, 1);
}

public static void test(int[] args) {

}

public static void test(int... args) {

}

A: They have the same definition.
In fact, int ... array2 is equivalent to int[] array2.

A: In the var args method, how do you use the variable array2.. Same as array right ??? It's the same actually, just denoted differently...
From the documentation,

It is still true that multiple arguments must be passed in an array,
  but the varargs feature automates and hides the process. Furthermore,
  it is upward compatible with preexisting APIs.

A: From the docs:

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

So it's ambiguous because array also maps to the varargs.

A: When defining a method with varargs, it can also be called using an array:
public static void method(int... array) {
    // do something with array
}

public static void caller1() {
    // This works obviously
    method(1, 2, 3);
}

public static void caller2() {
    // This works also
    method(new int[]{1, 2,, 3});
}

In fact in Java the two calls are analogous.
If you define another method with the array:
public static void method(int[] array)

Java won't know which method to call, because the call with array is already available.
For your case, it means that you can only have one signature:
public static int[] append(int[] array1, int ... array2)

and remove the other one.


text:
Q: Design Considerations For a Paint-Like Windows Application I'm in process of developing a new front end for an old open source fluid modeling engine written in C.  I am using C# and WPF. The apps network generation requires the user to draw a network of pipes, reservoirs, nodes, tanks, etc.  The app is more or less a fancy version of paint ;)
Right now I have the graphics set up as follows.  I have an embedded win-forms Panel that has mouseclick, mousemove, and paint events.  Mouse click saves the clicked coordinates to an array in the singleton class and then triggers the paint event via invalidate();.  The paint event then loops through the array and draws all the node coordinates in the array via: g.FillEllipse(x,y,20,20);  The user can click a node and bring up a menu via a function I wrote called DoesPointExist(xCord, yCord);.  It loops through the coordinates array and returns true if both xcord and ycord are within 5px of the clicked coordinates.  A somewhat archaic solution but it seems to work well enough.
This has worked pretty well for me thus far.  But in the future I am going to have to give each node (or circle on the Panel) more and more properties.  Nothing fancy, just numerical values like elevation that must be associated with each node.  Also, I'm going to need to add in an option to delete nodes at some point.
I could probably do this by setting all values of the deleted row to 0 and placing in if statement in the paintevents loop to not draw deleted points, or even figure out how to just get rid of the row period and shift all the others down.
My question is there a more intelligent and OOP type way to go about this?  Looping through and array seems a little old fashioned, there must be a better way to make use of C# features.  Is there some sort of object or class I could setup to make this process simpler?  The array is fine but by the end its going to be 40-50 columns.  My background is more based in functional type programming with lower level languages like C.  My program seems very bare of objects and classes other than a singleton glass for global data.
I know there are different ways to skin the cat; but it's important that the code I write will be accessible and easy to modify for future engineers so I'd like to add as much within the OOP paradigm as possible.  My current code is very functional... but not very tidy.
Paint event code:
private void wfSurface_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
        Graphics g;
        Graphics h;
        g = wfSurface.CreateGraphics();
        h = wfSurface.CreateGraphics();
        epanet epa = epanet.GetInstance();
        SolidBrush black = new SolidBrush(System.Drawing.Color.Black);
        SolidBrush blue = new SolidBrush(System.Drawing.Color.Pink);
        SolidBrush green = new SolidBrush(System.Drawing.Color.Green);
        System.Drawing.Pen line = new System.Drawing.Pen(System.Drawing.Color.FromArgb(255, 0, 0, 0));

        //Loop to draw vertical grid lines
        for (int f = 50; f < 1100; f += 50)
        {
            e.Graphics.DrawLine(line, f, 0, f, 750);
        }

        //Loop to draw vertical grid lines
        for (int d = 50; d < 750; d += 50)
        {
            e.Graphics.DrawLine(line, 0, d, 1100, d);
        }

        //Loop nodes, tanks, and resevoirs
        for (int L = 1; L < index; L += 1)
        {
            g.FillEllipse(black, Convert.ToInt32(epa.newNodeArray[L, 0] - 8), Convert.ToInt32(epa.newNodeArray[L, 1] - 8), 19, 19);
            h.FillEllipse(blue, Convert.ToInt32(epa.newNodeArray[L, 0] - 6), Convert.ToInt32(epa.newNodeArray[L, 1] - 6), 15, 15);
        }

        for (int b = 1; b < resIndex; b += 1)
        {
            g.FillRectangle(green, Convert.ToInt32(epa.ResArray[b, 0] - 8), Convert.ToInt32(epa.ResArray[b, 1] - 8), 16, 16);
        }
        for (int c = 1; c < tankIndex; c += 1)
        {
            g.FillRectangle(black, Convert.ToInt32(epa.tankArray[c, 0] - 8), Convert.ToInt32(epa.tankArray[c, 1] - 8), 20, 20);
            g.FillRectangle(green, Convert.ToInt32(epa.tankArray[c, 0] - 6), Convert.ToInt32(epa.tankArray[c, 1] - 6), 16, 16);
        }
}

Code for click event:
private void wfSurface_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        //Initialize epanet and save clicked coordinates to singleton class
        epanet epa = epanet.GetInstance();
        epa.xCord = e.X;
        epa.yCord = e.Y;

        //Check if point exists, if does open property window, doesn't do whatever drawing control is selected
        if (epa.DoesPointExist(e.X, e.Y, index) == false)
        {
            switch (epa.controlSelected)
            {
                case "Node":
                    epa.newSetCords(index, e.X, e.Y);
                    wfSurface.Invalidate();
                    index += 1;

                    break;

                case "Res":
                    epa.setResCords(resIndex, e.X, e.Y);
                    wfSurface.Invalidate();
                    resIndex += 1;
                    wfPanel.Cursor = Cursors.Arrow;
                    break;

                case "Tank":
                    epa.setTankCords(tankIndex, e.X, e.Y);
                    wfSurface.Invalidate();
                    tankIndex += 1;
                    break;

                case "Pointer":
                    break;

                default:
                    //epa.newSetCords(index, e.X, e.Y);
                    wfSurface.Invalidate();
                    break;
            }

        }
        else if (epa.DoesPointExist(e.X, e.Y, index) == true)
        {

            MessageBox.Show("Point Already Exists");
            if (epa.propOpen == false)
            {
                // Open control properties in right pannel
            }

        }

Code for singleton class:
public class epanet

{
    private static epanet instance = new epanet();
private epanet() { }

public static epanet GetInstance()
{
    return instance;
}

//Microsoft.Win32.SaveFileDialog save = new Microsoft.Win32.SaveFileDialog();

//Network Node Data
public int nodeIndex { get; set; }
public int newNodeIndex { get; set; }
public double xCord { get; set; }
public double yCord { get; set; }
public double x1Cord { get; set; }
public double y1Cord { get; set; }
public int selectedPoint { get; set; }
//public List<double> nodeList = new List<double>();

//Saving Data
public int fileCopyNum { get; set; }
public string filename { get; set; }
public string path { get; set; }
public string fullFileName { get; set; }

//Window Condition Data
public bool drawSurfStatus { get; set; }
public bool windowOpen { get; set; }
public bool OpenClicked { get; set; }
public bool saveASed { get; set; }
public bool newClicked { get; set; }
public bool propOpen { get; set; }

//Drawing Controls
public string controlSelected { get; set; }

//Declare Array to store coordinates
public double[,] nodeArray = new double[100000, 3];
public double[,] newNodeArray = new double[100000, 7];
public double[,] ResArray = new double[100000, 7];
public double[,] tankArray = new double[100000, 7];

public void newSetCords(int newNodeIndex, double xCord, double yCord)
{
    newNodeArray[newNodeIndex, 0] = xCord;
    newNodeArray[newNodeIndex, 1] = yCord;
    newNodeArray[nodeIndex, 2] = nodeIndex;

}

public void setResCords(int newNodeIndex, double xCord, double yCord)
{
    ResArray[newNodeIndex, 0] = xCord;
    ResArray[newNodeIndex, 1] = yCord;
    ResArray[nodeIndex, 2] = nodeIndex;

}

public void setTankCords(int newNodeIndex, double xCord, double yCord)
{
    tankArray[newNodeIndex, 0] = xCord;
    tankArray[newNodeIndex, 1] = yCord;
    tankArray[nodeIndex, 2] = nodeIndex;

}

public void setCords(int nodeIndex, double xCord, double yCord)
{
    nodeArray[nodeIndex, 0] = xCord;
    nodeArray[nodeIndex, 1] = yCord;
    //nodeArray[nodeIndex, 2] = nodeIndex;

}

public bool DoesPointExist(double xcord, double ycord, int index)
{
    int count = 1;
    bool outcome = false;
    while (count < index)
    {
        if (Math.Abs(xcord - newNodeArray[count, 0]) < 20)
        {
            if (Math.Abs(ycord - newNodeArray[count, 1]) < 20 )
            {
                outcome = true;
                selectedPoint = count;
                index = 0;
            }
        }
        count += 1;
    }

    return outcome;
}

As I said everything works completely fine.  I'm just looking for some feedback on if there's a more professional way to go about doing this.

A: If you've done much programming in C, you should be familiar with the concept of a linked-list.  It's much more useful than an array, because it lets you delete from any point in the list in constant time.  In C#, you'll want to look into System.Collections.Generic.List to make use of it.
Beyond that, standard object-oriented design is to look through your functional requirements and look for nouns, and those should become your classes.  The biggest noun I see in your question is "node."  So instead of having an array of vertices, have a linked list of nodes.  Each node can have properties such as Coordinates and Elevation, and is then extensible if you need more.  Note, if you find your Node class getting cumbersome, that's a huge sign that you should split off other classes.  Any logical grouping should pretty coherently present itself.
Look through your epanet class that you included.  You have functionality to handle files (filename, is it save-as'd, etc).  That should be turned in to a class (in a separate file) just to help keep the files maintainable.  The sequence of arrays you have, all of the same primary dimension define your general node structure.  Put those and your function that operate on those into your Node class.  You already have logic that works; it's just not intuitive to the next reader.  Spend a bit of time questioning your placement of all your code, and asking yourself if there are any logical groupings you can put together.
Your general flow is fine if you want to limit yourself to Winforms/GDI+, and you can obviously get along that way, but since you're programming in WPF, you may want to step up to actually using it while your project is still young.  C# Transition between GDI+ and WPF gives a little bit of a heads-up as how to do so, particularly suggestion 5 of the accepted answer.  There are tons of other references on the web as well.  A quick Google search brought up Manual rendering of a WPF User Control and of course MSDN.  I'll leave WPF advice up to others who know it better than I.
If you don't know yet if you want to use GDI or WPF, you definitely need to have a GDIRenderer class.  Ideally, you should have an IRenderer interface and a GDIRenderer class that implements that interface, though I do find that practically, it's more convenient to make the interface when you have a second object that implements it.  In any case, your Renderer class(es) should take a List of Node as input.  (You currently have them global, but it's generally good to only let one part of code have access to what it needs to, i.e. avoid globals.)  In your current code, GDIRenderer would simply contain and register your OnPaint function.  But by doing this, you isolate all of your rendering into a single class (which should be in a file of its own).  Then, should you decide to move on to WPF, you can substitue the GDIRenderer for a WPFRenderer, which could contain all the code needed to handle the OnRender functionality.  You want to do all you can to separate your business logic from the way you render.


text:
Q: Quantifying which properties are lost in Cayley–Dickson constructions? The Cayley–Dickson construction is a method of generalizing the algebraic structures of the Reals to the Complex to the Quaternions, etc.
For those interested, discussion on the algebraic properties Cayley–Dickson constructions are not new here. For instance, see these older posts:

*

*Why are properties lost in the Cayley–Dickson construction?

*Does the Cayley–Dickson Construction expose new properties
The first is about new properties gained in each iteration, and the second is about why properties are lost in each iteration. I hope it becomes evident why my question differs (albeit subtly) from previous questions.

Cracking this case open once more, what I find most intriguing about this mystery can be briefly explained by this chart, explaining the algebraic properties of each level of the construction:

Not surprisingly, we should expect these types of properties to drop off as the dimensions increase. However, I find it curious that precisely one importantly distinct algebraic property is lost in each construction (according to this chart), and that there seems to be no immediate pattern to precisely which property is lost.
What I mean by this, is that quantifying the properties lost in each iteration yields a sequence of logic with no inherent pattern.
For example, in dimensions $2^n:$
$$
\begin{align*}
n=2&\implies\neg[\forall a,b\in\mathbb{H}\ \ \ \ (ab=ba)]\\
n=3&\implies\neg[\forall a,b,c\in\mathbb{O}(a(bc)=(ab)c)]\\
n=4&\implies\neg[\forall a,b\in\mathbb{S}\ \ \ \ \ (a(ab)=(aa)b)].
\end{align*}$$
Sure, one immediate pattern is that these properties have to do with multiplication, but for $n=1$ or $n>5$, it is not clear. However, perhaps even in such cases, the properties in question and be equivalently expressed by some property of multiplication. So my question is:

Is there some formula (probably second order) which describes precisely which algebraic property is lost in the $2^n$ dimensional construction? Such formula may not have to describe exactly the same properties as the one in the above table, but would yield something equisatisfiable.


text:
Q: Error: ReferenceError: cliSystemConfigPackages is not defined I was trying to get a cerialize package to show in the vendor directory of the dist directory when I start getting the following error message, although ng build and ng server cmds work. The error shows up when I try localhost:4200 in the browser
Edit 2
This error might not be dependent on cerialize, because after removing all reference to cerialize in the app, performing an ng build and ng-serve, the problem still persist
error (edit 1 for full output)
zone.js:323 Error: ReferenceError: cliSystemConfigPackages is not defined(…)
ZoneDelegate.invoke
@ zone.js:323Zone.run
@ zone.js:216(anonymous function)
@ zone.js:571ZoneDelegate.invokeTask
@ zone.js:356Zone.runTask
@ zone.js:256drainMicroTaskQueue
@ zone.js:474ZoneTask.invoke @ zone.js:426

// The actual zone.js line referenced
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
                return this._invokeZS
                    ? this._invokeZS.onInvoke(this._invokeDlgt, this.zone, targetZone, callback, applyThis, applyArgs, source)
                    : callback.apply(applyThis, applyArgs);
            };

// zone popup error (popup on red x at zone error position in trace)
Error: ReferenceError: cliSystemConfigPackages is not defined
at barrels.forEach (http://localhost:4200/system-config.js:79:5)
at Array.forEach (native)
at eval (http://localhost:4200/system-config.js:78:9)
Evaluating http://localhost:4200/system-config.js
Error loading http://localhost:4200/system-config.js

system-config.ts
/** Map relative paths to URLs. */
const map: any = {
  '@angular2-material': 'vendor/@angular2-material',
  'cerialize': 'vendor/cerialize/dist/serialize.js',
  'immutable': 'vendor/immutable',
  'lodash': 'vendor/lodash/lodash.js'
};

/** User packages configuration. */
const materialPackages: string[] = [
  'core',
  'button',
  'card',
  'checkbox',
  'grid-list',
  'icon',
  'input',
  'list',
  'progress-bar',
  'progress-circle',
  'radio',
  'sidenav',
  'slide-toggle',
  'tabs',
  'toolbar',
];

/** User packages configuration. */
const packages: any = createCustomConfig(materialPackages);

function createCustomConfig(packages: string[]): any {
  return packages.reduce(
      (packageConfig: any, packageName: string) => {
        packageConfig[`@angular2-material/${packageName}`] = {
          format: 'cjs',
          defaultExtension: 'js',
          main: packageName
        };
        return packageConfig;
      }, {});
}

////////////////////////////////////////////////////////////////////////////////////////////////
/***********************************************************************************************
 * Everything underneath this line is managed by the CLI.
 **********************************************************************************************/
const barrels: string[] = [
  // Angular specific barrels.
  '@angular/core',
  '@angular/common',
  '@angular/compiler',
  '@angular/http',
  '@angular/router',
  '@angular/platform-browser',
  '@angular/platform-browser-dynamic',

  // Thirdparty barrels.
  'rxjs',

  // App specific barrels.
  'app',
  'app/shared',
  'app/shared/side-nav',
  'app/+new-patient',
  'app/registration/name',
  'app/registration/patient',
  'app/registration/age',
  'app/registration/gender',
  'app/registration/marital-status',
  'app/registration/religion',
  'app/registration/language',
  /** @cli-barrel */
];

const cliSystemConfigPackages: any = {};
barrels.forEach((barrelName: string) => {
  cliSystemConfigPackages[barrelName] = { main: 'index' };
});

/** Type declaration for ambient System. */
declare var System: any;

// Apply the CLI SystemJS configuration.
System.config({
  map: {
    '@angular': 'vendor/@angular',
    'rxjs': 'vendor/rxjs',
    'main': 'main.js'
  },
  packages: cliSystemConfigPackages
});

// Apply the user's configuration.
System.config({ map, packages });

angular-cli-build.js
/* global require, module */

var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function (defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      '@angular2-material/**/*',
      'angularfire2/**/*.js',
      'core-js/client/core.js',
      'cerialize/**/*',
      'firebase/lib/*.js',
      'immutable/**/*.js',
      'lodash/lodash.js'
    ]
    /*   sassCompiler: {
     includePaths: [
     'src/app/style' <-- directory for SASS reference files
     ] */
  });
};

Prior to my attempt to use cerialize package, my app worked fine. It is the first time I am actually seeing this error.
Cheers and thanks


text:
Q: Phpunit giving undefined variable projects error I am learning PHPUnit with Laravel and is stucked in an error.
I have been following TDD with Laravel from Laracasts and I am facing an PHPunit error when I do a get request.
The error am getting is :
ErrorException: Undefined variable: project
C:\xampp\htdocs\birdboardapp\storage\framework\views\06b7a65ce168ffa601dc57bf60713aa232636d2f.php:7
My test case is
  /** @test */
    public function a_user_can_view_a_project()
    {

        $this->withoutExceptionHandling();

        $project = $attributes = factory('App\Project')->create();

        $this->get('/projects/' . $project->id)
            ->assertSee($project->title)
            ->assertSee($project->description);
    }

My routes/web.php is as below
 Route::get('/projects/{project}', 'ProjectsController@show');

ProjectsController is
public function show(){

    $project = Project::findOrFail(request('project'));

    return view('projects.show' ,compact($project));
}

and the view (show.blade.php in projects directory) is
<!DOCTYPE html>

    <title></title>

{{ $project->title }}

{{ $project->description }}

Now when I try to run the test case a_user_can_view_a_project it gives me an error saying "ErrorException: Undefined variable: project"

A: In your controller show method, you seem to be calling compact($project), but that's not how compact function works.
compact accepts the variable name, not the variable itself.
See : https://www.php.net/manual/en/function.compact.php
The solution would be :

*

*use compact correctly :

public function show() {
  $project = Project::findOrFail(request('project'));

  return view('projects.show' , compact('project'));
}

*don't use compact at all ( recommended ) :

public function show() {
  $project = Project::findOrFail(request('project'));

  return view('projects.show' , [
    'project' => $project
  ]);
}


text:
Q: Adding items to a combo box I have a combo box that I want to bind with one column in my SQL database. This column is named "Type" and each row has a type. There are 10 Types total. This table has a total of 144 rows.
Now, when I bind the combo box to this column, I get 144 items in the combo box. So, instead of just getting the 10 types, I am getting each type however many times it shows up in that column. Is there a way to fix this? I have thought about hard coding the items into the combo box, but this might mess up when the user adds an item with a new "Type". Any help is appreciated. thanks

A: SELECT DISTINCT Type FROM TABLE;


text:
Q: STL overload vector assignment I'm working on a class that overloads the index operator ([]). To allow for assignment of an element, it's necessary for the operator to return a reference to the element. For example:
class myclass: public vector<int>
{
...
public:
    int & myclass::operator [] (int i)
    {
        return vector<int>::operator[](i);
    }
...

In this situation, the client code can use the returned reference to assign a value to an element. However, I would like to have a way to intercept the actual assignment of the element so I can use the assigned value to do some internal housekeeping. Is there a relatively clean and simple way to do this, or should I just create some accessor functions instead of using operator overloading?

A: There is no way to intercept the assignment of an integer. However, you could instead return a reference to a custom type whose assignment operator you have overloaded. The custom type can be convertible to int, so that it can be used as one.
Of course, this means that you cannot inherit std::vector<int> which returns a reference to int. You should avoid inheriting std::vector publicly anyway. A user of your class may accidentally delete the object through a std::vector<int>* which would have undefined behaviour.

A: AFAIK the std::vector index operator already returns reference to the item (either const or non-const), so no need to inherit and override.
If you want to intercept the assignment of the value, the correct way of doing this is to define/override the assignment operator of the value itself (you cannot do it in the vector index operator). That will of course not work with pure int, so you'd need to wrap the int in a class which will provide the assignment operator and there you can do "anything you want".
EDIT:
Ok I see, so then it might be needed to do some overrides. For the reverse lookup, one of the possibilities could be to not store the value in the reverse structure, but a pointer to it (to the original location). The value assignment in the original structure would then be reflected with the pointer redirection. This would also need to pass a custom comparison operator to the reverse lookup map, to not compare the pointers, but the values.
In general, it might be worth to also check boost::multi_index, which allows to do exactly that - create a single structure with multiple lookup indices.


text:
Q: android: add view to an inflated View I want to inflate a layout from my res/layout directory, and add some views to it in my activity class.
My layout xml file:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_marginTop="30dip"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/reg_button"
        style="@style/simple_button"
        android:onClick="clickButton"
        android:text="@string/reg_button" />

    <!--  I WANT TO PUT CONTENT HERE ! -->

</LinearLayout>

In my java code, I try to inflate the above layout and add a linearLayout with a Button.
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    mContext = getApplicationContext();

    //inflate xml
    LinearLayout mainLayout = (LinearLayout)     LayoutInflater.from(getBaseContext()).inflate(R.layout.regions_search, null);

    //Create a new LinearLayout
    LinearLayout newLinear = new LinearLayout(mContext);
    newLinear.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

    //create  a new Button
    Button test = new Button(mContext);
    test.setText("My button");

    //first , I add button to the LinearLayout
    newLinear.addView(test);

    //Then, I add layout to the inflated layout
    mainLayout.addView(newLinear);

    //display
    setContentView(mainLayout);

But the newLinear view (and its children) aren't getting displayed.

A: Use this in your activity,
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // display
    setContentView(R.layout.activity_main);

    Context mContext = getApplicationContext();
    LinearLayout mainLayout = (LinearLayout) findViewById(R.id.regions_search);
    // Create a new LinearLayout
    LinearLayout newLinear = new LinearLayout(mContext);
    newLinear.setLayoutParams(new LinearLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

    // create a new Button
    Button test = new Button(mContext);
    test.setText("My button");

    // first , I add button to the LinearLayout
    newLinear.addView(test);

    // Then, I add layout to the inflated layout
    mainLayout.addView(newLinear);
}

And in your xml file (activity_main.xml)in write as shown below,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/regions_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="30dip"
android:orientation="vertical">

<Button
    android:id="@+id/reg_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:onClick="clickButton"
    android:text="RegButton" />

<!-- I WANT TO PUT CONTENT HERE ! -->

</LinearLayout>

Try this it will work 100%.

A: Can you try adding the width and height parameters for both the new LinearLayout and the Button that you have added? Those parameters are required when creating views.
like this.
newLinear.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

A: test.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,1f));
comment line
setContentView(mainLayout);


text:
Q: Why does these homeomorpic with the $\mathbb{R}^2$? $Q) $ The usual topological space $(\mathbb{R}^2, T)$.  Say the subspace $(A_k ,T_k)$ in $(\mathbb{R}^2 ,T)$ for each $k \in \{ 1,2,3,4,5\}$. Find the $(A_k ,T_k)$ whose homeomorphic with the $(\mathbb{R}^2, T)$.
$A_1 = \{ (x,y) \vert x^2 + y^2 >1 \}$
$A_2 = \{ (x,y) \vert x^2 + y^2 <1 \}$
$A_3 = \{ (x,y) \vert -x \lt y \lt x \}$
$A_4 = \{ (x,y) \vert xy < 1 \}$
$A_5 = \mathbb{R}^2 - \{ (x,0) \vert 0 \leq x  \}$
In my point of view, the $A_1$ $\simeq$ $\mathbb{R}^2 \setminus (0,0)$ and $A_2 \simeq \mathbb{R}^2$. Because if we either contract the boundary of $A_1$ to $(0,0)$ or expand the boundary of the $A_2$ to the outer directions for the the $A_2$ case. Vice versa the case $A_4$, with the similar method, $A_4 \simeq \mathbb{R}^2$.
But the problem is $A_3$ and $A_5$. The answer sheet claimed the both of them are homeomorphic with the $\mathbb{R}^2$.(I.,e.$A_3 \simeq \mathbb{R}^2$ & $A_5 \simeq \mathbb{R}^2$. ) I can't understand why these do hold. If we applying the same method above for the $A_5$ case, Is it have to be
homeomorphic with the subset of $\mathbb{R}^2 \setminus (0,0)$ at most? Because it is not include the origin point at all.

A: Concerning $A_3$: if you rotate anticlockwise that set around the origin by $\frac\pi4$ radians, you get the open first quadrant, which is homeomorphic to $\Bbb R^2$ (consider the map $(x,y)\mapsto(e^x,e^y)$).
Concerning $A_5$: Consider the complex exponential map. Then$$\exp\left(\left\{z\in\Bbb C\mid-\frac\pi2<\operatorname{Im}z<\frac\pi2\right\}\right)=\Bbb C\setminus[0,\infty)$$and this gives you a homeomorphism between your set and $\left\{z\in\Bbb C\mid-\frac\pi2<\operatorname{Im}z<\frac\pi2\right\}$. And this set is homeomorphic to $\Bbb C$.


text:
Q: Add Bootstrap Modal using JavaScript and Cloned Node I am attempting to add a modal to a page after the page has load via a button click (in the below I did it on document ready instead of a click). The modal is created by cloning another modal and then appending the clone to the DOM. The modal node appears in the DOM but the modal does not open when giving it .modal() commands. I have created a simple codepen that shows my code and will show it below.
Codepen: https://codepen.io/anon/pen/YxQrZG
HTML:

Modal Header

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

JS:
 $("Document").ready(function () {
   var newModal = $("#exampleModel").clone(true, true);
   newModal.attr("id", "NewModelId")
   $('#LocalModalArea').append(newModal)
   $("#NewModelId").modal("show")
 });

A: On your codepen you haven't added jQuery which is required by bootstrap.

 $("Document").ready(function () {
   var newModal = $("#exampleModel").clone(false, true);
   newModal.attr("id", "NewModelId")
   $('#LocalModalArea').append(newModal);
   $("#NewModelId").addClass('super-red');
   $("#NewModelId").modal("show")
 });
.super-red{
 background-color: darkred;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Modal Header

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

Note, I added additional css to highlight cloned element.


text:
Q: How to optimize indexing of large number of DB records using Zend_Lucene and Zend_Paginator So I have this cron script that is deployed and ran using Cron on a host and indexes all the records in a database table - the index is later used both for the front end of the site and the backed operations as well.
After the operation, the index is about 3-4 MB.
The problem is it takes a lot of resources (CPU: 30+ and a good chunk of memory) and slows the machine down. My question is about how to optimize the operation described below:
First there is a select query built using the Zend Framework API, this query is then passed to a Paginator factory that returns a paginator which I am using to balance the current number of items being indexed and not iterate over too much items.
The script is iterating over the current items in the paginator object using a foreach loop until reaching the end and then it starts from the beginning after getting items for the next page.
I am suspecting this overhead is caused by the Zend_Lucene but no idea how this could be improved.

A: See my answer to Can I predict how large my Zend Framework index will be?
I tested Zend_Search_Lucene versus Apache Lucene (the Java version). In my test, the Java product indexed 1.5 million documents about 300x faster than the PHP product.
You'll be much happier using Apache Solr (the Tomcat container for Apache Lucene).  Solr includes a tool called DataImportHandler that sucks data directly from a JDBC data source.
Use the PECL Solr extension to communicate with Solr from PHP.  If you can't install that PHP extension, use Curl which should be available in default installations of PHP.


text:
Q: Mix of columns in excel to one colum with Pandas I have to import this Excel in code and I would like to unify the multi-index in a single column. I would like to delete the unnamed columns and unify everything into one. I don't know if it's possible.

I have tried the following and it imports, but the output is not as expected. I add the code here too
import pandas as pd
import numpy as np

macro = pd.read_excel(nameExcel, sheet_name=nameSheet, skiprows=3, header=[1,3,4])
macro = macro[macro.columns[1:]]
macro

A: The way to solve it is to save another header of the same length as the previous header.
cols = [...]
if len(df1.columns) == len(cols):
   df1.columns = cols
else:
   print("error")


text:
Q: Calling a parameterized function from a procedure where the function name is stored in an array I am having n number of functions. Consider n=10
I have stored the names of these n functions in an array named Array1
Example: Array1= Array("Function_1",Function_2","Function_3"............,"Function_10")
General Structure of these functions:
Function Function_1(TestRange as Range) as Range
...Some code
End Function
When I call this function using the array index how do I pass the parameter for TestRange?
Eg:
Sub main()
Dim MainRange as Range
For i = 1 To UBound(Array1)
    Set MainRange = Application.Run(Array1(i))
Next

End Sub
When I try to run main() procedure I am encountering the following error:
Run-Time Error '449' : Argument Not Optional
Can anyone help me on this?
Thanks,
Akshat

A: Sub Main()
    Dim arr, x
    Dim rngIn As Range, rngOut As Range

    arr = Array("Func1", "Func2")
    Set rngIn = ActiveSheet.Range("A1")

    For x = 0 To UBound(arr)
        Set rngOut = Application.Run(arr(x), rngIn)
        Debug.Print rngOut.Address()
    Next x

End Sub

Function Func1(rng As Range) As Range
    Set Func1 = rng.Resize(10, 1)
End Function

Function Func2(rng As Range) As Range
    Set Func2 = rng.Resize(1, 10)
End Function


text:
Q: Php clean double dash with str_replace I'm using php to clean out names to be used in a url slug:, where $title might look like this:  "This is the Title" or "This is the Title & Subtitle"
Those above examples I want to change to "this-is-the-title" and "this-is-the-title-subtitle", respectively.  So, I made this code....
<?php
$input1 = str_replace(" ","-",strtolower($title));
$output1 = preg_replace('/[^A-Za-z0-9-]/', '', $input1);
$output2 = str_replace("--","-",$output1);
echo $output2;
?>

It's working great, cleaning out all the non-alpha numeric, replacing spaces with dashes and making everything lower case.
However, in some instances, it's returning the double dash ("Title & More" turns to ("title--more").  It should be "title-more".  I know why the double dash is there, but I can't seem to clean it out.
I put in the line of code for $output2, but it doesn't seem to be working for some reason.  After lots of trial and error, I'm at a loss.
Thanks...

A: You can solve the same in a single regex:
preg_replace('/[^a-z0-9]+/', '-', strtolower($title));

The only change I made was the trailing + in the regex, meaning "1 or more occurances of the previous group". Now every group of special characters is replaced with a single dash - no matter how long the group is.
Just for answering the actual question, though: You would need to reduce duplicate dashes in a loop in your case:
$output2 = $output1;
do {
    $output1 = $output2;
    $output2 = str_replace("--", "-", $output1);
} while ($output2 != $output1);

(I would seriously consider renaming the variables, though)

A: I'm using a function written by myself to reach exactly the same goal.
function urlify($string, $utf8Input = false) {
    $string = strtolower(iconv($utf8Input ? 'UTF-8' : 'ISO-8859-1', 'ASCII//TRANSLIT', $string));
    $string = preg_replace('/[^a-z0-9]+/', '-', $string);
    $string = trim($string, '-');
    if (empty($string)) return '-';
    return $string;
}

You can remove the UTF8 and iconv part if you are not working with languages that use accented letters.

A: I can share my little function. Works even all kinds of languages. Russian, german, etc.
public static function getSeo($str, $separator = '-'){
    $from = array('А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р',
        'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я', 'а', 'б', 'в', 'г', 'д', 'е', 'ё',
        'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы',
        'ь', 'э', 'ю', 'я', "Á", "À", "Â", "Ä", "Ă", "Ā", "Ã", "Å", "Ą", "Æ", "Ć", "Ċ", "Ĉ", "Č", "Ç", "Ď", "Đ", "Ð",
        "É", "È", "Ė", "Ê", "Ë", "Ě", "Ē", "Ę", "Ə", "Ġ", "Ĝ", "Ğ", "Ģ", "á", "à", "â", "ä", "ă", "ā", "ã", "å", "ą",
        "æ", "ć", "ċ", "ĉ", "č", "ç", "ď", "đ", "ð", "é", "è", "ė", "ê", "ë", "ě", "ē", "ę", "ə", "ġ", "ĝ", "ğ", "ģ",
        "Ĥ", "Ħ", "I", "Í", "Ì", "İ", "Î", "Ï", "Ī", "Į", "IJ", "Ĵ", "Ķ", "Ļ", "Ł", "Ń", "Ň", "Ñ", "Ņ", "Ó", "Ò", "Ô",
        "Ö", "Õ", "Ő", "Ø", "Ơ", "Œ", "ĥ", "ħ", "ı", "í", "ì", "i", "î", "ï", "ī", "į", "ij", "ĵ", "ķ", "ļ", "ł", "ń",
        "ň", "ñ", "ņ", "ó", "ò", "ô", "ö", "õ", "ő", "ø", "ơ", "œ", "Ŕ", "Ř", "Ś", "Ŝ", "Š", "Ş", "Ť", "Ţ", "Þ", "Ú",
        "Ù", "Û", "Ü", "Ŭ", "Ū", "Ů", "Ų", "Ű", "Ư", "Ŵ", "Ý", "Ŷ", "Ÿ", "Ź", "Ż", "Ž", "ŕ", "ř", "ś", "ŝ", "š", "ş",
        "ß", "ť", "ţ", "þ", "ú", "ù", "û", "ü", "ŭ", "ū", "ů", "ų", "ű", "ư", "ŵ", "ý", "ŷ", "ÿ", "ź", "ż", "ž"
    );
    $to = array('A', 'B', 'V', 'G', 'D', 'E', 'E', 'Z', 'Z', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S',
        'T', 'U', 'F', 'H', 'C', 'Tch', 'Sh', 'Shtch', '', 'Y', '', 'E', 'Iu', 'Ja', 'a', 'b', 'v', 'g', 'd', 'e',
        'e', 'z', 'z', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'tch', 'sh',
        'shtch', '', 'y', '', 'e', 'iu', 'ja', "A", "A", "A", "A", "A", "A", "A", "A", "A", "AE", "C", "C", "C", "C",
        "C", "D", "D", "D", "E", "E", "E", "E", "E", "E", "E", "E", "G", "G", "G", "G", "G", "a", "a", "a", "a", "a",
        "a", "a", "a", "a", "ae", "c", "c", "c", "c", "c", "d", "d", "d", "e", "e", "e", "e", "e", "e", "e", "e", "g",
        "g", "g", "g", "g", "H", "H", "I", "I", "I", "I", "I", "I", "I", "I", "IJ", "J", "K", "L", "L", "N", "N", "N",
        "N", "O", "O", "O", "O", "O", "O", "O", "O", "CE", "h", "h", "i", "i", "i", "i", "i", "i", "i", "i", "ij", "j",
        "k", "l", "l", "n", "n", "n", "n", "o", "o", "o", "o", "o", "o", "o", "o", "o", "R", "R", "S", "S", "S", "S",
        "T", "T", "T", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "W", "Y", "Y", "Y", "Z", "Z", "Z", "r", "r",
        "s", "s", "s", "s", "B", "t", "t", "b", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "w", "y", "y", "y",
        "z", "z", "z"
    );
    $str = str_replace($from, $to, $str);
    $str = iconv('UTF-8', 'ASCII//IGNORE//TRANSLIT', $str);
    $str = trim(preg_replace('/[^ A-Za-z0-9_-]/', ' ', $str));
    return preg_replace('/[ -]+/', $separator, $str);
}

A: Use this to remove multiple spaces - preg_replace('/\s+/', ' ', $title)
After this add the dashes to the string - str_replace(" ","-",strtolower($title));

A: you can replace <space>&<space> with a single -. or replace more than one instance of - with a single -

A: After sleeping on the issue, then reading these replies (thanks as always) it finally dawned on me what was happening.
My code was leaving me with three dashes:
This:  "Books & Magazines"
Was changing to this:  "Books---Magazines" (The & replace with dash and spaces as well gives 3 dashes)
I ran it through an str_replace to clear double dashes to single, but still was left with a double dash and this was what was driving me crazy.
I kept getting this:  "Books--Magazines"
Turns out the str_replace was actually working.  Since there were three dashes, the first double dash was replaced and now the THIRD dash, but only a SINGLE dash was left alone.
Thus, this:  "---" became this "--"
I needed to run it through a str_replace 1 more time to fix the problem.  The solve problem looks just like my original code, but with 1 more line.
Probably not the most elegant solution, but it works and makes sense in my head finally.
<?php
$input1 = str_replace(" ","-",strtolower($title));
$output1 = preg_replace('/[^A-Za-z0-9-]/', '', $input1);
$output2 = str_replace("--","-",$output1);
$output3 = str_replace("--","-",$output2);
echo $output3;
?>

A: I think this is best:
 $output =  trim(preg_replace('/-+/', '-', $str), '-');

More: How can I convert two or more dashes to singles and remove all dashes at the beginning and end of a string?


text:
Q: Default element for Ant's macrodef? I would like to create a macro as such:
<macrodef name="testing">
  <element name="test" implicit="yes"/>
  <sequential>
    <test/>
  </sequential>
</macrodef>

And then use it:
<testing>
  <echo message="hello world"/>
</testing>

However, I would like to specify a default for the implicit element... something like:
<macrodef name="testing">
  <element name="test" implicit="yes">
    <echo message="hello world"/>
  </element>
  <sequential>
    <test/>
  </sequential>
</macrodef>

So I can then use it as such:
<testing/>

Except where I want to change the default element.
Is this possible without defining a task via a Java class?  So far, I don't see any documentation that indicates how to do it, if so.

Update
I ended up resolving my particular issue by using refid for filesets (which is what I actually was trying to pull into an element).  Using the refid, it was simple to just use a macrodef attribute, which CAN have a default value.
Another alternative would be to create a new base macro which uses the element, and then I could have kept my existing macro as using that one... but still, there is no real default mechanism for an element (which would be nice).
So, Simon gets the answer since he's correct!  Thanks!

A: This is not possible based on the nested element element documentation for the macrodef task.
There is a Bugzilla issue open for exactly the functionality you describe, unfortunately it has been open since 2004.

A: if you define your macrodef as:
<macrodef name="testing">
    <element name="additional" optional="true"/>
    <sequential>
        <echo message="hello"/>
        <additional/>
    </sequential>
</macrodef>

the following invocation:
<target name="testing-call">
    <mylib:testing/>
    <mylib:testing>
        <additional>
            <echo message="world!"/>
        </additional>
    </mylib:testing>
</target>

will output:
[echo] hello
[echo] hello
[echo] world!


text:
Q: Getting nullPointerException because Mockito variable is set to null even though I have mocked it Here is the class and the method I am trying to unit test.
public abstract class ShowService {

    @Resource(name = "blogCoreSolrClient")
    private SolrClient blogCoreSolrClient;

    protected Show findShow(ClientRegion clientRegion, TargetLocale locale, Integer showId) {

        SolrQuery query = new SolrQuery();
        query.setQuery("type:" + SolrType.show)
                .addFilterQuery(getRegionQuery(clientRegion))
                .addFilterQuery(getLanguageFallbackQuery(locale))
                .addFilterQuery("show_id:" + showId)
                .setRows(1);

        QueryResponse response = blogCoreSolrClient.query(query);

        List<Show> shows = response.getBeans(Show.class);

        if (shows != null && shows.size() > 0) {
            return shows.get(0);
        }

        return null;

    }

    public static class SyndicatedShow {
        @Field("show_id")
        public Integer showId;

        @Field("path_value")
        public String pathValue;
    }
}

Here's my Unit test written using Mockito
public class ShowServiceTest {

    public final QueryResponse queryResponse = Mockito.mock(QueryResponse.class);
    public final SolrClient blogCoreSolrClient = Mockito.mock(SolrClient.class);
    public final SolrQuery SolrQuery = Mockito.mock(SolrQuery.class);
    private SolrDocumentList solrDocuments = Mockito.mock(SolrDocumentList.class);
    private ShowService showService = Mockito.mock(ShowService.class);

    @Test
    public void findShowTest() {
      Mockito.when(blogCoreSolrClient.query(solrQueryCaptor.capture())).thenReturn(queryResponse);

        Mockito.when(queryResponse.getResults()).thenReturn(solrDocuments);

       Mockito.when(blogCoreSolrClient.query(any())).thenReturn(queryResponse);

        ShowService.Show showsResult = ShowService.findShow(ClientRegion.US, TargetLocale.EN_US, 1234);

        assertThat(showsResult.pathValue).isEqualTo("shows/test/");
    }

}

I am getting Null at blogCoreSolrClient when the code passes to findShow().
Because of that I am getting NullPointerException.
Any suggestions, where I might be going wrong. TIA

A: There are different problems :

*

*You're mocking the class under test

 private ShowService showService = Mockito.mock(ShowService.class);

*

*You don't tell to your ShowService to use the blogCoreSolrClient mock, then the blogCoreSolrClient mock instance is created, but never used.

As you are using IOC to inject the SolrClient (@Resource annotation), you need to inject the mock in your ShowService instance during the test.
There are different solutions, but the more convenient in your case would be to use the Mockito Extension to perform the injection.
Something like :
@ExtendWith(MockitoExtension.class)
public class ShowServiceTest {

@Mock
private SolrClient blogCoreSolrClient;
... // Other mocks

@InjectMocks
private ShowService showService;

@Test
public void findShowTest() {
  Mockito.when(blogCoreSolrClient.query(any())).thenReturn(queryResponse);
  ... // Complete test

}

}

The problem would be that your class under test is an abstract class.
I don't see any abstract method. So, if you really need the class under test to be abstract, then you'll face a technical difficulty with @InjectMocks.
Here are some solutions :
https://tedvinke.wordpress.com/2020/06/22/mockito-cannot-instantiate-injectmocks-field-the-type-is-an-abstract-class/


text:
Q: What will be Summation $\sum_{n=1}^{\infty}\frac{n^2}{n!}$ I break it down into two parts the numerator one into $\dfrac{n(n+1)(2n+1)}{ 6}$ but what should be summation of $n!$ ?

A: $$\sum_{n=1}^{\infty}\dfrac{n^2}{n!}=\sum_{n=1}^{\infty}\dfrac{n}{(n-1)!}=\sum_{n=1}^{\infty}\dfrac{n-1+1}{(n-1)!}=\sum_{n=1}^{\infty}\dfrac{n-1}{(n-1)!}+\sum_{n=1}^{\infty}\dfrac{1}{(n-1)!}$$
$$=\sum_{n=1}^{\infty}\dfrac{1}{(n-2)!}+\sum_{n=1}^{\infty}\dfrac{1}{(n-1)!}=e+e=2e$$

A: Hint: Consider the first two derivatives of the exponential series.


text:
Q: How do I get a table with 3 columns and the third colums only has 1 100%

            Hanrathsingel 14
            Home
            This one has to take the full height of the table

            1252 AE Laren
            Wie zijn wij

            T. 035-6231419
            Informatie

            M. 06-21700357
            Algemene Voorwaarden

            laren@qualitysites4all.com
            Contact

How do I get the column to be 100% of the table height but the other columns must keep their height?
Because I want to put a widget in there but I have to work in my boss his cms and I am not allowed to make new divs :(

A: Try rowspan:

            Hanrathsingel 14
            Home
            This one has to take the full height of the table

            1252 AE Laren
            Wie zijn wij

            T. 035-6231419
            Informatie

            M. 06-21700357
            Algemene Voorwaarden

            laren@qualitysites4all.com
            Contact

Example

A: JSFiddle Example
Use rowspan="5" in that TD.
Rowspan attribute, tells your element to "get the height" of 5 rows in this case.
If you have dinamic content remember to update this value to the actual number of rows of your table.


text:
Q: Django comments reverse relationship When using django.contrib.comments is there anyway to add the reverse relationship to a model that has comments?
For example:
post = Post.objects.all()[0]
comments = post.comments.all()

A: Yes, you should be able to do:
from django.contrib.contenttypes import generic
class Post(models.Model):
    ...
    comments = generic.GenericRelation(Comments)

per the Django docs on reverse generic relations

A: I came up with another way to do this (why? Because I wasn't aware of any other way to do that time). It relies on having an abstract model class from which all models in the system are derived. The abstract model itself has a method, comments, defined which when called returns a QuerySet of all the comment objects associated with the corresponding concrete object. I implemented it thus:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment

class AbstractModel(models.Model):

    def comments(self):
        """Return all comment objects for the instance."""
        ct = ContentType.objects.get(model=self.__class__.__name__)
        return Comment.objects.filter(content_type=ct,
                                    object_pk=self.id)

    class Meta:
        abstract = True


text:
Q: Flutter firebase drowpdown items cannot display I try to make a dropdown taking data from firestore, after selecting the items from DromdownMenuItem the selected new value cannot display please help..?
DropdownButtonHideUnderline(
                  child: DropdownButton<String>(
                    isDense: true,
//isExpanded: false,
                    value: projectName,
                    onChanged: (String? newValue) {
                      debugPrint('selected onchange: $newValue');
                      setState(
                        () {
                          debugPrint('make selected: $newValue');
                          projectName = newValue.toString();
                          state.didChange(newValue);
                          setDefaultMake = false;

                          ///var setDefaultMakeModel = true;
                          controllerProjectName.text = newValue.toString();
                        },
                      );
                    },
                    items: snapshot.data!.docs.map((value) {
                      return DropdownMenuItem<String>(
                        value: value.get('project_name'),
                        child: Text('${value.get('project_name')}'),
                      );
                    }).toList(),
                  ),
                ),


text:
Q: Spring Boot application won't run JavaScript code I am building a spring web application that allows sending code snippets to a database. I have an HTML endpoint where you can enter some text and click a button so that the text is sent to a database. Here's the html code:

The send.js script is responsible for taking the input text and casting it to json. Here's the send.js code:
    function send() {
    let object = {
        "code": document.getElementById("code_snippet").value
    };

    let json = JSON.stringify(object);

    let xhr = new XMLHttpRequest();
    xhr.open("POST", '/api/code/new', false)
    xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    xhr.send(json);

    if (xhr.status == 200) {
        alert("Success!");
    }
}

For some reason when I press the button nothing happens. I tried debugging the app and it seems like it doesn't execute the js code. I had some issues with even accessing the send.js in html at first, intellij just couldn't see it for some reason. This is my resources structure:

What am I doing wrong here?
Edit: I tried adding this instead of just checking if status is equal to 200 and I dont get either of the alerts
if (xhr.status != 200) {
    alert("Something went wrong!");
} else if (xhr.status == 200){
    alert("Success!");
}

A: In the html file you have id="code-snippet", and in the js you have "code_snippet", try fixing that


text:
Q: view data from joined table in database im trying to view data from 2 seperate table, but this error came out:
"Notice: Trying to get property of non-object in D:\xampp\htdocs\testsubject\User\inventory.php on line 18"

this is my PHP code:
$sql = "SELECT storage_details.itemCODE,storage_details.pckgeID,storage_details.cndition,storage_details.duration,pckge_info.price,storage_details.status
    FROM storage_details
    INNER JOIN pckge_info
    ON storage_details.pckgeID=pckge_info.pckgeID";
$result = $link->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "itemcode: " . $row["itemCODE"]. " - packageid: " . $row["pckgeID"]. "condition: " . $row["cndition"]. "duration: " . $row["duration"]. " status: " . $row["price"]. " " . $row["status"]."<br>";
}
} else {
echo "0 results";
}

mysql_free_result($result);

A: Trying to get property of non-object

this occurs when your object is null so I would look into the query and see if $result object is populated, most likely $result is null when you are running the query and thus the error.

A: Your query is most likely returning a database error. num_rows is trying a evaluate a null object. Have your script die on error and return the message. That will point you in the right direction once you figure out where you've gone wrong.
if ($result === false) { die(mysql_error($link)); }

Update: After reading your comments it seems the column pckge_info.pckgeID likely doesn't exist. Double check to make sure you are calling the correct column name for the table you are querying.


text:
Q: Load dependencies while compiling in eclipse Hi I am trying out hadoop tutorial for sample WordCount.
It asks to compile the program as follows:
$ bin/hadoop com.sun.tools.javac.Main WordCount.java

Executing javac with hadoop command seems to load all the dependencies for hadoop auomatically. Now I am trying out the same from eclipse. How can I imitate this / load hadoop dependencies / execute hadoop.sh while compiling through eclipse.

A: You can try to use eclipse's ability to run external tools


text:
Q: $E(X)=\int_0^{\infty} (1-F(t)) dt-\int_{\infty}^0 F(t) dt$? Show that given $X$ is an integrable random variable with CDF $F$, then $$E(X)=\int_0^{\infty} (1-F(t)) dt-\int_{-\infty}^0 F(t) dt.$$
I know we have to use Lebesgue-Stieltjes integral here and I don't know how. Here is what I did:
By Carathéodory's extension theorem, there is a unique Borel measure $\mu$ which agrees with $F$ on all intervals.
$$E(X)=\int_{-\infty}^{\infty} tdF(t)=\int_{-\infty}^{\infty} td\mu(t)=\int_{-\infty}^{0} td\mu(t)+\int_{0}^{\infty} td\mu(t).$$ I think next we are going to use $\mu(a,b]=F(b)-F(a)$ but I am not sure how.
Thanks ahead of time!:)

A: You have this.
$$\int_0^\infty t\,d\mu(t) = \int_0^\infty \int_0^t ds\,d\mu(t)
= \int_0^\infty \int_s^\infty d\mu(t)\, ds = \int_0^\infty (1 - F(s))\, ds. $$
Can you deal similarly with the other half?


text:
Q: I used to use sumifs in excel to sum quantities that meet a certain criteria how can i perform the same concept in access? | Fiber1  | Color1  | Weight1|   | Fiber2  | Color2  | Weight2|         | Fiber  | Color  | TOTAL|
|CY-312   | 1  |    | 16 |       |CY-312   | 2 |    | 16 |                CY-312   | 2 |    | ....|
|CY-312   | 1  |    | 15  |      |CY-312   | 1  |    | 15  |
|CY-312   | 2  |    | 15  |      |CY-312   | 2  |    | 15  |

Please help get the total number of CY-312 Color in Access

A: Consider:
SELECT "CY-312" AS Fiber, Count(IIf([Fiber1]="CY-312" And [Color1]=2,1,Null))+Count(IIf([Fiber2]="CY-312" And [Color2]=2,1,Null)) AS Total
FROM Data;

Alternatively, normalize data structure with UNION:
SELECT Fiber1 AS Fiber, Color1 AS Color, Weight1 AS Weight, 1 AS Src FROM Data
UNION ALL SELECT Fiber2, Color2, Weight2, 2 FROM Data;

Then use that query as source for aggregate GROUP BY query:
SELECT Fiber, Color, Count(Src) AS Cnt
FROM Query1
GROUP BY Fiber, Color;


text:
Q: Are compact spaces the only spaces with locally compact continuous images? Let $X$ be a topological space such that for every continuous map $f: X \to Y$, $f(X)$ is locally compact. Must $X$ be compact ?
(It would therefore characterise compact spaces.)
If possible, I would prefer a constructive proof/counterexample.

A: Here is a partial answer:
If $X$ is T2, and each T2-image of $X$ is locally compact, then $X$ is locally compact, normal and countably compact.
Proof.
As was observed by Randall, of course, $X$ is locally compact, hence regular.
(a) $X$ is normal: Let $A, B$ be disjoint, closed subsets of $X$. Consider the quotient space $X/A$, where the points of $A$ are identified. Since $X$ is regular, $X/A$ is T2, hence locally compact, hence regular. The quotient map $\lambda: X \rightarrow X/A$ is closed, hence $\lambda(B)$ is closed in $X/A$. Hence $\lambda(B)$ and the one-point $A$ can be separated in $X/A$, hence $A, B$ can be separated in $X$.
(b) If $X$ is a subspace of the reals, then $X$ is bounded:
(This is essentially the same argument as Engelking 1.4.17.)
Assume not, w.l.o.g let X be unbounded above. Then there is a strictly increasing sequence $(x_n)_{n \in \mathbb{N}}$ in $X$ with $n < x_n$ for all $n$. Hence $A := \{x_n: n \in \mathbb{N}\}$ is closed in $X$. As above, $X/A$ is locally compact, hence has a countable base (see Engelking 3.3.7). In particular, there is an open neighborhood base $(U_n)_{n \in \mathbb{N}}$ of the point $A$ in $X/A$. Again, let $\lambda: X \rightarrow X/A$ be the canonical map.
Let $n \in \mathbb{N}$. There exists $n < u_n \in \lambda^{-1}(U_n) \setminus A$.
[If not, then $A^{>n} = \lambda^{-1}(U_n) \cap \mathbb{R}^{>n}$ is infinite, discrete and clopen in $X$, hence there is a continuous, surjective map $f: X \rightarrow \mathbb{Q}$. Contradiction!]
$B := \{u_n: n \in \mathbb{N}\}$ is closed in $X$, $A \subset X \setminus B$, hence $\lambda(X \setminus B)
$ is an open neighborhood of the point $A \in X/A$. Hence there exists an $n \in \mathbb{N}$ such that $U_n \subset \lambda(X \setminus B)$. Contradiction!
(c) $X$ is pseudocompact: By (a) $X$ is completely regular. Let $f: X \rightarrow \mathbb{R}$ be a continuous map. By (b) $f(X)$ is bounded.
(d) $X$ is countably compact: (a) and (c) (see Engelking 3.10.21).
Remarks:
Note that countably compact, locally compact, normal spaces are quite close to compact spaces.
The standard counter-example is $\omega_1$, which $almost$ fullfills this condition, namely, all completely regular images of $\omega_1$ are locally compact. Would be interesting to know, what's about the other images. I assume that a proof that $\omega_1$ does not fullfill this condition would yield a proof of the OP's assumption. On the other hand, a proof that $\omega_1$ fullfills the condition would then provide a counter-example.


text:
Q: Алгоритм очереди с приоритетом Существует такая задача создания очереди с объектами, которые имеют коэффициенты приоритета.
То есть выборка из этой очереди должна происходить не только того объекта, который первый в очереди но и еще который наиболее достоин.
Первое решение примитивное, которое было реализовано: это создание нескольких очередей (массивов), и первым делом доставание объектов из более приоритетных массивов. Но здесь встала проблема, что сколько бы не стояли в очереди неприоритетные объекты (с низким коэффициентом) если будет много приоритетных то до них очередь никогда не дойдёт или будет доходить очень долго.
Тогда было придумано доставать поочередно сначала самых приоритетных, в след итерации наоборот от меньшего коэффициента к большему (и внутри массивов в порядке очереди).
Но первый способ получается слишком сложным и непонятным. Тогда решил попробовать сделать рандомную выборку из очереди. То есть уже не важно место в очереди, важен лишь коэффициент.
Собирается 1 массив куда дублируются элементы согласно их коэффициенту. Получается, что если у объекта коэффициент 5, то он находится 5 раз в этом массиве. И потом выбирается рандомный индекс из этого массива. И согласно теории вероятности все должны быть довольны в меру своего коэффициента. Но не могу точно понять не будет ли в этом случае кто-то очень долго ждать и стоит ли повышать коэффициент в зависимости от времени, которое находится в очереди. И так как не силён в алгоритмах, не уверен, что это решение точно будет работать.
Буду признателен, если кто-то знает подходящий алгоритм для моей задачи, или же подсказать в правильном ли направлении я двигаюсь.

A: Для того, чтобы малоприоритетные задачи в конце концов обрабатывались, им нужно время от времени повышать приоритет.
В схеме с несколькими очередями можно сделать так. По таймеру выбираете случайным образом очередь с низким приоритетом и перещаете объект из головы этой очереди в хвост очереди со следующим приоритетом. Если у вас N приоритетов, а позиция объекта в очереди своего приоритета n, то в среднем за N*n тактов таймера объект повысит свой приоритет. Это означает, что в конечном итоге каждый объект доберётся до максимального приоритета.
В этом сценарии главный параметр - это длительность такта. Если такт короткий, то малоприоритетные объекты будут быстро "всплывать" и забивать очередь высокоприоритетных. Если такт длинный, то время ожидания малоприоритетных будет слишком велико, и они могут отваливаться по таймауту (если такой есть). Нужно подбирать длительность такта экспериментально.
И общее замечание. Если у вас высокприоритетные объекты поступают слишком быстро, стоить перепроектировать систему и либо добавить вычислительных мощностей, чтобы быстрее обрабатывать их поток, либо как-то ограничить вход. А ещё можно поступить как в блокчейне Эфириума - если клиенты хотят, чтобы их транзакции обработали, пусть платят :)
UPDATE
Как подсказал @avp, приоритет можно повышать не только по таймеру.
Например, каждый раз, когда вы извлекаете объект из очереди, вы повышаете приоритет одному из малоприоритетных объектов.
UPDATE 2
У вашего метода со случайным взвешенным выбором есть несколько недостатоков:

*

*нарушается очерёдность объектов. Как правило, в системах потоковой обработки с приоритетами желательно, чтобы объекты одного приоритета обрабатывались в порядке добавления в очередь. Вместо очереди получается пул.

*нет гарантии, что объект будет обработан. Если сумма весов (вы называете их коэффициентами) объектов равна W, то время, за которое объект минимального приорета, будет обработан с вероятностью 1/2 можно оценить как W*ln(2). Если очеред будет разрастаться, то будет расти суммарный вес W, и время ожидания тоже будет расти. Так как это вероятность, то вероятность того, что объект вообще не будет обработан за время работы программы, ненулевая.
Я бы делал повышение приоритета по таймеру.


text:
Q: AWS reuse IP's in several security groups I have several IP's and I want add access from exactly those IP's to some security groups.
Is there way to declare the IP's once and reuse them in security groups instead of declare those IP's on each security group?

A: There is no way to do an "include" in a security group, including a list of rules by reference.
However, by default, each instance can be a member of up to five security groups, so one common solution is to make each instance a member of two security groups -- one for common rules, and another for rules that are more specific and not shared across all the instances.
Note that it is possible to use a security group ID instead of an IP address in a security group rule, but this has nothing to do with the rules in the referenced group -- it is not an "include."  An inbound rule listing a security group ID allows inbound traffic from instances that are members of the listed group. It does not cause a security group to follow any of the rules in the other group.

A: The accepted answer is no longer true, you can use Prefix Lists to achieve that.
https://docs.aws.amazon.com/vpc/latest/userguide/managed-prefix-lists.html


text:
Q: Unable to get provider com.crashlytics.android.CrashlyticsInitProvider After implementation 'com.google.firebase:firebase-core:16.0.1' and classpath 'com.google.gms:google-services:4.0.1'
I started getting the following error when starting the application:

FATAL EXCEPTION: main
                    Process: com.fentury.android, PID: 10771
                    java.lang.RuntimeException: Unable to get provider com.crashlytics.android.CrashlyticsInitProvider: io.fabric.sdk.android.services.concurrency.UnmetDependencyException: This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,
                    install an Android build tool and ask a team member to invite you to this app's organization.
                        at android.app.ActivityThread.installProvider(ActivityThread.java:5856)
                        at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                        at android.app.ActivityThread.-wrap2(ActivityThread.java)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:154)
                        at android.app.ActivityThread.main(ActivityThread.java:6119)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                     Caused by: io.fabric.sdk.android.services.concurrency.UnmetDependencyException: This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,
                    install an Android build tool and ask a team member to invite you to this app's organization.
                        at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:235)
                        at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:209)
                        at io.fabric.sdk.android.InitializationTask.onPreExecute(InitializationTask.java:44)
                        at io.fabric.sdk.android.services.concurrency.AsyncTask.executeOnExecutor(AsyncTask.java:611)
                        at io.fabric.sdk.android.services.concurrency.PriorityAsyncTask.executeOnExecutor(PriorityAsyncTask.java:43)
                        at io.fabric.sdk.android.Kit.initialize(Kit.java:69)
                        at io.fabric.sdk.android.Fabric.initializeKits(Fabric.java:440)
                        at io.fabric.sdk.android.Fabric.init(Fabric.java:384)
                        at io.fabric.sdk.android.Fabric.setFabric(Fabric.java:342)
                        at io.fabric.sdk.android.Fabric.with(Fabric.java:313)
                        at com.crashlytics.android.CrashlyticsInitProvider.onCreate(CrashlyticsInitProvider.java:27)
                        at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                        at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                        at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                          ... 10 more

Also added in AndroidManifest.xml next line:
<meta-data android:name="firebase_crash_collection_enabled" android:value="false" />

A: If you are going to use other Firebase's API's, I'd suggest to setup crashlytics
As mentioned on Firebase's crashlytics page, here.
And obviously before that you'd need to setup firebase for your app
and create project through firebase console.
I believe you had already done that.
It's because I see small difference in crashlytics setup on these two pages(fabric and firebase).
like on firebase's crashlytics:
in app level gradle
dependencies {
    // ...
    implementation 'com.crashlytics.sdk.android:crashlytics:2.9.3'
}

on fabric:
dependencies {
    // ...
      implementation('com.crashlytics.sdk.android:crashlytics:2.9.4@aar') {
    transitive = true;
  }
}

You won't need to add fabric api key through manifest if you are using with firebase, I think it somehow get connected with firebase key(just guessing).
I'm saying this from my experience, anyone correct me if I'm somewhere wrong.

A: I ran into this issue as well it was caused by using the incorrect Fabric.with() initializer for debug builds.
Don't use:
// Set up Crashlytics, disabled for debug builds
Crashlytics crashlyticsKit = new Crashlytics.Builder()
        .core(new CrashlyticsCore.Builder()
                .disabled(BuildConfig.DEBUG)
                .build())
        .build();

// Initialize Fabric with the debug-disabled Crashlytics
Fabric.with(this, crashlyticsKit, new Crashlytics()); // WRONG!

Instead use:
// Set up Crashlytics, disabled for debug builds
Crashlytics crashlyticsKit = new Crashlytics.Builder()
        .core(new CrashlyticsCore.Builder()
                .disabled(BuildConfig.DEBUG)
                .build())
        .build();

// Initialize Fabric with the debug-disabled Crashlytics
Fabric.with(this, crashlyticsKit); // Correct initializer!

Documentation: https://docs.fabric.io/android/crashlytics/build-tools.html#disable-crashlytics-for-debug-builds

A: This helped to solve my problem
<meta-data
            android:name="firebase_crashlytics_collection_enabled"
            android:value="false" />

And remove this:
<meta-data android:name="firebase_crash_collection_enabled" android:value="false" />

A: I found that the only thing you need to do after following the instruction on the Firebase Crashlytics docs is to apply the fabric plugin in your app build file (This step is actually missing from the docs!).
In your app-level build.gradle add the following
// Apply the Fabric plugin
apply plugin: 'io.fabric'

Edit: It appears that this step has been recently added to the docs (See Step 2 / part 2).

A: In my case I was building app for android 4.4 compatibility which does not have build in Multidex support. I solved the problem by following steps bellow to enable Multidex for android 4.4 and the problem went away:
Enable multidex for apps with over 64K methods
David


text:
Q: x86_64 CPU registers RAX,EAX,AX,AH,AL A 64 bit general purpose register, example:RAX can be accessed via EAX(lower 32 bit), AX(lower 16 bit), AH, AL(b bits). I do have following questions;

*

*Are these (EAX/AX/AH/AL) real physical registers or a mapping/notation to access a part of RAX?

*What is the use of these mapping registers?
I understood if we change EAX/AX/AH/AL this in turn clears the RAX and results in having a new value.
so why do these mapping registers used and under what scenario it is useful.

A: My understanding is based on the transition from 16 to 32 bit so I cant spek for 64 bit stuff specifically but its my understanding that the microprocessor circuitry for al/ah affects only the appropriate 8 bits in the physical register circuitry and that ax is likewise hardwired on the processor to affect only the lower 16 bits. I operate with the presumption that 64 bit architecture works under the same principal although I havent done much research into 64-bit systems to be honest.
A register is of course a pile of transistors laid out in such a fashion that there are 8/16/32/64 lines which represent the bits forming the value in the register. When you read/write to AL, you are reading/writing directly to the AX registers lower 8 lines and the EAX's lower 8 lines and presumably the RAX registers lower 8 lines. Like wise AX to EAX and in all likelihood EAX to RAX.
Virtualisation techniques were introduced in the 90's to allow for 16-bit processing on intel machines operating in 32-bit protected mode using v86 mode which used mapping techniques rather than switching back between real mode and protected mode since the switching incurred significant processing penalties and multi-tasking operating systems could not effectively run both 32-bit programs and 16-bit programs at the same time.
Caveat - Im unfamilliar with writing for 64-bit machines.

A: 1) They're mappings for RAX
2) They mostly exist for backwards compatibility with shorter word-length architectures. They're occasionally useful for bit-twiddling RAX.


text:
Q: Regular expression javascript change value of param in url Using regex, I want to write a function that will replace a get parameter with a new value.
For example the following will replace pin with a new value. If the parameter doesn't exist, we will add it to the url.
  myfunc('http://localhost:8080/signup.html?first_name=Ray&username=ray%2B1%40gmail.com&bid=257&pin=1908554354&provisionalId=258&last_name=Ya&debug=true#/signupnew', 'pin', 'AAAAAAA');

// returns http://localhost:8080/signup.html?first_name=Ray&username=ray%2B1%40gmail.com&bid=257&pin=AAAAAAA&provisionalId=258&last_name=Ya&debug=true#/signupnew

A: You can define the function like this :
function myfunc(url, name, value) {
   return url.replace(new RegExp("(\\?|&)"+name+"=.*?($|&)"), '$1'+name+'='+value+'$2')
}

This suppose the name and values are yet escaped for an URL.
Demonstration (open the console to see the result)


text:
Q: jQuery Menu Animated I want a JQuery menu can any one tell me the code.
I want to make an animated menu placed on right, using jQuery
how it will work:
if i click on a menu (example: ABOUT US) the menu/ the ABOUT US text will moving to HOME and HOME is moving to CONTACT US
so basicly the menu is rotated to left and the selected menu is placed on the center with bigger font.
It should looks like this
===============================================================================
Code Goes here
<link href="style.css" rel="stylesheet" type="text/css"/>

About us

Project

Home

Our Team

Contact Us

And the CSS goes here style.css
body{
font-family: arial;
font-size: 13px;
background: #c9c9c9;}
.clear{
display: block;
clear: both;}
 #wrap{
background: white;
width: 960px;
height:400px;
margin: auto;
padding:10px;}
.text{
padding: 10px;
border: 1px solid #E6E1C8;
background: #F3DDA6;}
 #red{
    background:#069;}
 #navigation{
width: 200px;
float: right;}
 #navigation ul{
list-style: none;}
 #navigation ul li{
height: 30px;
border-bottom: 1px dotted #ccc;}
 #navigation ul li a{
text-indent: 20px;
padding: 5px 0;
display: block;
height: 20px;
text-decoration: none;
color: #434343;
/*background-image: url(bull.png);*/
background-repeat: no-repeat;
background-position: 5px 6px ;
font-weight:bold;}
 #navigation ul li a:hover{
/*background-color: #8E8963;
background-image: url(bull.png);*/
background-repeat: no-repeat;
background-position: 15px 6px ;
/*color: white;*/}
 #footer{
border-bottom: 1px solid #ccc;
border-top: 1px solid #ccc;
text-align: center;}
 #footer img{
border: none;}

And the JQUERY goes here  menu.js
   $(document).ready(function(){
   var Duration = 150;

   $('#navigation ul li a').hover(function()
   {
     $(this).animate({ paddingRight: '20px' }, Duration);
      },
     function() {
      $(this).animate({ paddingRight: '0px' }, Duration);
      });
    });

A: Here is some suggestion for this problem.
I hope you can have the solution from this.
Please make the following changes to your list.

About us

Project

Home

Our Team

Contact Us

and add the following js to your page:
$('#navigation ul li a').click(function () {

    var currentId = $(this).attr('id');

    if (currentId == 'middle') {
        return false;
    } else {
        var Ltext = $('#middle').text();
        $('#middle').text($(this).text());
        $(this).text($('#last').text());
        $('#last').text(Ltext);
    }
});


text:
Q: Could I help users update all the extensions they installed from my extension? I recently developed an extension called Better Extension Manager to provide an alternative of Chrome's extension manager, with some improvement like search and operate on more than one extensions at one time.
Some users advise that it would be better to have a "update all extensions now" option, I couldn't find APIs from the document to do this. Am I missing something?

A: You might be able to do this with a NPAPI plugin but otherwise will have to open a feature request. http://new.crbug.com


text:
Q: How to change JDK version temporarily for mvn I have used the following command to set the java version temporarily
export JAVA_HOME=/etc/alternatives/java_sdk_1.8.0
export PATH=$JAVA_HOME/bin:$PATH

but when i run mvn -v I see it's pointing to java 7
so how to change JAVA_HOME temporarily and see the effect in mvn -v ??

A: I solved by downloading another maven. and running
./mavendir/bin/mvn -v

Now it works fine


text:
Q: Multiple parameters taking up multiple lines in C# I am trying to develop a C# windows form application using visual studio. It connects to a microsoft access database. I have a form that saves data to the database. I have text boxes that I need to link to the database field. My problem is I have a lot of textbox names and values for the textbox to code so I need to do it on multiple lines. I did a search on this site and I see you can use the @ symbol in front of the first set of double quotes which encases the first group of parameters but I am not sure how to deal withe the second group of parameters which is the list of values. It would be something like:
command.CommandText = @"insert into xxx (xx,xx,xx,xx,xx,xx,xx)

but when it gets to
values('" + txt_ID.Text + "','" + txt_Nickname.Text + "')"

I get an error saying

"newline in constant"

and that it expects either a ";" or a "}".
So basically I have to set of parameters that I am trying to code on multiple lines.

A: You should use parameterized queries:
command.CommandText = "INSERT INTO mytable (id, nickname) VALUES (@id, @nickname)";

OleDbParameter[] parameters = new OleDbParameter[2];
parameters[0] = new OleDbParameter("@id", Convert.ToInt32(txt_ID.Text));
parameters[1] = new OleDbParameter("@nickname", txt_Nickname.Text);

command.Parameters.AddRange(parameters);

Keep in mind that the parameters must be added in the same order they appear in the query. OleDb doesn't use the names but only the order.
That is why you could use "?" as placeholders in the query with the exact same result
command.CommandText = "INSERT INTO mytable (id, nickname) VALUES (?, ?)";


text:
Q: Typescript cannot log after tests are done. Did you forget to wait for something async in your test? I have this async function resolveProps which traverse through all nested schema of a given jsonschema (if any) and give me all props in a tree hierarchy
import * as _ from "lodash";
import { loadSchema } from "../loader";

 export type SchemaData = {
  filename: string;
  schemaStorage: SchemaStorageMode;
  isRoot: boolean;
  schemaPath: string;
};

const resolveProps = async (schemaData: SchemaData): Promise<object> => {
  let schemaObj = {};
  // just for e.g.
  schemaObj = {
    child_data: {
      allOf: [
        { $ref: "child_schema_1.json" },
        { type: "object" },
      ],
    },
    ip: {
      allOf: [
        { type: "string" },
        { format: "ipv4" },
      ],
    },
    user: { type: "string" },
    pwd: { type: "string" }
  };

  _.map(schemaObj, async (value, key) => {

    const childSchema = await Promise.all(
      generatePaths(JSON.parse(JSON.stringify(value)), "$ref") // [{"values":"child_schema_1.json"},{"values": ""},{ "values": ""},{ "values": ""}]
        .filter((o) =>
          o.values.includes(".json");
        )
        .map((o) =>
          o.values;
        )
        .map((e) =>
          resolveProps({
            ...schemaData,
            filename: e
          })
        )
    );

    if (!_.isEmpty(childSchema))
     return _.set(
       schemaObj,
       [key],
       _.reduce(childSchema, (acc, e) => ({ ...acc, ...e }))
      )
    else
      return _.set(schemaObj, [key], value);
  });

  return schemaObj;
};

export { resolveProps };

And this is how I am calling it from testcase.
test("validates data successfully", async () => {
  const schemaData: SchemaData = {
    filename: "tc_multilevel_schema_top.json",
    schemaStorage: SchemaStorageMode.FileBased,
    isRoot: true,
    schemaPath: path.join(__dirname, "..", "..", "..", "public", "artifacts"),
  };

  const res = await resolveProps(schemaData);

  // expect(res).toBe({some json object});
});

This works fine without promise , but with promise which eventually I want , not getting the desired res. If I console anything inside my resolveProps I am getting cannot log after tests are done. Did you forget to wait for something async in your test? But its actually consoles the right fulfilled data.
I am guessing missing some basic of promise implementation here.
To evaluate jest for async function I tried below sample testcase and that worked fine
import { promises as fs } from "fs";
import * as path from "path";

export const loadJsonFromFS = async (filename: string, filepath: string) => {
  return JSON.parse(await fs.readFile(path.join(filepath, filename), "utf8"));
};

test("validates data successfully", async () => {
  const res = await loadJsonFromFS(
    "tc_multilevel_schema_top.json",
    path.join(__dirname, "..", "..", "..", "public", "artifacts")
  );
  expect(res).toEqual({some data});
});

A: I am able to resolve it by wrapping the recursive part under a await , when analyzed the issue , figured out everything under recursive part was getting fulfilled post the test execution , so it make sense to add await there and that fixed the issue
await Promise.all(
    _.map(schemaObj, async (value, key) => {
       .....
      })
    )


text:
Q: Sequence Classification with LSTM - Instant overfitting and high variance in validation results. How to procede? I am new here so please forgive me if I missed something in creating an good question. Just tell me and I will add missing information etc. :)
The task is to predict if a damage will occur with sensor data.
So Im training a LSTM network to classify sequences of sensor data into class 1 (damage) and class 2 (no damage). Class 1 means that after the data sequence there was a damage in the system and class 2 means there was no damage after the sequence.
Now I wanted so see if the network would be able to predict a damage ahead of time. So I cut a certain amount of data from the end (i.e. 30 days/ 60 days / ... - the number after "dmgDist" in the legend) Since then the model cant "see" up to the damage but only 1/2/ ... months before it. So in theory if the model can classify these sequences correctly it can predict a damage ahead of time in the given timeframe.
One of the main problems is that the validation results are very different from run to run (with the same settings). So Im already doing multiple runs and average them together to get a more reliable result over all. (In this instance 15 runs with each setting)
Now you see that the Training goes rather well but the validation results is kinda whack. So it would be great to get a bit of guidance from more experienced ML-engineers here.

*

*Is there something I could do to make the results more reliable?

*Do you have a thought on where this stems from? (My guess was not enough samples with a lot of data per sample)

*How do you continue in researching on this? (Important factor: Time. Each run takes between 10 to 20 min so these results already took hours to produce)

The optimal result would be to show that a reliable accuracy >=55% is possible with a distance to the damage of 180 days. (Since 50% is basically guessing). Because that would be a foundation where further research can start with more data etc.
Some information on the data: Sequence Length: 4 years with a data point every 10 minutes. 44 Features. ca. 50 Samples.


text:
Q: Entity Framework 5.0. Something like "any of" Query This is my code from my previous question:
public DateTime GibSomeStartDate(IEnumerable<int> partnerNumbers, DateTime startTime)
{
     var contractsStartDate = from contract in this.databaseContext.Contract
                              where partnerNumbers.Contains(contract.Pnr)
                                 && contract.SomeDateTime >= startTime
                              select contract.SomeDateTime;
}

I hope it will not be flagged or downvoted cause its an another question even though with the same code.
I want to return only contractsStartDate(s) that contains any of partnerNumbers in contract.Pnr.
For example if partnerNumbers are 1, 2, 3 and there are contracts with Pnr 1, 3, 4 and 7 - four contract Instances - than I need contract(s) which have Pnr 1 and 3
With my where partnerNumbers.Contains(contract.Pnr) I check the exact match - and that is not what I want.

*

*the contractsStartDate is of type
System.Data.Entity.Infrastructure.DbQuery

*EF 5.0

*databaseContext is child of System.Data.Entity.DbContext
Updated

*

*Contract is an Entity. Pnr is int property

A: Its work good Sorry!
Why is it happened? Cause I have tetsted it wrong! )


text:
Q: Java: Use of default values public static void main(String[] args) {
    int i;
    System.out.println(i);
}

When I do this, even though the default value of an int is 0, it gives a compile-time error saying the variable i has not been initialized. So, what is the underlying concept here and what is the use of default values of primitives when they cannot help in cases like this?


text:
Q: How to make vertical scroll bar align with a specific  smoothly with jQuery?
...

...
click me

When user clicks,make the vertical srollbar align with
 smoothly
EDIT
Is it doable without other plugins?

A: try smooth anchors plugin
EDIT:
It seems the previous jQuery plugin is not online anymore.
basically what you need is two things:

*

*Create an anchor link

*Use javascript for smoothing the transition

The basic idea is to prevent default click action and animate scroll:
jQuery(document).ready(function($) {
    $(".scroll").click(function(event){
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
    });
});

I can qoute the solution mentioned here as a more generic solution:
Smooth Scrolling: Performs a smooth page scroll to an anchor on the same page using jQuery
$(document).ready(function() {
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
        });
      }
    }
  });

  // use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});

Here is a more comperhensive explanation

A: You will get that smooth scrolling effect from
Animated Scrolling for Same-Page Links