text:
Q: TypeError: only size-1 arrays can be converted to Python scalars (self._linewidth = float(w)) I'm new on python and opencv. Sorry for easy one.
When I run the below code, the given error is such a like that:
TypeError: only size-1 arrays can be converted to Python scalars
import numpy as np
import cv2
from matplotlib import pyplot as plt
import numpy as np

image = cv2.imread('C:\\Users\\abim\\Desktop\\im_pro\\images\\strawberries.jpg')
image.shape

# Convert from BGR to RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

 # Resize to a third of the size
image = cv2.resize(image, None, fx=1/3, fy=1/3)
def show(image):
    # Figure size in inches
    plt.figure(figsize=(15, 15))
    # Show image, with nearest neighbour interpolation
    plt.imshow(image, interpolation='nearest')

show(image)

# Show Red/Green/Blue
images = []
for i in [0, 1, 2]:
    colour = image.copy()
    if i != 0: colour[:,:,0] = 0
    if i != 1: colour[:,:,1] = 0
    if i != 2: colour[:,:,2] = 0
    images.append(colour)
show(np.vstack(images))

def show_rgb_hist(image):
    colours = ('r','g','b')
    for i, c in enumerate(colours):
        plt.figure(figsize=(20, 4))
        histr = cv2.calcHist([image], [i], None, [256], [0, 256])

        if c == 'r':
            colours = [((i/256, 0, 0)) for i in range(0, 256)]
        if c == 'g':
            colours = [((0, i/256, 0)) for i in range(0, 256)]
        if c == 'b':
            colours = [((0, 0, i/256)) for i in range(0, 256)]

        plt.bar(range(0, 256), histr, color=colours, edgecolor=colours, width=1)

        plt.show()

show_rgb_hist(image)

    # Convert from RGB to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
images = []
for i in [0, 1, 2]:
     colour = hsv.copy()
     if i != 0: colour[:,:,0] = 0
     if i != 1: colour[:,:,1] = 255
     if i != 2: colour[:,:,2] = 255
     images.append(colour)

hsv_stack = np.vstack(images)
rgb_stack = cv2.cvtColor(hsv_stack, cv2.COLOR_HSV2RGB)
show(rgb_stack)

matplotlib.rcParams.update({'font.size': 16})
def show_hsv_hist(image):
    # Hue
    plt.figure(figsize=(20, 3))
    histr = cv2.calcHist([image], [0], None, [180], [0, 180])
    plt.xlim([0, 180])
    colours = [colors.hsv_to_rgb((i/180, 1, 0.9)) for i in range(0, 180)]
    plt.bar(range(0, 180), histr, color=colours, edgecolor=colours, width=1)
    plt.title('Hue')

    # Saturation
    plt.figure(figsize=(20, 3))
    histr = cv2.calcHist([image], [1], None, [256], [0, 256])
    plt.xlim([0, 256])
    colours = [colors.hsv_to_rgb((0, i/256, 1)) for i in range(0, 256)]
    plt.bar(range(0, 256), histr, color=colours, edgecolor=colours, width=1)
    plt.title('Saturation')

    # Value
    plt.figure(figsize=(20, 3))
    histr = cv2.calcHist([image], [2], None, [256], [0, 256])
    plt.xlim([0, 256])

    colours = [colors.hsv_to_rgb((0, 1, i/256)) for i in range(0, 256)]
    plt.bar(range(0, 256), histr, color=colours, edgecolor=colours, width=1)
    plt.title('Value')

show_hsv_hist(hsv)

# Blur image slightly
image_blur = cv2.GaussianBlur(image, (7, 7), 0)
show(image_blur)

The error is:
Traceback (most recent call last):
  File "C:\Users\abim\Desktop\im_pro\python\5Aralık.py", line 51, in <module>
    show_rgb_hist(image)
  File "C:\Users\abim\Desktop\im_pro\python\5Aralık.py", line 47, in show_rgb_hist
    plt.bar(range(0, 256), histr, color=colours, edgecolor=colours, width=1)
  File "C:\Users\abim\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\pyplot.py", line 2459, in bar
    **({"data": data} if data is not None else {}), **kwargs)
  File "C:\Users\abim\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\__init__.py", line 1810, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\abim\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\axes\_axes.py", line 2296, in bar
    label='_nolegend_',
  File "C:\Users\abim\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\patches.py", line 658, in __init__
    Patch.__init__(self, **kwargs)
  File "C:\Users\abim\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\patches.py", line 87, in __init__
    self.set_linewidth(linewidth)
  File "C:\Users\abim\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\patches.py", line 348, in set_linewidth
    self._linewidth = float(w)
TypeError: only size-1 arrays can be converted to Python scalars

Could anyone tell me what the problem is? It also works on jupyter notebook but why not on eclipse ide for python and python own idle?
Thanks a lot..

A: pyplot bar API needs an array of "heights" as 2nd argument for plotting bars in y direction but your histogram has more dimensions.
Try below code.
def show_rgb_hist(image):
    colours = ('r','g','b')
    for i, c in enumerate(colours):
        plt.figure(figsize=(20, 4))
        histr = cv2.calcHist([image], [i], None, [256], [0, 256])

        if c == 'r':
            colours = [((i/256, 0, 0)) for i in range(0, 256)]
        if c == 'g':
            colours = [((0, i/256, 0)) for i in range(0, 256)]
        if c == 'b':
            colours = [((0, 0, i/256)) for i in range(0, 256)]

        plt.plot(histr, color=c)

        histList = iter(list(histr)) #Expand to 256 elements
        heights = [x[0] for x in histList] #Compose "height" values
        plt.bar(range(0, 256), heights, color=colours, edgecolor=colours, width=1)

    plt.show()


text:
Q: Excel JavaScript API (ExcelApi1.1) fails when creating a table/range with a large data set (400k-600k rows) returning the error "GeneralException" When using the Excel JavaScript API (ExcelApi1.1) to create a table and add data via a web Excel add-in, using an Excel document in desktop office, the table failed to be created when attempting to add 400k-600k or more rows, returning the error "GeneralException: An internal error has occurred."
Note: When using an Excel document in online office the failure occurs at 20k – 40k or more rows, returning the error "GeneralException: An internal error has occurred."
Initially the implementation of the web Excel Add-in was identical to that provided in the tutorial 'Create an Excel task pane add-in'. But the performance of adding rows (all rows or one at a time) directly to the table was significantly worse. https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/excel-tutorial
Following Microsoft advice on 'Performance optimization using the Excel JavaScript API' the implementation was changed to create a range then add this range to a new table, before call context.sync(). https://github.com/OfficeDev/office-js-docs-pr/blob/master/docs/excel/performance.md
The core of the web Excel Add-in is as follows:
Excel.run(function(context) {

// Temporally suspend the auto calcatuion when you try to do large dataset read/wirte operation
if (Office.context.requirements.isSetSupported('ExcelApi', 1.6)) {
    // Only supported in 1.6 onwards
    context.application.suspendApiCalculationUntilNextSync();
}

const currentWorksheet = context.workbook.worksheets.getActiveWorksheet();

var rowCount = dataValueArray.length;
console.log('data.length=' + rowCount);

var range = currentWorksheet.getRange("A2:I" + (rowCount + 1));
range.values = dataValueArray;

const expensesTable = currentWorksheet.tables.add("A1:I" + (rowCount + 1), true /*hasHeaders*/);
expensesTable.name = "ExpensesTable";

expensesTable.getHeaderRowRange().values = [["Timestamp", "NanoSeconds", "OPCServer", "Source", "Severity", "Message", "Condition", "Category", "SequenceNo"]];

var ret = context.sync().then(function() {
    console.log('staticDataAlarms: context.sync() complete:(s)', + (performance.now() - start) / 1000);
});

return ret;
})

A large number of rows cannot be added, our expectations is for Excel to render tables containing at least 1 million rows, similar to using the 'Get Data' function.
Tests were performed on the following environments:
Excel - Office 2019 32 bit, Version 1903 (Build 11425.20244)
Excel – Office 2016 32 bit, Version 16.0.4738.1000
Excel – Office online, Build 16.0.11615.35054
Also see related Issue: Performance of Excel JavaScript API (ExcelApi1.1) when creating a table/range with a large data set (+50k rows) is slow (5 seconds per 50k rows)

redpajama_set_name: RedPajamaStackExchange


text:
Q: using bitmap, camera capture but occur nullpointerException on android I try camera preview capture on android.
use Bitmap.
but occur NullpointerException
java.lang.NullPointerException
  at kr.co.mytest.test.video.CameraTextureView.getImage(CameraTextureView.java:167)
  at kr.co.mytest.test.video.CameraTextureView.onPreviewFrame(CameraTextureView.java:161)
  at android.hardware.Camera$EventHandler.handleMessage(Camera.java:936)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:136)
  at android.app.ActivityThread.main(ActivityThread.java:5001)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
  at dalvik.system.NativeStart.main(Native Method)

CameraTextureView.class
public class CameraTextureView extends TextureView implements TextureView.SurfaceTextureListener, Camera.PreviewCallback {

   private Camera mCamera;
   private CaptureViewer captureView;
   .
   .
   .
   @Override
   public void onPreviewFrame(byte[] data, Camera camera) {
      Log.d(TAG,"CHECK");

      YuvImage image = new YuvImage(data, 20, 640 ,480, null);

      Rect rect = new Rect(0, 0, 640, 480);
      ByteArrayOutputStream bao = new ByteArrayOutputStream();
      image.compressToJpeg(rect, 100, bao);

      byte[] jpeg = bao.toByteArrary();
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inPreferredConfig = Bitmap.Config.RGB_565;

      Bitmap convertedImage = BitmapFactory.decodeByteArray(jpeg, 0, jpeg.length, options);
      Log.d(TAG, "convertedImage" + convertedImage);  //android.graphics.Bitmap@21ac0b78

      getImage(Bitmap.createScaleBitmap(convertedImage, 480, 360, true)); //nullPointerException
 }

 public void getImage(Bitmap bitmap) {

      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

      captureView.displayImage(bitmap);
 }

CaptureView.class
public class CaptureView extends View {
    private Bitmap mBitmap = null;

    public void displayImage(Bitmap image) {
       mBitmap = Bitmap.createBitmap(image);
       postInvalidate();
    }
}

displayImage is only showing capture image.
why occur nullpointerException?
onPreviewFrameis Called as preview frames are displayed.
how to process occur nullPointerException?
thanks.!


text:
Q: Ask for a reqular expression to remove prefix or suffix from a string in Oracle I want to remove prefix or suffix from a string, the string looked like below:
L-CHGSUP-CDO-BR-NET|MS COORDINATOR X|MS COORDINATOR Z| or
|L-CHGSUP-CDO-BR-NET|MS COORDINATOR X|MS COORDINATOR Z|||
I want to remove delimiter | in the end or beginning of the string and in the final, the string should be looked like this:
L-CHGSUP-CDO-BR-NET|MS COORDINATOR X|MS COORDINATOR Z
So, how to write a regular expression to do this in PLSQL?

A: This regular expression does the job:
select regexp_replace('|L-CHGSUP-CDO-BR-NET|MS COORDINATOR X|MS COORDINATOR Z|||','(^[\|]*)|[\|]*$') from dual

A: As EatÅPeach suggested, you don't need to use a regular expression for this, the built-in TRIM function will do:
select trim('|' from '|L-CHGSUP-CDO-BR-NET|MS COORDINATOR X|MS COORDINATOR Z|||')
from dual;

TRIM('|'FROM'|L-CHGSUP-CDO-BR-NET|MSCOORDINATORX|MSCOORDINATORZ|||')
--------------------------------------------------------------------
L-CHGSUP-CDO-BR-NET|MS COORDINATOR X|MS COORDINATOR Z

Or if you already have the value and want to trim it within PL/SQL (as a contrived example):
set serveroutput on
declare
  old_value varchar2(80);
  new_value varchar2(80);
begin
  old_value := '|L-CHGSUP-CDO-BR-NET|MS COORDINATOR X|MS COORDINATOR Z|||';
  new_value := trim('|' from old_value);
  dbms_output.put_line(new_value);
end;
/

anonymous block completed
L-CHGSUP-CDO-BR-NET|MS COORDINATOR X|MS COORDINATOR Z


text:
Q: jquery.ajax creates non-object error hey there i have this jquery:
var input = JSON.stringify(data); // output: [100.100]
var lines = input.split('.');
var vari1 = lines[0];  // output: [100
var vari2 = lines[1];  // output: 100]

var data = {'x':vari1+"."+vari2};
$.ajax({
    url: "checkAvailability.php",
    type: 'POST',
    data : {data:JSON.stringify(data)},
    success : function(data) {
        alert(data);
    }
});

checkAvailability.php:
$data = $_POST['data'];
$data = json_decode($data,true);

if($availabilityChecker->check_availability($data['x'])) {
    echo json_encode(array("error" => "is ok", "result"=>1));
} else {
    echo json_encode(array("error" => "not ok", "result"=>0));
}

but than i get:
Call to a member function check_availability() on a non-object

for this line:
if($availabilityChecker->check_availability($data['x'])) {

i just want to get this string "100.100" in my check_availability-function, how to do this? greetings

A: in your PHP, it sounds like $availabilityChecker is a simple variable or an array. You're trying to call a method inside that object but it's not one to call. To be an object instance it needs to have something like
$availabilityChecker = new Class();


text:
Q: ChartJS keeps adding one day to X axis. I cannot find a reason. Any suggestion? ChartJS(v 2.2.2) keeps adding 1 empty day to timeline chart. Here is data used for this chart:
line_data:
    data:
        0:[72.73, 71.43, 66.67]
        1:[35.48, 61.11, 42.86]
    labels:
        0:["2017-01-28T00:00:00Z", "2017-01-29T00:00:00Z", "2017-01-30T00:00:00Z"]
        1:["2017-01-25T00:00:00Z", "2017-01-26T00:00:00Z", "2017-01-27T00:00:00Z"]
    series:
        0:"Jan 28 - Jan 30"
        1:"Jan 25 - Jan 27"

And here are settings for xAxes that I pass to ChartJS in my Angular(v1.6.1) directive:
type: 'time',
position: 'bottom',
gridLines: {
    display: false
},
time: {
    unit: 'day',
    unitStepSize: 1,
    displayFormats: {
        day: 'MMM DD',
        hour: 'h:mm A'
    }
}

And Here is chart I am getting:

Any suggestion what's wrong?

A: I managed to solve it by setting the max value for the time scale :
scales: {
    xAxes: [{
        type: 'time',
        time: {
            unit: 'day',
            max: <THE REAL LAST DAY DATE>
        }
    }]
}


text:
Q: Panel loses content when scrolled down I have 2 panels inside one larger panel. The 2 inner panels auto size and the outer panel auto scrolls so that I can scroll down the content of my 2 panels together.
I use the paint event to draw grid lines on my right hand panel and there are label controls on both.
It all works fine (also resizing and being responsive) but when I'm scrolled down something weird happens.
So say I call the things you see when your scrollbar is at the top the initial state. Then when  I scroll down and nothing of this initial state is visible and I resize/minimize/refresh... My right hand panel (with the grid lines and labels) greys out and everything dissapears.
Both the labels and graphics will only come back if I scroll up again and hit the bottom of the initial state.
I know it might be hard to understand but feel free to ask for clarification on anything if you think you might be able to help.

The initial state

After scrolling down and resizing/minimize - restoring...

Everything appears again when I reach something which was in the initial state
The paint event for the right hand panel (although I doubt it'll be of much use)
private void panelPlanning_Paint(object sender, PaintEventArgs e)
    {
        for (int i = 0; i <= sub.Days + 1; i++)
        {
            if (toolStripButtonGrid.CheckState == CheckState.Checked)
            {
                if (vertGrid)
                {
                    if (dashedVert)
                    {
                        Pen blackPen = new Pen(Color.FromArgb(50, 0, 0, 0), 1);
                        blackPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;

                        e.Graphics.DrawLine(blackPen, i * labelDaysWidth, 0, i * labelDaysWidth, panelPlanning.Height);
                    }
                    else
                    {
                        Pen blackPen = new Pen(Color.FromArgb(50, 0, 0, 0), 1);
                        e.Graphics.DrawLine(blackPen, i * labelDaysWidth, 0, i * labelDaysWidth, panelPlanning.Height);
                    }
                }
            }
        }

        for (int i = 0; i < userList.Count; i++)
        {
            if (horGrid && toolStripButtonGrid.CheckState == CheckState.Checked)
            {
                if (dashedHor)
                {
                    Pen blackPen = new Pen(Color.FromArgb(50, 0, 0, 0), 1);
                    blackPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;

                    e.Graphics.DrawLine(blackPen, 0, i * userHeight, panelPlanning.Width, i * userHeight);
                }
                else
                {
                    Pen blackPen = new Pen(Color.FromArgb(50, 0, 0, 0), 1);
                    e.Graphics.DrawLine(blackPen, 0, i * userHeight, panelPlanning.Width, i * userHeight);
                }
            }
        }

        for (int i = 0; i <= sub.Days + 1; i++)
        {
            if (dtPickerStart.Value.AddDays(i) == DateTime.Today)
            {
                Pen blackpen = new Pen(Color.Black, 3);
                e.Graphics.DrawLine(blackpen, i * labelDaysWidth + labelDaysWidth / 2, 0, i * labelDaysWidth + labelDaysWidth / 2, panelPlanning.Height);
            }
        }

        if (userList.Count > 0)
        {
            panelPlanning.Height = userList.Count * userHeight;
            panelUsers.Height = userList.Count * userHeight;
        }
        if (nrResources == 0)
        {
            nrResources = 10;
        }
        userHeight = panel1.Height / nrResources;
    }

EDIT
https://www.dropbox.com/sh/p4k9zilmy5pq6ev/RpBEe05B3j
A boiled down version of the solution giving the same problem.
EDIT 2
I have been able to fix most of the issues. Below is some code I changed (to see what I changed you can see the dropbox link above to compare.
private void this_beginResize(object sender, EventArgs e)
{
    this.ResizeBegin -= new EventHandler(this_beginResize);

    panelPlanning.Paint -= new PaintEventHandler(panelPlanning_Paint);

    this.SuspendLayout();
    SuspendDrawing(panelTimeline);
    SuspendDrawing(panelPipeLine);
    SuspendDrawing(panel1);
}

I used to remove the ResizeEnd event and add it again later. I changed that into the ResizeBegin, since this makes more sense to me.
private void this_SizeChanged(object sender, EventArgs e)
{
    panelTimeline.Controls.Clear();
    sub = dtPickerEnd.Value - dtPickerStart.Value;
    addDayLabels(sub);

    panelUsers.Controls.Clear();
    addUserLabels();

    panelPlanning.Paint += new PaintEventHandler(panelPlanning_Paint);

    ResumeDrawing(panel1);
    ResumeDrawing(panelTimeline);
    ResumeDrawing(panelPipeLine);
    this.ResumeLayout();

    if (userList.Count > 0)
    {
        panelPlanning.Height = userList.Count * userHeight;
        panelUsers.Height = userList.Count * userHeight;
    }
    if (nrResources == 0)
    {
        nrResources = 10;
    }
    userHeight = panel1.Height / nrResources;
    lastPanelHeight = panel1.Height;

    panelPlanning.Controls.Clear();
    addPlanning();

    this.ResizeBegin += new EventHandler(this_beginResize);
}

When the resize is at an end I used to make the planning panel the height of the container panel. This was probably the main reason my content was lost when I scrolled down.
I replaced this with the code from my paint event to calculate the heights. I also assigned a variable lastPanelHeight which keeps track of the panel height for the method below.
Maximize and restore events are called here before they are actually executed, so I need to know what they have to be restored to.
protected override void WndProc(ref Message m)
{
    if (m.Msg == 0x0112) // WM_SYSCOMMAND
    {
        // Check your window state here
        if (m.WParam == new IntPtr(0xF030) || m.WParam == new IntPtr(0xF120)) // Maximize event - SC_MAXIMIZE from Winuser.h
        {
            //Same code as the two above combined but with lastPanelHeight as value to do the calculations with
        }
    }
    base.WndProc(ref m);
}

HOWEVER, I'm still experiencing issues. When I resize and the form gets bigger or I restore the window from maximized or minimized state, the scrollbar acts in a weird way.
When it's all the way down and the form gets bigger it stays at the same height in the panel, thus moving up.
On a restore the scrollbar always goes all the way back to the top.
Any ideas?

A: After an initial improvement (see question EDIT2) I focussed on the scrollbar and got that to work after a while too. The trick is too keep track of the scrollbar value and the panel height before the resize and compute it with the new height after the resize. The scroll position is set like this but the scrollbar would still show in another position. This can be fixed by enabling and disabling the scrollbar. full code (mind that there is code for a maximize and restore too) below.
/// The beginning of a form resize
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void this_beginResize(object sender, EventArgs e)
{
    lastLocation = this.Location;
    this.ResizeBegin -= new EventHandler(this_beginResize);

    panelPlanning.Paint -= new PaintEventHandler(panelPlanning_Paint);
    scrollvalue = panel1.VerticalScroll.Value;
    lastHeight = panel1.Height;

    this.SuspendLayout();
    SuspendDrawing(panelTimeline);
    SuspendDrawing(panelPipeLine);
    SuspendDrawing(panel1);
}

/// <summary>
/// Called when the form is done resizing
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void this_SizeChanged(object sender, EventArgs e)
{
    if (this.Location != lastLocation)
    {
        lastLocation = this.Location;
        return;
    }

    panelTimeline.Controls.Clear();
    sub = dtPickerEnd.Value - dtPickerStart.Value;
    addDayLabels(sub);

    panelUsers.Controls.Clear();
    addUserLabels();

    panelPlanning.Paint += new PaintEventHandler(panelPlanning_Paint);

    ResumeDrawing(panel1);
    ResumeDrawing(panelTimeline);
    ResumeDrawing(panelPipeLine);
    this.ResumeLayout();

    if (userList.Count > 0)
    {
        panelPlanning.Height = userList.Count * userHeight;
        panelUsers.Height = userList.Count * userHeight;
    }
    if (nrResources == 0)
    {
        nrResources = 10;
    }
    userHeight = panel1.Height / nrResources;

    panel1.VerticalScroll.Value = scrollvalue * panel1.Height / lastHeight;
    panel1.VerticalScroll.Enabled = false;

    panelPlanning.Controls.Clear();
    addPlanning();

    this.ResizeBegin += new EventHandler(this_beginResize);

    panel1.VerticalScroll.Enabled = true;
    panel1.VerticalScroll.Value = scrollvalue * panel1.Height / lastHeight;
}

/// <summary>
/// Handles maximize and restore
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
    if (m.Msg == 0x0112) // WM_SYSCOMMAND
    {
        // Check your window state here
        if (m.WParam == new IntPtr(0xF030) || m.WParam == new IntPtr(0xF120)) // Maximize event - SC_MAXIMIZE from Winuser.h
        {
            this.ResizeBegin -= new EventHandler(this_beginResize);

            panelPlanning.Paint -= new PaintEventHandler(panelPlanning_Paint);
            scrollvalue = panel1.VerticalScroll.Value;

            if (panel1.Height != 0)
            {
                lastHeight = panel1.Height;
            }

            this.SuspendLayout();
            SuspendDrawing(panelTimeline);
            SuspendDrawing(panelPipeLine);
            SuspendDrawing(panel1);

            panel1.VerticalScroll.Enabled = false;
        }
    }

    base.WndProc(ref m);

    if (m.Msg == 0x0112) // WM_SYSCOMMAND
    {
        // Check your window state here
        if (m.WParam == new IntPtr(0xF030) || m.WParam == new IntPtr(0xF120)) // Maximize event - SC_MAXIMIZE from Winuser.h
        {
            panelTimeline.Controls.Clear();
            sub = dtPickerEnd.Value - dtPickerStart.Value;
            addDayLabels(sub);

            panelUsers.Controls.Clear();
            addUserLabels();

            panelPlanning.Paint += new PaintEventHandler(panelPlanning_Paint);

            ResumeDrawing(panel1);
            ResumeDrawing(panelTimeline);
            ResumeDrawing(panelPipeLine);
            this.ResumeLayout();

            if (userList.Count > 0)
            {
                panelPlanning.Height = userList.Count * userHeight;
                panelUsers.Height = userList.Count * userHeight;
            }
            if (nrResources == 0)
            {
                nrResources = 10;
            }
            userHeight = panel1.Height / nrResources;

            panel1.VerticalScroll.Value = scrollvalue * panel1.Height / lastHeight;
            panel1.VerticalScroll.Enabled = false;

            panelPlanning.Controls.Clear();
            addPlanning();

            this.ResizeBegin += new EventHandler(this_beginResize);

            panel1.VerticalScroll.Enabled = true;
            panel1.VerticalScroll.Value = scrollvalue * panel1.Height / lastHeight;
        }
    }
}


text:
Q: Why is if/else structure not being utilized in this method? public static String winner(String computer,String user)
{
    String win=" ";
    if (computer=="rock" && user=="scissors")
    {
        win="Computer wins! Rock smashes scissors.";
    }
    else if (computer=="paper" && user=="rock")
    {
        win="Computer wins! Paper wraps rock.";
    }
    else if (computer=="scissors" && user=="paper")
    {
        win="Computer wins! Scissors cuts paper.";
    }
    else if (computer==user)
    {
        win="Tie. No winner";
    }
    else if (user=="rock" && computer=="scissors")
    {
        win="YOU win! Rock smashes scissors.";
    }
    else if (user=="paper" && computer=="rock")
    {
        win="YOU win! Paper wraps rock.";
    }
    else if (user=="scissors" && computer=="paper")
    {
        win="YOU win! Scissors cuts paper.";
    }
    return win;
}

The method receives 2 lower case strings as parameters. I have checked by printing the parameters. I do not understand why my if else statements are not working. I am simply trying to do the possibles out comes of a rock paper scissors game. Thanks for all your help guys.

A: You should compare strings with equals in Java, not ==, or you will be comparing references, not value.
How do I compare strings in Java?


text:
Q: Should i go with angular 2 already? I'm starting a new project for internal use in my company. It won't need to be released sooner than in six months. Is it reasonable to start writing it in Angular 2 or just go with Angular 1? As from their github, they already have made 44% progress reaching beta stage milestone. How much, do you think, Angular 2 API will change until reaching final stage?

A: Angular2 is  not polished, and the APIs will change. So if you plan to do a short, small project , you probably want to stick to Angular1 for a little while. But if you're starting and want to set up a nice base for your projects to come, you could start now using Angular2.

A: comparing to ng-2 to ng-1 the amount of effort needed for ng-2 is very less compared to ng-1. in ng-2 all the directives are removed and i hoe in future ng-2 can be more easy to code and deploy external services . if you are already an ng-1 developer then its good that you can do your project in this


text:
Q: kivy: How to change Switch default from ON/OFF to OPEN/CLOSE or to YES/NO? To be more clearly, I want the text of the Switch changed from On/Off to Open/Close or Yes/No.  I did not find out how to do it. Thanks.

A: You can hack this by changing the background image of the right rectangle in the Switch.
You can make an icon that is 83x32 pixels like the widget.
I Made a very ugly example on sumo an online photoeditor:

Then I saved it as images/icon.jpg
If you want to change the slider too, its 43x32 pixels.
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.switch import Switch

class MyGui(Widget):

    def __init__(self,**kwargs):
        super(MyGui,self).__init__(**kwargs)

        self.switch = Switch()

        self.switch.canvas.children[2].source = "images/icon.jpg" # The slider is the last element, so in that case -> children[-1].source

        self.add_widget(self.switch)

class MyApp(App):

    def build(self):
        return MyGui()

if __name__ == '__main__':
    MyApp().run()

If you want to do this in kv language, you could do like this:
from kivy.lang import Builder

Builder.load_string("""

<MyGui>:
    Switch:
        canvas:
            Color:
                rgb: 1,1,1
            Rectangle:
                source: 'switch.jpg'        # make or download your background jpg
                size: sp(83), sp(32)
                pos: int(self.center_x - sp(41)), int(self.center_y - sp(16))
            Rectangle:
                source: 'switch_slider.jpg' # make or download your slider jpg
                size: sp(43), sp(32)
                pos: int(self.center_x - sp(41) + self.active_norm_pos * sp(41)), int(self.center_y - sp(16))
""")

class MyGui(Widget):
    pass

A: The switch text is sadly not a text but an image. You can find the kv file here. You should be able to provide a different theme (see here) or you can override the class and implement your own rendering (which then displays OPEN/CLOSE) instead of the ON/OFF.

A: If you don't intend to change its whole appearance, you can patch the style.kv and use a little bit of canvas instructions to create a widget of your taste. ^.^
(and it's a lot more flexible than creating image for each different switch, if you don't want to change its color)
from kivy.lang import Builder
from kivy.base import runTouchApp
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<Custom@Switch>:
    values: ['OFF', 'ON']
    canvas:
        Color:
            rgb: 0.2, 0.709, 0.898, 1
        Rectangle:
            size: [sp(41.5), sp(20)]
            pos: [self.center_x - sp(41.5), self.center_y - sp(10)]
        Color:
            rgb: 0.4, 0.4, 0.4, 1
        Rectangle:
            size: [sp(41.5), sp(20)]
            pos: [self.center_x, self.center_y - sp(10)]
    Label:
        text: '[b]{}[/b]'.format(root.values[0])
        markup: True
        font_size: 13
        pos: [root.center_x - sp(70), root.center_y - sp(50)]
    Label:
        color: 0.75, 0.75, 0.75, 1
        text: '[b]{}[/b]'.format(root.values[1])
        markup: True
        font_size: 13
        pos: [root.center_x - sp(30), root.center_y - sp(50)]

<Test>:
    Custom:
    Switch:
    Custom:
        values: ['Yes', 'No']
''')
class Test(BoxLayout): pass
runTouchApp(Test())

A: If you're using @el3in's solution make sure to clarify canvas.after instead of canvas otherwise the original switch image stays on top ;)


text:
Q: Iptables forward all internal traffic I have a VM with an internal interface connected to local LAN. The VM has a working OpenVPN connection to another site. How do I forward all incoming traffic on the local interface through the VPN tunnel with iptables? I'm running an Ubuntu distro.

A: To be able to do a site-to-site VPN with the existing connection, you need to have routing paths via the VPN. Let's say that you're in Site #1 (all things are symmetric, regardless of which is acting as OpenVPN server).

*

*First, you need to be sure that the VM with the VPN connection (that we can call "VPN#1") can reach the remote subnet. This is done by adding a route using OpenVPN configuration

*

*If "VPN#1" is the OpenVPN client, you can either add it in the server using push keyword, or add it locally using route

*If "VPN#1" is the OpenVPN server, you can add it using route, or using an external tool like ip

*Then, you need to be sure that both the "VPN#1" and the remote endpoint has the IP forwarding enabled (add net.ipv4.ip_forward=1 to /etc/sysctl.conf and reload using sysctl -p)

*If VPN#1 is the default gateway, then it's done. If it's not, you need either add a static route for the remote LAN in the default gateway, or you can add a static route on each host of your LAN.

*Check the firewall in VPN#1: it should be configured to allow traffic between LAN and VPN interfaces (see FORWARD chain in filter table using iptables)

If you repeat this on the remote side, everything should work. Use ping and traceroute to debug any issue.

A: OK got it working now. I can RDP the server on the other side from my local LAN. I cannot use smb to access the administrative shares on the windows servers on the other side. This are the IP table rules i used:
/sbin/iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
/sbin/iptables -A FORWARD -i tun0 -o ens160 -m state --state RELATED,ESTABLISHED -j ACCEPT
/sbin/iptables -A FORWARD -i ens160 -o tun0 -j ACCEPT


text:
Q: Чтение и доступ к  бинарным данным в файле Добрый день,
Всю жизнь пользовался perlом для обработки текста и для web, а сейчас возникла задача распотрошить бинарный файл. Опыта в этом никакого, кроме некоторый мутной теории, посему прошу помощь зала.
Есть бинарный файл, формат его мне известен, надо прочитать заголовок и затем уже сам контент. Вот, к примеру, первые 64 байта
0000000 8991 1998 0044 0000 0003 0000 000a 0000
0000010 0004 0000 0100 0000 3edf 0046 0000 0000

Первые два байта это, допустим, size. Затем 2 байта - это Count,  затем 6 байт - Something. Хочу сделать хеш %header, и в него положить в виде $header{'Size'}, $header{'Count'} и т.д.
Как правильно это хранить, и как правильно вообще читать?
A: Смотреть надо в сторону функций pack и unpack
@$header{'Size','Count'} = unpack('ss',$binary_str);

A: Используйте Objdump


text:
Q: Is it correct to pass base class type to enable_shared_from_this? What is the difference between:
TaskImpl : Task, std::enable_shared_from_this<Task>

and
TaskImpl : Task, std::enable_shared_from_this<TaskImpl>

Can they be used interchangeably?


text:
Q: Gamma Photons vs. Muons; Which is more expensive Which one takes more energy to produce?
I ask as I theorize that keeping the plasma in a fusion reactor is very expensive.
Muons, while useful, are too short lived.
Maybe... Keeping the plasma at close but not actually passed the fusion threshold, and a steady gamma laser to push a small section over that edge would be more feasible.
Or heck,  have in the plasma itself trace amount of thorium.

A: A muon has a rest energy of 106 MeV, so it takes this much energy to produce.
Gamma photons are usually defined to be photons with an energy of at least 100 keV. They have been measured up to something like 1000 TeV.
So there are gamma photons a thousand times less energetic than a muon, and also gamma photons billions of times more energetic than a muon.
The plasma in most fusion reactors is contained by magnetic fields, not by particles like muons or radiation like gamma rays.
Some fusion reactors use a completely different approach where strong lasers shine from all directions to heat and confine the plasma, but the photons coming out of these lasers do not need to have gamma-ray energies.


text:
Q: How to get asset images id in android I need to set a list of images in ViewPager. I have a list of images in my asset folder. I grouped the images in seperate folders inside asset like assets/images; assets/images1,...... Now I need to get the id of the images (say images1 alone) in int[] array.
     I got the name of the images(images1) in String[] array. How to get the id of the images in string[]  using their names.

A: You have to put your images in drawable folder to access them. Then you can use this code to get the id of images from their name..
 String yourImageName;
 int resID = getResources().getIdentifier(yourImageName, "drawable", "com.example.yourpackegename.");

A: Create a folder named "drawable" in your project's "res/".
Say you have Images like ...
res/drawable/image,image1,image2,...
In your ACTIVITY, call them by using R.drawable.image,R.drawable.image1,....
"Now I need to get the id of the images (say images1 alone) in int[] array"

You can also store them in Array and also call them by using the "R.drawable.YOUR_IMAGE_NAME" as,
int[] images = {R.drawable.image,R.drawable.image1,R.drawable.image2,R.drawable.image3,....};

Hope this helps.

A: int[] array_images = {
                      R.drawable.image0,
                      R.drawable.image1,
                      R.drawable.image2,
                      R.drawable.image3,
                      R.drawable........,
                      ....
                      };

A: Usually "id" is created only for the images in the resource folder but not for the ones in the asset folder.

A: if you are keeping your image in assets than you have to decode it using asset manager .
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
}

private void init() {
    InputStream is = null;
    ImageView imageView = new ImageView(this);
    ((RelativeLayout)findViewById(R.id.parent)).addView(imageView);
    try {
     is = getAssets().open("ic_launcher.png");//name of image in your asset folder
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = BitmapFactory.decodeStream(is);
    imageView.setImageBitmap(bitmap);

         // if you dont want bitmap  you can use drawable

       // Drawable d = Drawable.createFromStream(is, null);
    //imageView.setImageDrawable(d);

}

}
else keep your images in drawable folder in res and use it using R.drawable.imagename


text:
Q: OOTB web part filter based on user group I have one list with Title and AssignedTo field (Person or Group) that allows only People (not group). I want to show OOTB web part (e.g. List view web part, content query web part etc. anything is accepted) which shows all data of current user group.
E.g. List having 4 items(Title, AssingedTo) as below

*

*Test1 User A

*Test2 User B

*Test3 User C

*Test4 User D

User A,B,C are in one group called "Marketing" and User D in "Sales"
Now User A log in so he can see first 3 items because User A,B,C are in same group.
I am not sure how to fulfill this.

A: *

*Audiences

For showing specific web parts to specific users based on some property you may need to leverage Audiences. In that scenario, only users that share a certain property, e.g. Department will see the given webpart.

*

*Filtering list view

Another option is using [Me] when creating a list view. How exactly it would be used depends on the columns and settings of your list.

*

*People Search

Another option is a filter - based PeopleSearch. Choose local People Results and configure a filter based on the property (e.g. Department):


text:
Q: Validator regex pattern input accept only a number with 2-5 digits I want to validate user's input data with a custom Validator in a JSF application. The data inserted must be a number between 2 and 5 digits.
Facelet
<h:inputText id="num1" label="num1" required="true" size="5" maxlength="5"
styleClass="#{component.valid ? '' : 'validation-failed'}"
value="#{sumaManagedBean.number1}"
requiredMessage="You must enter a value">
<f:validator validatorId="validators.NumberValidator"/>
</h:inputText>
<h:message for="num1" />

ManagedBean
@ManagedBean
@SessionScoped
public class SumaManagedBean implements Serializable
{

    int number1;

    public SumaManagedBean() {
    }

    //Getters and Setters
    public int getNumber1() {
        return number1;
    }

    public void setNumber1(int number1) {
        this.number1 = number1;
    }

    //Methods
}

Validator
@FacesValidator("validators.NumberValidator")
public class NumberValidator implements Validator
{
    private static final String NUMBER_PATTERN = "[0-9]{1,5}";

    private Pattern pattern;
    private Matcher matcher;

    public NumberValidator()
    {
        pattern = Pattern.compile(NUMBER_PATTERN);
    }

    @Override
    public void validate(FacesContext context, UIComponent component,Object value) throws ValidatorException
    {
        String number = value.toString();

        //Only numeric characters
        matcher = pattern.matcher(value.toString());
        if(!matcher.matches())
        {
            FacesMessage msg = new FacesMessage("Only numeric characters");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);

        }
        //Minimum length 2 numbers
        else if((number.length() < 2))
        {
            FacesMessage msg =  new FacesMessage("Minimum length 2 numbers");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }
    }
}

When I insert a one digit number, the validator works properly and shows the message "Minimum length 2 numbers". But when I insert some letters instead of numbers like "eee3", the validator shows the following message: "num1: 'eee3' must be a number between -2147483648 and 2147483647. Example: 9346", when it should show "Only numeric characters".
What am I doing wrong?

A:
But when I insert some letters instead of numbers like "eee3", the validator shows the following message: "num1: 'eee3' must be a number between -2147483648 and 2147483647. Example: 9346"

That's the default conversion error message of JSF builtin IntegerConverter. It will transparently kick in when you bind an input field to a bean property of type Integer or its primitive counterpart int. JSF converters will run before JSF validators. On any conversion error, the validators won't run. In other words, you don't need to validate against that numeric regex pattern at all.
You can customize that converter message via converterMessage attribute.
<h:inputText value="#{bean.integer}" ... converterMessage="Only numeric characters" />

Moreover, that length (range) validation can also be done by JSF builtin <f:validateLongRange>.
<h:inputText value="#{bean.integer}">
    <f:validateLongRange minimum="10" maximum="99999" />
</h:inputText>

Its validator message can be customized via validatorMessage attribute. All in all, your input component can with essential parts look just like this, without any custom validator:
<h:inputText value="#{bean.integer}" maxlength="5" required="true"
    requiredMessage="You must enter a value"
    converterMessage="Only numeric characters"
    validatorMessage="Minimum length 2 numbers">
    <f:validateLongRange minimum="10" maximum="99999" />
</h:inputText>

Unrelated to the concrete problem, doing a value.toString() inside a Validator is bad practice. Don't do that. You're supposed to cast the provided value argument to the actual type as declared in the model (the bean property). You'd then quickly have realized that some parts of your validation was unnecessary.
Integer number = (Integer) value;

And, a Matcher instance is not thread safe. You're not supposed to declare it as an instance variable of a class whose instances could be shared across multiple threads.


text:
Q: ggplot legend disappears when using ggplotly() I am trying to keep a legend which is generated when I use ggplot, but upon applying plotly the legend disappears. Here is my code:
ggplotchange <- ggplot(data = map.world1, aes(x = long, y = lat, group = group, fill = happiness, text  = paste("Country:", region, "
", "Happiness:", -happiness, "
", "Economy:", economy, "
", "Family:", family, "
", "Health:", -health, "
", "Freedom:", -freedom, "
", "Trust:", trust, "
", "Generosity:", generosity))) +
  geom_polygon() +
  scale_fill_gradientn(colors = ocean.curl(150)) +
  theme(
    panel.grid = element_blank(),
    axis.text = element_blank(),
    axis.title = element_blank(),
    axis.ticks = element_blank(),
    legend.title = element_blank(),
    plot.title = element_text(hjust = 0.5)) +
  labs(title = "Change from 2015 to 2022") +
  guides(fill = guide_legend(title=""))
ggplotly(ggplotchange, tooltip = c("text"))

The dput of the map.world1 data is this:
structure(list(long = c(-69.8991241455078, -69.8957061767578,
-69.9421920776367, -70.004150390625, -70.0661163330078, -70.0508804321289
), lat = c(12.4520015716553, 12.4229984283447, 12.4385251998901,
12.50048828125, 12.5469722747803, 12.5970697402954), group = c(1,
1, 1, 1, 1, 1), order = 1:6, region = c("Aruba", "Aruba", "Aruba",
"Aruba", "Aruba", "Aruba"), subregion = c(NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_),
    region.y = c(NA_character_, NA_character_, NA_character_,
    NA_character_, NA_character_, NA_character_), happiness = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), economy = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), family = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), health = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), freedom = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), trust = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), generosity = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_)), row.names = c(NA,
6L), class = "data.frame")

I've attached a photo of what the plot looks like before

A: guides(fill = guide_legend(title="")) seems to be the problematic argument. Removing it will put the legend back in the ggplotly object. However, the legend title is still there (which I assume you want removed since the problematic argument removes the legend title). Additionally, the legend is converted from factor to continuous. This seems to be one of the ongoing issues related to ggplotly() and legends, so I'm not sure if your question has a clean answer.
EDIT: Based on this post, you may have to build your own legend outside of ggplot() using functions and then add that legend to plotly() using layout().
library(tidyverse)
library(plotly)
library(pals) # for ocean.curl()
options(scipen = 999999)

# https://stackoverflow.com/questions/33135060/read-csv-file-hosted-on-google-drive
id <- "1yXECGkwlTjtcmeP2hqRzxFImYp5UbwpT" # google file ID
map.world1 <- dget(sprintf("https://docs.google.com/uc?id=%s&export=download", id))

ggplotchange <- ggplot(data = map.world1, aes(x = long, y = lat, group = group, fill = happiness, text  = paste("Country:", region, "
", "Happiness:", -happiness, "
", "Economy:", economy, "
", "Family:", family, "
", "Health:", -health, "
", "Freedom:", -freedom, "
", "Trust:", trust, "
", "Generosity:", generosity))) +
  geom_polygon() +
  scale_fill_gradientn(colors = ocean.curl(150)) +
  theme(
    panel.grid = element_blank(),
    axis.text = element_blank(),
    axis.title = element_blank(),
    axis.ticks = element_blank(),
    legend.title = element_blank(),
    plot.title = element_text(hjust = 0.5)) +
  labs(title = "Change from 2015 to 2022", color = "")

ggplotly(ggplotchange, tooltip = c("text"))


text:
Q: matrix inverse with modular entries? So I am dealing with a square $nxn$ matrix where the entries are all integers taken modulo $m$, we can assume $m$ to be a prime.  Can we make sense of an inverse of such a matrix?  Assuming of course that the matrix is invertible if we take the entries as real numbers.  And also obviously need to have the entries be invertible mod $m$, are those two things enough? Or would we need to ensure that every single entry we encounter in the process of row reducing is invertible mod $m$?

A: It's a matrix over the ring $\mathbb{Z}_m$, therefore is invertible iff its determinant is an invertible element of the ring, that is, iff $\det(A)$ is coprime to $m$, if $A$ is the matrix in question.


text:
Q: How do I best dump a Psych::Nodes::Document back to a YAML string? This does what I want, but going via to_ruby seems unnecessary:
doc = Psych.parse("foo: 123")
doc.to_ruby.to_yaml
# => "---\nfoo: 123\n"

When I try to do this, I get an error:
DEV 16:49:08 >> Psych.parse("foo: 123").to_yaml
RuntimeError: expected STREAM-START
from /opt/…/lib/ruby/2.5.0/psych/visitors/emitter.rb:42:in `start_mapping'

I get the impression that the input needs to be a stream of some sort, but I don't quite get what incantation I need. Any ideas?
(The problem I'm trying to solve here, by the way (in case you know of a better way) is to fix some YAML that can't be deserialised into Ruby, because it references classes that don't exist. The YAML is quite complex, so I don't want to just search-and-replace in the YAML string. My thinking was that I could use Psych.parse to get a syntax tree, modify that tree, then dump it back into a YAML string.)

A: Figured out the incantation after finding the higher-level docs at https://ruby-doc.org//stdlib-2.3.0_preview1/libdoc/psych/rdoc/Psych/Nodes.html, though please let me know if there's a better way:
doc = Psych.parse("foo: 123")
stream = Psych::Nodes::Stream.new
stream.children << doc
stream.to_yaml
# => "foo: 123\n"


text:
Q: EditText not adding space after word swiped in I have an android phone using googles keyboard. On any EditText field in any other app if I use the swipe method to enter text in, it adds a space after each word. However, I have written my own app and when I use the swipe method to enter text on my EditText field it does NOT add a space sothewordsbleedtogether. This is very annoying.
I have an AlertDialog with a linear view added. On that linear view there is a text EditText. Here is my code to create the EditText and add it to the view:
final EditText titleBox = new EditText(this);
titleBox.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT |
    InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES |
    InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
titleBox.setHint("Title");
layout.addView(titleBox);

Any ideas why its not adding spaces in between my words?
This was marked as a possible duplicate, but that question was about not allowing the first character to be a space....Im asking about allowing a space after words that are entered via a keyboard swipe.
Update
Here is the entire method of similar page, its having the same issue, its slightly less complex then the initial page I was troubleshooting. This one doesn't even have a LinearLayout associated:
private void addBudget(final Budget budget) {
EditText taskEditText = new EditText(this);
        taskEditText.setId(R.id.add_budget_text);
             taskEditText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

String dialogTitle = "Add budget";
final AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(dialogTitle)
                .setMessage("What do you want to call this budget?")
                .setView(taskEditText)
                .setPositiveButton("Save", new    DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // final String task = ;
                        SQLiteDatabase db = mHelper.getWritableDatabase();

                        Budget lBudget = new Budget();
                        if (budget != null) {
                            lBudget = budget;
                        }
                        EditText taskEditText = (EditText) findViewById(R.id.add_budget_text);
                        lBudget.title = String.valueOf(taskEditText.getText());

                        // Init custom budget object //new Budget(){{ title=task; id = budgetID;}}
                        int retId = mHelper.saveBudget(db, lBudget);

                        db.close();
                        int retRow = updateUI(retId);
                        mTaskListView.smoothScrollToPosition(retRow);

                    }
                })
                .setNegativeButton("Cancel", null)
                .create();
// Handle done on soft keyboard
        taskEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                int result = actionId & EditorInfo.IME_MASK_ACTION;
                if (result == EditorInfo.IME_ACTION_DONE) {
                    dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
                    return true;
                }
                return false;
            }
        });
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        dialog.show();

    }

A: I didnt know if you got solved, i just had the same problem today and found a way to solve it.
I saw a "extrange" performance of the swipe, sometimes it showed the "blankspace" and sometimes not.
The way i found to check if it was shown and if it didnt, add it, was this:
        editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            checkCancel();
            int compare = count-before;
            if(compare>1){
                String text = editText.getText().toString();
                String lastChar = (text.substring(text.length()-1,text.length()));
                if(!lastChar.equals(" ")){
                    String plus = text+" ";
                    editText.setText(plus);
                    editText.setSelection(editText.getText().length());
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }

        } );

You can see, onTextChanged can use the variables "before" and "count" and if the compare (difference between last word and current one) is more than 1, it's a word entered by Swipe. Then you can check if the "blankspace" is shown, and if not, just add it and perfom anything you want with it.
Hope it helps!

A: Could you try this? Add the filter into the editText. I used it for enter code on my app.
EditText et = (EditText) findViewById(R.id.edit_text);
et.setFilters(new InputFilter[] {
new InputFilter() {
    @Override
    public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int start, int end {
           if(charSequence.equals("")){
                return charSequence;
           }
           if(charSequence.toString().matches("[a-zA-Z ]+")){
                return charSequence;
           }
           return "";
        }
    }
});

A: So I uninstalled the google keyboard and reinstalled and I changed the build to release. One of those two things fixed it.


text:
Q: How to ignore external list in case of lists in list(without using Numpy) I writing a function that its input is-  image_one, image_two, mask).
This function outputs a new image by calculating every new pixel according to the formula-
new_image[i][j] = round(image_one[i][j] x mask[i][j] + image_two[i][j] x (1 - mask[i][j]))

I wrote until now-
def image_plus_mask(image_one, image_two, mask):
    hight = len(image_one)
    width = len(image_one[0])
    new_image = [[0 for _ in range(width)] for _ in range(hight)]

    for i in range(hight):
        for j in range(width):
            new_image[i][j] = round((image_one[i][j] * mask[i][j]) + (image_two[i][j] * (1-mask[i][j])))
    return new_image

The function dose work on double lists.
For example:
Input-
image_plus_mask([[50, 50, 50]], [[200, 200, 200]], [[0, 0.5, 1]])

Output(as expected)-
[[200, 125, 50]]

The problem is that it is not working on 3 lists, and I need it to work on both- 2 and 3 lists.(by 2 I mean-[[]], by 3 I mean- [[[]]])
For example-
Input-
image_plus_mask([[[1,2,3], [4,5,6]],[[7,8,9],[10,11,12]]],
[[[250,250,250], [0,0,0]],[[250,250,100],[1,11,13]]],[[0,0.5]]*2))

Expected Output-
[[[250, 250, 250,], [2,2,3]], [[250, 250, 100], [6, 11, 12]]]

What can I do?

A: Like in the comments said:
def image_plus_mask(image_one, image_two, mask):

    hight = len(image_one)
    width = len(image_one[0])

    #case: 3 lists
    if isinstance(image_one[0][0], (list,tuple)):
        depth = len(image_one[0][0])
        new_image = [[[0 for _ in range(depth)] for _ in range(width)] for _ in range(hight)]
        print(new_image)
        for i in range(hight):
            for j in range(width):
                for k in range(depth):
                    new_image[i][j][k] = round((image_one[i][j][k] * mask[i][j]) + (image_two[i][j][k] * (1-mask[i][j])))

    #case: 2 lists
    else:
        new_image = [[0 for _ in range(width)] for _ in range(hight)]
        for i in range(hight):
            for j in range(width):
                new_image[i][j] = round((image_one[i][j] * mask[i][j]) + (image_two[i][j] * (1-mask[i][j])))

    return new_image

you need to adjust your shape of new_image. Look at your expected Output for 3 lists and look inside the function what you define for new_image. Couldn't work.
Output now:
res1 = image_plus_mask([[[1,2,3], [4,5,6]],[[7,8,9],[10,11,12]]],
[[[250,250,250], [0,0,0]],[[250,250,100],[1,11,13]]],[[0,0.5]]*2)

res2 = image_plus_mask([[50, 50, 50]], [[200, 200, 200]], [[0, 0.5, 1]])

print(res1)
[[[250, 250, 250], [2, 2, 3]], [[250, 250, 100], [6, 11, 12]]]

print(res2)
[[200, 125, 50]]

A: Your mask has to be the same shape as your inputs.
If it is different then the image_one[i][j] * mask[i][j] will not work.
I highly suggest you using numpy arrays like this:
image1 = np.array([[50, 50, 50]])
image2 = np.array([[200, 200, 200]])
mask = np.array([[0, 0.5, 1]])

output = np.round(image1 * mask + image2 * (1 - mask))

print(output)

Output:
[[200. 125.  50.]]

If the shape of your inputs (images and mask) is consistent this will give what you want with any dimensions.


text:
Q: matlab - winopen(), reading from the keyboard in fullscreem window hi all
I wrote a short program that runs an avi file and records input from the keybpard while the avi is displaying. the problem is this. if the movie is in fill screen the program doesn't take the input from the keyboard. it takes the input only if the movie is minimizd.
this is my code

>
  close all
  clc
  winopen('c:/optic2.avi')
  RT=[]
  for i=1:1:5
      tic
      count=input('');
      RT(i)=toc
  end
  xlswrite('c:/GS.xls',RT)

any ideas?
thanks

A: I usend KbChack from the psychtoolbox.


text:
Q: how to output into a tree like structure via Tree::DAG_Node? I'm trying to write a program that can read from a file then put into a heap sort then output in a tree along with the sorted list. But I got stuck, instead of having the put be the numbers used in the heap sort, it just post 1-10 on one line then 1-9 on the next line. I'm really confused and I barely understand this language as it is. I put a example of the out below alone with the output I am hoping to have it draw.
#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
use Tree::DAG_Node;

process_data(read_file('testing.txt'));
process_data((3,1,4,1,5,9,2,6,5,3,6));

sub read_file{
    my($filename)=@_;
    my @data=();
    my @words;
    open(my $fh, "<", $filename)
        or die "Could not open file: $!\n";
    while(<$fh>){
    chomp;
    @words = split(' ');
    foreach my $word(@words){
    push @data, $word;
}

}
close $fh;

return @data;
}

sub heap_sort {
    my ($a) = @_;
    my $n = @$a;
    for (my $i = ($n - 2) / 2; $i >= 0; $i--) {
        down_heap($a, $n, $i);
    }
    for (my $i = 0; $i < $n; $i++) {
        my $t = $a->[$n - $i - 1];
        $a->[$n - $i - 1] = $a->[0];
        $a->[0] = $t;
        down_heap($a, $n - $i - 1, 0);
    }
}

sub down_heap {
    my ($a, $n, $i) = @_;
    while (1) {
        my $j = max($a, $n, $i, 2 * $i + 1, 2 * $i + 2);
        last if $j == $i;
        my $t = $a->[$i];
        $a->[$i] = $a->[$j];
        $a->[$j] = $t;
        $i = $j;
    }

sub max {
    my ($a, $n, $i, $j, $k) = @_;
    my $m = $i;
    $m = $j if $j < $n && $a->[$j] > $a->[$m];
    $m = $k if $k < $n && $a->[$k] > $a->[$m];
    return $m;
}
}

sub draw_tree{
    my(@data)=@_;
    my $root = Tree::DAG_Node->new;
$root->name($_[0]);
$root->new_daughter->name($_) for (1..10);
my @names = @data;
my $count = 50;
for my $n ($root->daughters) {
    for (split //, $names[$count++]) {
        $n->new_daughter->name($_)
    }
}
print map "$_\n", @{$root->draw_ascii_tree};
}

sub process_data{
    my(@data)=@_;
    my @a = @data;
    print "@a\n";
    print "\n";
    heap_sort(\@a);
    draw_tree(@a);
    print "\n";
    print "@a\n";
    print "\n";

}

here is the output I get
CMD output of my code
Output I am expecting:
(using example data)
1 1 9 4 5
   1
   |
 1 ----- 9
 |
 /\
4 5

1 1 4 5 9


text:
Q: How to save an image in a directory named on the User? I am using Django2.2 and I am currently learning Django. I have created a model where I have to post an image of a certain thing and that model is connected with a User. I want to save the image on a directory named on that certain user
I have a custom User Model where I created a field called Profile Photo and that profile photo is saved to a directory named on that User.But then I created another application called 'Product' and there I created many fields including an image field.I am trying to save that image on that directory named on that specific User.
def user_directory_path(instance, filename):
   return 'media/%s/%s' % (instance.username, filename)

 class Products(models.Model):
   title = models.CharField(max_length=100)
   body = models.CharField(max_length=1000)
   image = models.ImageField(upload_to = user_directory_path)
   product_user = models.ForeignKey(User, on_delete=models.CASCADE)

   def __str__(self):
         return self.title

When I try to save a Product and error occurs.
'Products' object has no attribute 'username'

Is there any successful ways to do it.

A: A Products instance indeed has no username attribute. The product_user has, you thus can change this to:
def user_directory_path(instance, filename):
   return 'media/%s/%s' % (instance.product_user.username, filename)

Note: models have usually singular names, so Product, instead of Products.


text:
Q: Finding duplicate entries in Collection Is there a tool or library to find duplicate entries in a Collection according to specific criteria that can be implemented?

To make myself clear: I want to compare the entries to each other according to specific criteria. So I think a Predicate returning just true or false isn't enough.

I can't use equals.

A: It depends on the semantic of the criterion:
If your criterion is always the same for a given class, and is inherent to the underlying concept, you should just implement equals and hashCode and use a set.
If your criterion depend on the context, org.apache.commons.collections.CollectionUtils.select(java.util.Collection, org.apache.commons.collections.Predicate) might be the right solution for you.

A: If you want to find duplicates, rather than just removing them, one approach would be to throw the Collection into an array, sort the array via a Comparator that implements your criteria, then linearly walk through the array, looking for adjacent duplicates.
Here's a sketch (not tested):
   MyComparator myComparator = new MyComparator();
   MyType[] myArray = myList.toArray();
   Arrays.sort( myArray, myComparator );
   for ( int i = 1; i < myArray.length; ++i ) {
      if ( 0 == myComparator.compare( myArray[i - 1], myArray[i] )) {
         // Found a duplicate!
      }
   }

Edit: From your comment, you just want to know if there are duplicates. The approach above works for this too. But you could more simply just create a java.util.SortedSet with a custom Comparator. Here's a sketch:
   MyComparator myComparator = new MyComparator();
   TreeSet treeSet = new TreeSet( myComparator );
   treeSet.addAll( myCollection );
   boolean containsDuplicates = (treeSet.size() != myCollection.size());

A: You can adapt a Java set to search for duplicates among objects of an arbitrary type: wrap your target class in a private wrapper that evaluates equality based on your criteria, and construct a set of wrappers.
Here is a somewhat lengthy example that illustrates the technique. It considers two people with the same first name to be equal, and so it detects three duplicates in the array of five objects.
import java.util.*;
import java.lang.*;

class Main {
    static class Person {
        private String first;
        private String last;
        public String getFirst() {return first;}
        public String getLast() {return last;}
        public Person(String f, String l) {
            first = f;
            last = l;
        }
        public String toString() {
            return first+" "+last;
        }
    }
    public static void main (String[] args) throws java.lang.Exception {
        List<Person> people = new ArrayList<Person>();
        people.add(new Person("John", "Smith"));
        people.add(new Person("John", "Scott"));
        people.add(new Person("Jack", "First"));
        people.add(new Person("John", "Walker"));
        people.add(new Person("Jack", "Black"));
        Set<Object> seen = new HashSet<Object>();
        for (Person p : people) {
            final Person thisPerson = p;
            class Wrap {
                public int hashCode() { return thisPerson.getFirst().hashCode(); }
                public boolean equals(Object o) {
                    Wrap other = (Wrap)o;
                    return other.wrapped().getFirst().equals(thisPerson.getFirst());
                }
                public Person wrapped() { return thisPerson; }
            };
            Wrap wrap = new Wrap();
            if (seen.add(wrap)) {
                System.out.println(p + " is new");
            } else {
                System.out.println(p + " is a duplicate");
            }
        }
    }
}

You can play with this example on ideone [link].

A: You could use a map and while iterating over the collection put the elements into the map (the predicates would form the key) and if there's already an entry you've found a duplicate.
For more information see here: Finding duplicates in a collection

A: I've created a new interface akin to the IEqualityComparer<T> interface in .NET.
Such a EqualityComparator<T> I then pass to the following method which detects duplicates.
public static <T> boolean hasDuplicates(Collection<T> collection,
        EqualsComparator<T> equalsComparator) {
    List<T> list = new ArrayList<>(collection);
    for (int i = 0; i < list.size(); i++) {
        T object1 = list.get(i);
        for (int j = (i + 1); j < list.size(); j++) {
            T object2 = list.get(j);
            if (object1 == object2
                    || equalsComparator.equals(object1, object2)) {
                return true;
            }
        }
    }
    return false;
}

This way I can customise the comparison to my needs.

A: Treeset allows you to do this easily:
Set uniqueItems = new TreeSet<>(yourComparator);
List<?> duplicates = objects.stream().filter(o -> !uniqueItems.add(o)).collect(Collectors.toList());

yourComarator is used when calling uniqueItems.add(o), which adds the item to the set and returns true if the item is unique. If the comparator considers the item a duplicate, add(o) will return false.
Note that the item's equals method must be consistent with yourComarator as per the TreeSet documentation for this to work.

A: Iterate the ArrayList which contains duplicates and add them to the HashSet. When the add method returns false in the HashSet just log the duplicate to the console.


text:
Q: AVAudioEngine Input Mic Tap influences Music PlayerNode - SWIFT I am creating an app that lets the user talk into the microphone while music is playing (similar to Karaoke). I have managed to get this working using the AudioEngine with multiple inputs going into the mixer. However, when the mic is enabled, the sound quality of the music is also lost. It almost sounds like the music is being payed through the microphone. I figure this is due to the mic and music having different AVAudioFormats, but I cannot find a format that works for the mic other than:
var format = AVAudioFormat(commonFormat: AVAudioCommonFormat.PCMFormatFloat32, sampleRate: 8000.0, channels:AVAudioChannelCount(2), interleaved: false)

where my music output format is simply
mixer.outputFormatForBus(0)

which sounds clear when the mic is disabled.
it is worth noting I am also using the AvAudioSessionCategory:
session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions:AVAudioSessionCategoryOptions.AllowBluetooth, error: nil)

I have run out of ideas as to what I am doing wrong. Any help is greatly appreciated!

A: Need to see more of your code, mainly how you have setup your input and output in AVAudioSession.
Don't know from your description what your input or output setup is. For iPhone you have 3 input mics (front, back & bottom) and 2 outputs (receiver (ear) & speaker (bottom)). If you have input set to bottom mic, then very likely the output is set to receiver which is meant to be held to ear.


text:
Q: Performance tuning on INNER JOIN with BETWEEN Condition I have two table's namely tbl_Small and tbl_Large.
Both the table's I have stored in Microsoft Azure and querying from Microsoft SQL Server.
--Table 1: Tbl_Small
CREATE TABLE tbl_Small
(
    cola int
);

INSERT INTO tbl_Small VALUES(1234),(123),(34);
--1000 rows

--Table 2: tbl_Large
CREATE TABLE tbl_Large
(
    ID bigint identity(1,1),
    cola int,
    colb int,
    colc varchar(100)
);

INSERT INTO tbl_Large(cola,colb,colc) VALUES(0,140,'A'),(150,200,'C'),(1000,15000,'D');
--30 million rows

I want to get large table details by joining small table with between condition.
My try:

*

*Created NONCLUSTERED index on tbl_Small(cola).

*Created NONCLUSTERED index on tbl_Large(cola) and tbl_Large(colb).

Query:
SELECT s.cola as [Input],l.cola,l.colb,l.colc
FROM tbl_Large AS l
INNER JOIN tbl_Small s ON s.cola BETWEEN l.cola and l.colb

Note: The above query's execution time is over 10 minutes.
Edit: After adding nonclustered index on all columns as said in answer, I got the following execution plan.
Time taken for execution: 5 min

DTU Percentage graph:

A: Your index on tbl_Large needs to be covering i.e. it holds all the data the query needs. If you just create an index on the one column then to get all the data the server will need to use the index and another source to get the other column data. It's probable it won't find it worth the extra work and will ignore the index all together.
For tbl_Large create an index on both col a and col b and also include the value for col c so the code looks like this:
CREATE NONCLUSTERED INDEX IX_tbl_Large_cola_colb on tbl_Large (cola, colb)
INCLUDE (colc)


text:
Q: Combo box to list Macros I want when you hit 'send' you are presented with a form. This I am developing in Outlook 2010.
Is there a way to populate a combo-box with a list of Macros?
Public Sub Confidential()
    Application.ActiveInspector.CurrentItem.Sensitivity = olConfidential
    Application.ActiveInspector.CurrentItem.Save
    Set MsgSub = Outlook.Application.ActiveInspector.CurrentItem
    Set objMail = Outlook.Application.ActiveInspector.CurrentItem
    Subject = MsgSub.Subject
    MsgSub.Subject = Subject + " - [CONFIDENTIAL]"
    Email = objMail.HTMLBody
    info = "

 AUTO TEXT: This message has been marked as 'CONFIDENTIAL' please treat it as such   "
    objMail.HTMLBody = Email + info
End Sub

Private Sub Sens_DropButtonClick()
    Sens.AddItem "Confidential()"
    Sens.AddItem "Normal()"
End Sub

Public Sub Send_Click()
    Set objMail = Outlook.Application.ActiveInspector.CurrentItem
    objMail.Send
End Sub

Would I be right in thinking that this is a public sub?
My goal is when you hit the 'send' button a form will appear with a dropdown box, this has 4 options which are the sensitivity options you can use with the emails, except I have created them as macros and added code on them (to add to subject and footer of message) but I wont it so a user is forced to make a selection, hence why I am creating this form instead of having the 4 buttons.

A:
My goal is when you hit the 'send' button a form will appear with a dropdown box, this has 4 options which are the sensitivity options you can use with the emails, except I have created them as macros and added code on them (to add to subject and footer of message) but I wont it so a user is forced to make a selection, hence why I am creating this form instead of having the 4 buttons. – Rsmithy 36 mins ago

If I understand you correctly, Yes it is possible to do what you want. See this Example
Let's say you have a userform with 4 options A,B,C and D and the userform code is
Private Sub UserForm_Initialize()
    ComboBox1.AddItem "A"
    ComboBox1.AddItem "B"
    ComboBox1.AddItem "C"
    ComboBox1.AddItem "D"
End Sub

Private Sub CommandButton1_Click()
    lstNo = ComboBox1.ListIndex
    Unload Me
End Sub

Next Paste this in a module
Public lstNo As Long

and this in the ThisOutlookSession
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    UserForm1.Show

    MsgBox "user chose " & lstNo & "from combo"

    Select Case lstNo
    Case -1
        'User didn't select anything in the combo
    Case 0
        'User selected option 1 in the combo
    Case 1
        'User selected option 2 in the combo
    Case 2
        'User selected option 3 in the combo
    Case 3
        'User selected option 4 in the combo
    End Select
End Sub

Replace the above comments in the Select Statement` with the Macro Names that you want executed depending on the user choice.
SNAPSHOTS IN ACTION

And this is what you get when you select the Option D (ListIndex 3)

FOLLOWUP
Dim email As String, info As String

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    UserForm1.Show

    Select Case lstNo
        Case -1
            'User didn't select anything, default will be used
        Case 0
            With Item
                .Sensitivity = olNormal
                .Save
            End With
        Case 1
            With Item
                .Sensitivity = olPersonal
                .Save
            End With
        Case 2
            With Item
                .Sensitivity = olPrivate
                .Save
            End With
        Case 3
            With Item
                .Sensitivity = olConfidential
                .Subject = .Subject & " - [CONFIDENTIAL]"
                Email = .HTMLBody
                info = "

 AUTO TEXT: " & _
                "This message has been marked as 'CONFIDENTIAL' please treat it as such   "
                .HTMLBody = Email & info
                .Save
            End With
    End Select
End Sub

A:
Is there a way to populate a combo-box with a list of Macros?

Not in Outlook, I'm afraid. Programmatic access to the VBA IDE isn't supported in Outlook due to the possibility of spreading viruses or conducting malicious activity via email.
See VBA Extensibility in Outlook for reference.
The closest you can come is by programmatically displaying the "Run Macro" dialog, like this:
ActiveExplorer.CommandBars.FindControl(,186).Execute
However I'm not sure if this is available in Outlook 2010.
But showing a dialog box can't possibly be your goal. Maybe if you explain what your goal is, someone can suggest a better way of reaching it that doesn't require populating a combo box with a list of macro names.


text:
Q: are "all-male" and "all-female" opposites of androgynous? In the book The Left Hand of Darkness by Ursula K. Le Guin, the residents of a planet are all androgynous. Then a male human, named "Genly", arrives to this planet. I am looking for a word for his sexuality in comparison to the androgynes.
If a society has both females and males, can we call the women "all-female" when compared to androgynes?

A: The antonym of an androgenous species is either "dioecious" (from the Greek of "two households") or gonochoric (from the Greek for "dispersed offspring").  These are technical terms in biology referring to sexual organs, and they can apply to species, colonies, or individuals.  Go here for details.
You can also say that individuals are "unisexual" or "hermaphroditic."  When we speak of persons whose sex is unambiguous, we use either "female" or "male."
Note that most human beings have both a sexual identity (XX=female and XY=male chromosomal configurations) and the corresponding gender identity (i.e., which they consider themselves).  But small percentages have unusual chromosomal makeups, and a somewhat larger percentage don't feel the usual gender identification.  Human sexual characteristics are more complicated that those of plants making even physical identification difficult.  This is to say that for people, "androgynous" may encompass more traits, physical and psychological than the reproductive.


text:
Q: mapping two tables into one java object using hibernate xml mapping I want to have a single java object that is mapped to 2 database tables using Hibernate XML mapping.
Table1 columns: (id, row_num, t1c1)

Table2 columns: (id, row_num, t2c1)

I want to have a java object with below attributes:
id, row_num, t1c1, t2c1
Most of the example I find with one-to-one relation, is one object containing the other as a sub-object:
example1
example2
I wonder if I can join the two tables in the XML mapping (The mapping has to work for read/write).


text:
Q: Anonymous Inner Classes: When are they (in)appropriate? Take the following example. There's an object I want to use, call it a Doodad. Doodad elements have poorly implemented handling of browser events. Typical instantiation of a Doodad would be Doodad someDoodad = new Doodad();. Obviously this isn't suiting my needs because of the poor event handling. Is it appropriate for me to override the onBrowserEvent() method, like so:
Doodad someDoodad = new Doodad() {
@Override
  public void onBrowserEvent(Event event) {
      switch (DOM.eventGetType(event)) {
          case Event.ONDBLCLICK:
          case Event.ONFOCUS:
          case Event.ONCLICK:
              if (!isEnabled()) {
                  return;
              }
              break;
      }
      super.onBrowserEvent(event);
  }
};

Obviously this is a simple example, but when might I not want to use an anonymous inner class? Is it ever explicitly disallowed or impossible?
I'm seeing lots of answers to the first question, but none of the answers so far answer the second: Is it ever explicitly disallowed or impossible to use an anonymous inner class?

A: Typically the best usage of anonymous inner classes is when you want to create only one instance of specific implementation of this class. And when the implementation is pretty simple. Ideally it should contain 1-2 lines of code.
In your case it is still OK although your method onBrowserEvent() is longer than 2 lines.

A: Anonymous inner classes is Java's syntax for creating closures.  Here's an approximate example:
interface Adder {
  int add(int arg);
}

...

Adder createAdder(int n) {
   final int nf = n;
   return new Adder() {
       int add(int arg) { return arg + nf; }
   }
}

Method createAdder creates what essentially is a function using a closure to capture the passed value n.  Closures are important in functional programming which is trying to make it into mainstream.  This is why everyone is screaming that we need "real" closures in Java (i.e. mostly better syntax than in my example).
(Of course I'm not answering the question asked; I think what I'm saying is that anonymous classes are good for what I described above. for almost everything else I would create a named inner class because if anything name is self-documenting and is in my opinion easier to read)

A: Often, an event listener is a piece of code that is not very generic, but is tied to a specific widget, a button, a text-field, whatever. In such a case, the code does not need to be properly exposed for the world to reuse it. It is easier to define it where it is used, in place, and that's what anonymous inner classes are for. They allow to quickly embed pieces of code inside another method, without having to worry about class names, packages, visibility, or re-usability.
Of course, what you can do with anonymous inner classes can always be done with proper stand-alone classes. But it makes more sense to do it this way when your event handling class is generic enough (can handle lots of events), is reusable, is stateful, or more generally when there is some benefit from extracting the event management code from the code that defines the event-generating element.
I'm not sure I understand specifically your question, I hope this piece of info will help you find your answer. Do not hesitate to ask further questions.

A: I would suggest anonymous classes when it implements one method and/or is half a screen full.
If the anonymous has non trival piece of code its worth having a named class IMHO.

A: My take:
Anonymous inner classes: Callback from one function (so you don't write the code twice)
Named inner classes: Callbacks from several functions (or a class that you need only for the internal logic of the parent class)

A: I only use an anonymous inner class when it contains a very small amount of code. Reason is IMO it clutters up the code and makes it less readable.
If there is more code required, I prefer to create a new class, extending the base class (in this case 'Doodad()'

A: In your example you would want to create a separate class. This is because of the reason why you are overriding the method. That is, there is poor handling for browser events.
Specifically, you may want to create these improved Doodads in a couple of different places. And what happens if the event handling is updated and improved in the future? You'll want to remove all of these improved Doodads and use the proper implementation. Trying to find all your anonymous Doodads may be tiresome or tricky. Whereas if you have a separate named class then refactoring out this class will be easy.
In addition the reason for your improving the Doodad can be self documenting if you create a separate class for it. Whereas if you just have an anonymous class then you will have to write comments or leave future maintainers guessing why you've done what you've done.
eg.
public class ImprovedBrowserEventHandlingDoodad extends Doodad {
    ...
}

Anything that resembles a closure is normally a good candidate for using an anonymous class
eg.
new Thread(new Runnable() {
    @Override
    public void run() {
        doSomething();
    }
}).start();

You only want to do something in this one specific set of circumstances and there is no need to copy and paste the code somewhere else or to refactor it into a method.
Event handlers for GUIs are typical in using anonymous classes because their use is limited to the how the GUI is designed and there is no need to create a separate instance of the event handler outside the specific component that is using it. For instance, when you mouse over a scroll bar its appearance generally changes. Nothing else in the program will cause this change and typically the event handler will be a couple of lines telling the scrollbar to change its appearance eg. scrollbar.setMouseOverEffect(true);.


text:
Q: icCube with incremental rows Inserted/Updated/Deleted Our web application manages Employee entries on their own activities, and will show dashboards with isCube.
During the day, all the Employee will have to insert data on web application, and the dashboards will have to show real data, every time that incremental load will be scheduled.
All Employee will insert details of their own activity during the day, what they do, the projects on which they worked, the output they produced (for example how many insurance policy they have done) and so on.
During the day it is possible that Employee will have to update and delete their own datas.
So this is the reason why we would like to have incremental rows Inserted/Updated/Deleted.
Is there a way to do this or we have to schedule Full Load during the night?
Thank you
BR
Maria

A: This is not really a development questions, better to handle this in the standard icCube forum


text:
Q: Loading ResourceDictionary in code behind in UWP/C++ I'm trying to load, in runtime, ResourceDictionary that is stored in a file. In C# it looks simply as
ResourceDictionary resourceDictionary = new ResourceDictionary();
resourceDictionary.Source = new Uri("ms-appx:///!UWP/Styles/UWPDictionary.xaml", UriKind.Relative);
Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);

but same code (in c++/cx) is not working:
auto rd = ref new ResourceDictionary();
rd->Source = ref new Uri("ms-appx:///!UWP/Styles/UWPDictionary.xaml");
Application::Current->Resources->MergedDictionaries->Append(rd);

As I get it, this code should be executed right after InitializeComponent() in App.xaml.cpp's constructor. Source is set correctly (creating URI is executed without any error).
Last line MergedDictionaries->Append(rd) throws an exception:

Exception thrown at 0x7464A6F2 (KernelBase.dll) in wp_UWP.exe: 0x40080201: WinRT originate error (parameters: 0x8000FFFF, 0x00000016, 0x0D30F274).
  Exception thrown at 0x7464A6F2 in wp_UWP.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x0D30F714. HRESULT:0x8000FFFF Catastrophic failure
  WinRT information: Catastrophic failure
Unhandled exception at 0x0C9E571A (Windows.UI.Xaml.dll) in wp_UWP.exe: 0xC000027B: An application-internal exception has occurred (parameters: 0x00F1CA10, 0x00000002).

How to fix this code? I don't understand why it throws such 'Catastrophic failure' exception.

A: You can put the code whenever you initialize main page or in constructor of the main page and it will run fine:
void App::OnLaunched
(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
{
    auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == nullptr)
    {
       // Load the dictionary if not already loaded
       if (!resourcesLoaded) {
          auto rd = ref new ResourceDictionary();
          rd->Source = ref new Uri("ms-appx:///Dictionary.xaml");
          Application::Current->Resources->MergedDictionaries->Append(rd);
          resourcesLoaded = true;
       }
       ..
       ..
   }
   ..
   ..
}

Looks like it works actually everywhere except in app constructor and I have no idea why is that.


text:
Q: How ruthless is Geralt of Rivia? In the scene The Butcher of Blaviken, Geralt killed or gravely wounded half a dozen men without hesitating but when fighting Renfri, he is rather hesitant and even though he had warned her "If we cross swords...", impling he'll kill her if they do cross swords.

In the trailer for The Witcher 3: Wild Hunt, he kills three men he considers evil, again without hesitation, even torturing one by hanging him and deliver him at the merci of his victim.

He protects Duny at the court of Cintra as he's an intelligent being (and not a monster) and also wants to help the Hirikka (before it is slayed for Kingdom and Honor). It somehow just is not consistent for me that at one moment, he kills without any hesitation and at others, he tries to save lifes and is risking his own. Is there a code he follows what intelligent being it is fine to slay and who shall be protected? And how ruthlessly is Geralt following that if he determines somebody needs to be killed? With Butcher of Blaviken, it would seem that he doesn't have any hesitation about killing people in his way.


text:
Q: Simple ranking algorithm in Groovy I have a short groovy algorithm for assigning rankings to food based on their rating.  This can be run in the groovy console.  The code works perfectly, but I'm wondering if there is a more Groovy or functional way of writing the code.  Thinking it would be nice to get rid of the previousItem and rank local variables if possible.
def food = [
  [name:'Chocolate Brownie',rating:5.5, rank:null],
  [name:'Fudge', rating:2.1, rank:null],
  [name:'Pizza',rating:3.4, rank:null],
  [name:'Icecream', rating:2.1, rank:null],
  [name:'Cabbage', rating:1.4, rank:null]]

food.sort { -it.rating }

def previousItem = food[0]
def rank = 1
previousItem.rank = rank
food.each { item ->
  if (item.rating == previousItem.rating) {
    item.rank = previousItem.rank
  } else {
    item.rank = rank
  }
  previousItem = item
  rank++
}

assert food[0].rank == 1
assert food[1].rank == 2
assert food[2].rank == 3
assert food[3].rank == 3    // Note same rating = same rank
assert food[4].rank == 5    // Note, 4 skipped as we have two at rank 3

Suggestions?

A: This is my solution:
def rank = 1
def groupedByRating = food.groupBy { -it.rating }
groupedByRating.sort().each { rating, items ->
  items.each { it.rank = rank }
  rank += items.size()
}

A: I didn't try it, but maybe this could work.
food.eachWithIndex { item, i ->
    if( i>0 && food[i-1].rating == item.rating )
        item.rank = food[i-1].rank
    else
        item.rank = i + 1
}

A: Here's another alternative that doesn't use "local defs" with the groovy inject method:
food.sort { -it.rating }.inject([index: 0]) { map, current ->
    current.rank = (current.rating == map.lastRating ? map.lastRank : map.index + 1)
    [ lastRating: current.rating, lastRank: current.rank, index: map.index + 1 ]
}


text:
Q: Ant conditional unless possible? I'd like a target to execute if either of two conditions are met. Can you have two unless evaluated for one target? Essentially, I'd like target not to run if either of these are true:
unless="product.is.x" or "product.is.y"

Sorry if I'm going about this in all the wrong way, I'm somewhat new to Ant.

A: Read about targets where they mention exactly how to do it:

A target also has the ability to perform its execution if (or unless) a property has been set.

In your case, you can do like:
<condition property="myTarget.condition">
    <or>
        <equals arg1="${product.is.x}" arg2="true" />
        <equals arg1="${product.is.y}" arg2="true" />
    </or>
</condition>

...

<target name="myTarget" unless="myTarget.condition">
    ...


text:
Q: How does the mobile 3.5mm audio port work, and Can I light a LED from it? I am trying to do this, light a LED from the headphone wire(mobile) but it seems it gives ac in there, I don't have much idea, please help.

A: If you must light your led without an external supply you could consider a small audio stepup transformer.Perhaps something out of a dead transistor radio.Otherwise you could build a diode pump that say quadrupled the voltage.Use shottkey diodes for your diode pump because they waste less voltage .Use a red led for your experiment  because they need less volts than the other colors.

A: Yes, audio signals are AC. Headphone voltages will be too low to light an LED.

A: I don't really know for sure, but I would be checking out the mic wire. It could have bias current designed to power electret mics. Easy enough to check - just measure the mic to GND voltage, and then to be sure put in 1k - 10k resistor there, and measure voltage again. From these two measurements you should be able to determine open circuit voltage of that source, and internal resistance.

A: I assume you by headphone wire you mean the 3.5mm jack of your phone.
First consider lighting a LED. To light a LED you need a DC voltage and a few mA of current. Your audio jack isn't built to source current or provide DC voltage. It just transmits AC signal to your headphones.There is no way in which you will be able to light a LED from your jack.
You cannot use it for a purpose which it is not intended to serve.


text: Q: NgRx, может кто-то посоветует туториалы? В документации толком нету даже Всем привет! Прошу прощения за такой вопрос. Я действительно искал книги по NgRx, не нашел. Зашел на сайт документации. Там трудно разобраться. Книги на русском не нашел. Есть лишь на англ. Может кто-то, знает на русском? Какой-либо туториал. Спасибо заранее. Или есть аналог NgRx? Я толком не разбираюсь, просто где-то прочитал что NgRx надо знать к ангуляру.


text:
Q: Webpack,Karma test Babel Missing class properties transform Hi I am running a karma test on a React-Redux app and getting error:
Missing class properties transform

Ie error with static keyword as in
static propTypes

This only happens when running npm test with karma not with running the actual app.
I downloaded "babel-plugin-transform-class-properties":"^6.11.5", and included in my webpack.config.js as follows:
var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'inline-source-map',
  entry: [
    'babel-polyfill',
    'webpack-hot-middleware/client',
    './src/client/index'
  ],
  output: {
    path: path.resolve(__dirname, './static/dist'),
    filename: 'bundle.js',
    publicPath: '/dist/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
      }
    })
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        query: {
          plugins: [,
            [
              'react-transform', {
                transforms: [{
                  transform: ['react-transform-hmr',
                  'transform-class-properties']
                  imports: ['react'],
                  locals: ['module']
                }, {
                  transform: 'react-transform-catch-errors',
                  imports: ['react', 'redbox-react']
                }]
              }
            ]
          ]
        },
        include: [path.resolve(__dirname, 'src')]
      },
      {
        test: /\.css?$/,
        loaders: ['style', 'raw']
      }
    ]
  }
};

My .babelrc file looks like this:
{
  "presets": ["es2015", "stage-0", "react"]
}

I am still getting same error.
Please let me know what is missing, thanks.
This is my package.json file just in case
"devDependencies": {
    "babel-eslint": "^4.1.2",
    "babel-plugin-react-transform": "^2.0.0",
    "babel-preset-airbnb": "^1.1.1",
    "babel-plugin-transform-class-properties":"^6.11.5",
    "css-loader": "^0.15.1",
    "deep-equal": "^1.0.1",
    "enzyme": "^2.2.0",
    "eslint": "^1.4.3",
    "eslint-config-airbnb": "1.0.0",
    "eslint-plugin-react": "^3.4.0",
    "expect": "^1.10.0",
    "jasmine-core": "^2.4.1",
    "json-loader": "^0.5.4",
    "karma": "^0.13.22",
    "karma-babel-preprocessor": "^6.0.1",
    "karma-chrome-launcher": "^0.2.3",
    "karma-cli": "^1.0.1",
    "karma-coverage": "^0.5.4",
    "karma-jasmine": "^0.3.7",
    "karma-mocha": "^1.1.1",
    "karma-phantomjs-launcher": "^1.0.0",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-spec-reporter": "0.0.24",
    "karma-webpack": "^1.7.0",
    "mocha": "^2.3.2",
    "mocha-jsdom": "^1.0.0",
    "nock": "^2.18.2",
    "phantomjs-prebuilt": "^2.1.4",
    "raw-loader": "^0.5.1",
    "react-addons-test-utils": "^0.14.0",
    "react-hot-loader": "^1.2.7",
    "redux-slider-monitor":"1.0.7",
    "react-transform-catch-errors": "^1.0.0",
    "react-transform-hmr": "^1.0.0",
    "redbox-react": "^1.0.6",
    "redux-devtools": "^3.0.0",
    "redux-devtools-dock-monitor": "^1.0.1",
    "redux-devtools-log-monitor": "^1.0.1",
    "redux-devtools-chart-monitor":"1.4.2",
    "redux-mock-store": "0.0.4",
    "webpack": "^1.9.10",
    "webpack-dev-middleware": "^1.2.0",
    "webpack-dev-server": "^1.9.0",
    "webpack-hot-middleware": "^1.1.0",
    "webpack-isomorphic-tools": "^0.8.8"
  },


text:
Q: .NET 2.0 equivalent of C# extension method How do I do change this piece of code to .NET 2.0 compatible by replacing the extension method to .NET 2.0 of equivalent?
public interface IMessagingService {
    void sendMessage(object msg);
}
public interface IServiceLocator {
    object GetService(Type serviceType);
}
public static class ServiceLocatorExtenstions {
    //.NET 3.5 or later extension method, .NET 2 or earlier doesn't like it
    public static T GetService<T>(this IServiceLocator loc) {
        return (T)loc.GetService(typeof(T));
    }
}
public class MessagingServiceX : IMessagingService {
    public void sendMessage(object msg) {
        // do something
    }
}
public class ServiceLocatorY : IServiceLocator {
    public object GetService(Type serviceType) {
        return null; // do something
    }
}
public class NotificationSystem {
    private IMessagingService svc;
    public NotificationSystem(IServiceLocator loc) {
        svc = loc.GetService<IMessagingService>();
    }
}
public class MainClass {
    public void DoWork() {
        var sly = new ServiceLocatorY();
        var ntf = new NotificationSystem(sly);
    }
}

Thank you very much.

A: Just remove this keyword from extension methods.
public static class ServiceLocatorExtensions
{
    public static T GetService<T>(IServiceLocator loc) {
        return (T)loc.GetService(typeof(T));
    }
}

And call it as any other static method by passing instance of object which you are 'extending':
IServiceLocator loc = GetServiceLocator();
Foo foo = ServiceLocatorExtensions.GetService<Foo>(loc);

Actually this is what .Net 3.5 compiler does behind the scene. Btw suffix Extensions you can remove too. E.g. use Helper to not confuse people.

A: svc = loc.GetService<IMessagingService>();

equals
svc = ServiceLocatorExtenstions.GetService<IMessagingService>(loc);

However, you don't have to remove extension methods and still target .NET 2.0 - check this post (more on google): http://kohari.org/2008/04/04/extension-methods-in-net-20/

A: If you don't want to use extension methods and avoid ambiguity in your code, the clanest solution is to move all ServiceLocatorExtenstions methods inside your IServiceLocator interface definition and remove ServiceLocatorExtenstions class.
But this one, probabbly, will involve more work then other solutions oferred here, by the way will produce more consistent result.

A: Why not put the generic method in your interface (as well)? Since your extension method only makes the call easier, isn't it better to make it easier in the first place?
There are ways of having extension methods in .NET 2.0: see here or here.