text:
Q: converting void to string - void to object issue? I have the following multi threaded code, that take a list of servers and async runs the heavyoperation, the heavy operation returns the results and im trying to the populate a multiline text box with the results ( either as a batch when completed or as each task returns ), i have add some code to hopefully perform this task but the three lines below with comments on the right cause we confusion regarding void to static and void to objects :( any hints greatly received as to what i require changing....  Thanks
here is the code :-
   public partial class Form1 : Form
{
    Progress<string> progressReporter = new Progress<string>();
    CancellationTokenSource cancelSource;

    public Form1()
    {
        InitializeComponent();
        progressReporter.ProgressChanged += progressManager_ProgressChanged;
    }

    async private void btnStart_Click(object sender, EventArgs e)
    {
        btnStart.Enabled = false;
        btnCancel.Enabled = true;
        cancelSource = new CancellationTokenSource();
        textBox1.Text = await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token); //--Cannot implicity convert type 'void' to 'string'
        await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token);
        lblStatus.Text = "Completed.";
        btnStart.Enabled = true;
        btnCancel.Enabled = false;
    }
    static async Task PerfromTaskAction(CancellationToken ct)
    {
        StringBuilder sb = new StringBuilder();

        object[] arrObjects = new object[] { "SERVER1", "SERVER2", "SERVER3", "SERVER4" };
        IList<Task> tasks = new List<Task>();
        foreach (object i in arrObjects)
        {
            if (ct.IsCancellationRequested) break;
            sb.Append(string.Format("{0}", tasks.Add(Task.Run(() => HeavyOperation(i.ToString()))))); //-- Argument 2: cannot convert from 'void' to 'object'
            tasks.Add(Task.Run(() => HeavyOperation(i.ToString())));
        }
        await Task.WhenAll(tasks).ConfigureAwait(false);
        return sb.ToString(); //--Since 'Form1.PerfromTaskAction(CancellationToken)' is an async method that returns 'Task', a return keyword must not be followed by an object expression?
    }
    void progressManager_ProgressChanged(object sender, string e)
    {
        lblStatus.Invoke((Action)(() => lblStatus.Text = e));
    }
    static string HeavyOperation(string i)
    {
        PowerShell ps = PowerShell.Create();
        ps.AddCommand("invoke-command");
        ps.AddParameter("computername", i);
        ps.AddParameter("scriptblock", ScriptBlock.Create("get-vmreplication | select State"));
        Collection<PSObject> result = ps.Invoke();
        return(result[0].Properties["State"].Value.ToString());
    }
    private void btnCancel_Click(object sender, EventArgs e)
    {
        cancelSource.Cancel();
    }

}

A: You have three errors, so taking them one at a time:
//-- Argument 2: cannot convert from 'void' to 'object'
sb.Append(string.Format("{0}", tasks.Add(Task.Run(() => HeavyOperation(i.ToString())))));

The return type of List<T>.Add is void. So it can't be used as the second parameter to string.Format. It's not at all clear here what you want to do with this line of code, so I can't suggest a fix.
//--Since 'Form1.PerfromTaskAction(CancellationToken)' is an async method that returns 'Task', a return keyword must not be followed by an object expression
return sb.ToString();

This error is saying that you're in an async Task method (which is the async equivalent of void), so it can't have a return value. And yet your code is attempting to return a value.
The fix here is to change the method signature to return Task<string>:
static async Task<string> PerfromTaskAction(CancellationToken ct)

As for the final error:
//--Cannot implicity convert type 'void' to 'string'
textBox1.Text = await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token);

If PerformTaskAction returns a Task, then the return type of Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token) is also Task, and this means the type of await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token) is void. And you cannot take a void and assign it to textBox1.Text.
The fix for the last error (changing to Task<string>) also fixes this one. The return type of Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token) is now Task<string>, and the type of await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token) is now string.
Update from comment:
Since you want to return all the strings when they all complete, this is easier to do without StringBuilder:
static async Task<string> PerfromTaskAction()
{
  object[] arrObjects = new object[] { "SERVER1", "SERVER2", "SERVER3", "SERVER4" };
  var tasks = arrObjects.Select(i => Task.Run(() => HeavyOperation(i.ToString())));
  var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  return string.Join("", results);
}

Note that since CancellationToken isn't used in HeavyOperation, it can be removed from the PerformTaskAction signature.

A: change method signature to
static async Task<string> PerfromTaskAction(CancellationToken ct)

return Task(sb.ToString());

and then
textBox1.Text = await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token).Result;


text:
Q: The chronograph instrument error is 0.01s, so why should 10 periods be measured in calculation?
The experimental subjects have a period of less than 0.1s, and the resolution is not enough. If only one cycle is measured, it will be greatly affected by chance.

how to figure it out? and also some description, please?

A: Suppose I want to know how many people visit a grocery store in a month. Here's one approach: I know that the store is scheduled to be open for 3600 minutes every month, so I can watch the door for one minute and extrapolate.
That's a terrible way to extrapolate, because the interval is too small. I might look for a minute where nobody comes, and extrapolate to "zero people will visit the store this month." I might happen to look for a minute where a family of seven arrives all at once, and extrapolate that 25,200 people will visit the store.  There's too much variation in that tiny interval for the extrapolation to be useful.
People-counting is different from frequency measurement (because people-arrivals are "Poisson distributed"), but the same general idea applies: lots of measurements are better than fewer measurements.  You describe a system with period 0.1s and a chronometer with precision 0.01s.  If you measure a single period, the best you could possibly do would be an uncertainty of 10%, which is like being uncertain whether your cartful of groceries will cost you \$100 or \$110.  (You don't say much about your setup, but if you have a hand-operated stopwatch which displays centi-seconds, your precision will be limited by your reaction time in pressing the "start" and "stop" buttons with your thumb. My experience is that students usually operate a stopwatch with quarter-second reaction-time noise.)
But, suppose instead that you count out 100 periods, and measure that much longer interval with a precision that is one-tenth of one period. Now your time measurement is good to one part in a thousand, like being uncertain whether your grocery bill will be \$100 or \$100.10.  If your lab partner were to say to you "hey I think that was only 99 periods," your measurement would still be better than your single-period measurement.
Ten periods is a good compromise position, because a well-done intro-lab experiment will typically have percent-scale uncertainties.

A: The underlying assumption here is that chronometer is accurate (it measures time correctly over a sufficiently long interval) but not very precise (it cannot measure intervals of less than 0.1 seconds). Another way of putting this is that the observational errors made when the chronometer is used to measure intervals are random errors, rather than systemic errors.
If this is the case then using the chronometer to measure ten periods (if, indeed, all periods are the same length) and then dividing by ten to get an average measurement for one period will give a better estimate than trying to measure just one period on its own.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set ViewModel property when a TextBox is focused I have a MVVM application and I want to keep track of the focused element in my ViewModel.
I would like to set ViewModel property when a TextBox is focused.
I would like to have something like this
 <TextBox Text="{Binding P1}">
    <TextBox.Style>
       <Style TargetType="{x:Type TextBox}">
         <Style.Triggers>
           <Trigger Property="IsFocused" Value="True">
             <Setter Property="{Binding P1Selected}" Value="True"/>
           </Trigger>
         </Style.Triggers>
       </Style>
    </TextBox.Style>
 </TextBox>

where P1 and P1Selected are viewModel properties.
Of course this code does not work. I wrote it just to give the idea..

A: Sorry, my answer was wrong.
Please see OneWayToSource binding from readonly property in XAML.


text:
Q: How to view an image when scroll position is located at the bottom of the page? I need the browser to scroll my ASP.NET page to the top when the user
clicks on a server-side link or button at the bottom of the page.

Back to up

I use this code for it:
 $(document).ready(function () {

        $('a[href=#top]').click(function () {
            $('html, body').animate({ scrollTop: 0 }, 'slow');
            return false;
        });

    });

I want to show this button when the scroll position is at the bottom of the page and don't want to show this when the scroll position is at the top of the page.
How to view this button when the scroll position is at the bottom of the page?

A: I use this code. it is useful for me.

Top

A: Add a scroll listener and manage your button visibility by checking if the main container (could be body) scrollTop is max value:
var $elem  = $('#mainContainer');
var $button = $('#top');
$(window).scroll(function(){
    if ($elem[0].scrollHeight - $elem.scrollTop() == $elem.outerHeight()) {
      // We're at the bottom.
      $button .show();
    }
   else
       $button .hide();
});

More example : http://www.yelotofu.com/2008/10/jquery-how-to-tell-if-youre-scroll-to-bottom/


text:
Q: Angular Bootstrap Toggle Switch I'm trying to implement a toggle slider within an *ngFor based on 'yes' or 'no' values from my API. The initial toggle slider state must be checked (slider to left, or slider to the right) on the initial modal load.
I'm getting the initial state on load of my modal, but I can't slide the toggle 'yes' if the response value from the API is 'no'. I'm using Bootstrap 4, btw.
I've tried multiple variations of adding NgClass but I can't seem get this part working.
Here is what I've tried so far.
admin.component.html
<form [formGroup]="permissionForm">

{{ item.permissionToolTip }} {{ item.hasPermission }}

                                    <input
                                      #permissionToggle
                                      [id]="i"
                                      formControlName="HasPermission"
                                      type="checkbox"
                                      (change)="onChangePermission($event,i)"
                                      [value]="item.hasPermission"
                                      >

                          </form>

admin.component.css
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}

/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}

/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}

.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}

input:checked + .slider {
background-color: rgba(58,177,96,1);
}

input:focus + .slider {
box-shadow: 0 0 1px rgba(58,177,96,1);
}
input:focus + .slider {
box-shadow: 0 0 1px rgba(58,177,96,1);
}

input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
border-radius: 34px;
}

.slider.round:before {
border-radius: 50%;
}

.noPermission {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: 0.4s;
    transition: 0.4s;
}

.noPermission:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    -webkit-transition: 0.4s;
    transition: 0.4s;
}
.noPermission.round {
    border-radius: 34px;
}

.noPermission.round:before {
    border-radius: 50%;
}

input:checked + .noPermission.slider {
    background-color: rgba(58,177,96,1);
    }

    input:focus + .noPermission {
    box-shadow: 0 0 1px rgba(58,177,96,1);
    }

input:checked + .noPermission:before {
    -webkit-transform: translateX(0);
    -ms-transform: translateX(0);
    transform: translateX(0);
}

Thanks in advance.


text:
Q: NSOpenPanel - title not displayed and window not closing I am building a toolbar app with a menu containing one option that displays a NSOpenPanel in order to let the user select a folder.
It is working fine except that the title is not displayed on the NSOpenPanel and that I have to use a tricky method to close the window after the "OK" button has been hit.
Here is my code :
let dialogue = NSOpenPanel()
                dialogue.title                   = "Choisissez un répertoire"
                dialogue.canChooseFiles          = false
                dialogue.showsResizeIndicator    = true
                dialogue.showsHiddenFiles        = false
                dialogue.canChooseDirectories    = true
                dialogue.canCreateDirectories    = false
                dialogue.allowsMultipleSelection = false
                dialogue.allowedFileTypes        = [""]

    if (dialogue.runModal() == NSModalResponseOK)
    {

                    let result = dialogue.url

                    dialogue.setIsMiniaturized(true)
                    dialogue.setIsVisible(false)
                    dialogue.close()

                    if (result != nil)
                    {
                      let path = result!.path

                    }
                    else
                    {
                      return
                    }
    }

I have not found a way to display the title although it is configured.
I have to use setIsMiniaturized(true) and setIsVisible(false) before closing the NSOpenPanel otherwise it is only closing at the end of the process.
Any help would be appreciate.

A: Since OSX 10.11 the title is not shown any more. You can misuse the message property if you really need to show some text:
let fileDialog = NSOpenPanel()
fileDialog.message = "Your message"


text:
Q: How do you create a custom project type (from my plugin) without opening Eclipse? I have created a plugin for Eclipse. With the help of this plugin, I am creating a new type of project, let's say XTypeProject. The creation of this XTypeProject is similar to any other type of project you create in Eclipse.

File -> New -> YourProjectType

I just want to know whether there is any way I can create a simple XTypeProject in Eclipse through some external mechanism, anything, and this project created through an external mechanism has to be similar to the project I create using Eclipse. Can Maven help me in this? Or is there any other way to do that?

A: Here are my findings :-

*

*I went through the advice of Amos M. Carpenter and searched for the source code of the plugin that I have written.

*After that, I did a debug (Plugin Debug) and searched for the methods that are called when we create a project from the Eclipse menu.

*I took a note of all those class files and their methods that are called and the information/parameters they need for further processing.

*I initiated the same call through ANT and was able to do what I wanted.
Thank you for the support.
P.S - I can't share my Plugin details as it is written for an organisation.


text:
Q: How to transform a rectangle into a circle I want to turn a rectangular image into a circle using the HTMLCanvas element. (Finally I only need the upper half of the circle but that could be easily managed by cutting the resulting circle in half.)
From this

To this

My idea was to do a simple line by line transformation. So far I have just the basic drawing logic but I'm totally lost with the math for the transformation.
<!DOCTYPE html>
<body>
    <canvas id="canvas"></canvas>
</body>

<script type="text/javascript">
var img = new Image();
img.onload = function init() {
    var img = this;
    var imgH = img.height;
    var imgW = img.width;

    // make the canvas the same size as the image.
    var c = document.getElementById("canvas");
    c.width = imgW;
    c.height = imgH;

    var ctx = c.getContext("2d");
    var halfHeight = imgH/2;

    // draw the upper part
    // line by line
    for(var i = 0; i < halfHeight; i++) {
        // I'm totally lost here.

        // current output without transformation
        ctx.drawImage(img, 0, i, imgW, 1, 0, i, imgW, 1);
    }

    // add the second half which must not be transformed
    ctx.drawImage(img, 0, halfHeight, imgW, halfHeight, 0, halfHeight, imgW, halfHeight);
};
img.src = "https://i.stack.imgur.com/52TjZ.png";

</script>
</html>

A fiddle
https://jsfiddle.net/kirschkern/amq7t6ru/2/
(I need it in pure JS and 2d. No three.js, no webgl.)
Any help is highly appreciated.

A: I don't know much about Javascript but as this seems more of a mathematical question, I'll have my shot.
Replace the lines
    // I'm totally lost here.

    // current output without transformation
    ctx.drawImage(img, 0, i, imgW, 1, 0, i, imgW, 1);

with
    var xMargin = -Math.sqrt(1-Math.pow((i-halfHeight)/halfHeight,2))*imgW/2+imgW/2;
    ctx.drawImage(img, 0, i, imgW, 1, xMargin, i, imgW-(2*xMargin), 1);

This distorts the upper half of the image as an ellipse (a circle would work only if your input image would be a square) as this:

Does this solve your question?
Explanation
I took the equation of a shifted ellipse from Wikipedia and set c1 and a to be equal to imgW/2 and c2 and b to imgH/2. Taking i for y let me compute x; I saved one of the solutions as xMargin. The width of the picture at the given vertical coordinate would be the original width minus twice the margin.
In the end, I fed drawImage() with these inputs, see the documentation.

A: Plain 2D JavaScript does not have primitives to distort images like this. So a simple drawImage will not be enough.
What you can do is approximate things. Write a function which for every point in the distorted image (the one with the circle) computes the corresponding position in the original image. Then you can do one of four things, in increasing order of effort and resulting quality.

*

*Iterate over all the pixels in the destination image, and look up the corresponding pixel value in the source image.

*Like before, but with subsampling: take several positions inside the square of the source pixel, and average the resuling colors for a smoother appearance.

*Approximate the affine transformation in a given point (for this you will likely need partial derivatives of your mapping function) and use it to draw an affinely transformed image.

*Same as 3 but with projective instead of affine transforms. That would arguably make it 3D in its formulation.

*Like 1 or 2 but implement all of that in WebGL as a fragment shader. I know you said you don't want that, but in terms of performance and resulting quality this should give the best results.


text:
Q: VueJS change content of component slots globally I want to use component for selectbox. But I need change texts in slots (eg. Whoops! Nothing here.).
I know how to change component slots in template"
<v-select>

      My text which will displayed

</v-select>

But how to change content of slots globally? So whenever I use component, slots will have own defined content (not default which is in component).
Thanks

A: I don't really understand。I think you need to create a new component!
<template>
  <v-select>

      My text which will displayed

  </v-select>
</template>

So you use it like this.
<template>
  <my-select></my-select>
</template>

A: https://github.com/cloydlau/vue-global-config provides the ability to programmatically pass global slots, global scoped slots, global props, global attrs, global listeners and global hooks, support Vue 2.6/2.7/3.


text:
Q: bulk indexing in elasticsearch issue I am trying to index a file by using below code:
But I am wondering why it is not happening:
Could any body explain the reason for not indexing.
public static void main(String[] args) throws IOException {
    String line;
    List l=new ArrayList();
    FileReader file=new FileReader("test.txt");
    BufferedReader br=new BufferedReader(file);
    while((line=br.readLine())!=null){
        l.add(line);
    }
    br.close();
    System.out.println(l);
    Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("10.210.51.207",9300));
    BulkRequestBuilder bulkRequest = client.prepareBulk();

    // either use client#prepare, or use Requests# to directly build index/delete requests
    Iterator it=l.iterator();
    while (it.hasNext()){
        String name=(String) it.next();
        bulkRequest.add(client.prepareIndex("cricket", "cric", "1")
                   .setSource(jsonBuilder()
                   .startObject()
                   .field("user", name)
                   .field("postDate", new Date())
                   .field("message", "BULK INSERT TEST")
                   .endObject()
                   )  );

    }

    GetResponse getResponse = client.prepareGet("cricket", "cric", "1").execute().actionGet();
    System.out.println(getResponse.getSourceAsString());
    System.out.println("Bulk request finished");

}

Thans in advance

A: You need to execute your bulkRequest to add the document(s) to the index.
Please add the following before your GetResponse.
 BulkResponse bulkResponse = bulkRequest.execute().actionGet();

You can then check the properties on the bulkResponse object to ensure it completed successfully.


text:
Q: How can I use object as an array? I want to use next syntax:
$o = new MyClass();
$o['param'] = 'value'; // set property "param" in "value" for example

Now I have an error:
Fatal error: Cannot use object of type MyClass as array

Can I use object like this? Maybe there are any magic methods?

A: What you could do, is create a new class called MyClass and make it implement the ArrayAccess interface.
You can then use:
$myArray = new MyClass();
$myArray['foo'] = 'bar';

Although it's easier to just use:
$myArray->foo = 'bar';

A: You object has to implement ArrayAccess interface.
class MyClass extends ArrayAccess
{
   private $container = array();

   public function offsetSet($offset, $value)
   {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}


text:
Q: What does  mean in HTML? <form>

How much was your bill?

    $ <input id="billamt" type="text" placeholder="Bill Amount">

How was your service?

    <select id="serviceQual">
      <option disabled selected value="0">-- Choose an Option --</option>
      <option value="0.3">30% - Outstanding</option>
      <option value="0.2">20% - Good</option>
      <option value="0.15">15% - It was OK</option>
      <option value="0.1">10% - Bad</option>
      <option value="0.05">5% - Terrible</option>
    </select>

</form>

Code from Carolyn hemmings tip calculator

A: From the specification:

Decimal numeric character reference
The ampersand must be followed by a U+0023 NUMBER SIGN character (#), followed by one or more ASCII digits, representing a base-ten integer that corresponds to a code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON character (;).

A: Those are html entries. I can't explain clearly here. you may read about this from w3schools.com you may use this link. https://www.w3schools.com/html/html_entities.asp
more about display html symbols.  https://www.w3schools.com/html/html_symbols.asp


text:
Q: Fixing a proof that open path connected sets in $\mathbb{C}$ are connected.
Let $\Omega\subset \mathbb{C}$ be open. Then if $\Omega$ is pathwise connected, then $\Omega$ is connected.

Let $\Omega\subset\mathbb{C}$ be open, and suppose we can write $\Omega =\Omega_1\cup \Omega_2$ for disjoint open $\Omega_1,\Omega_2\subset\mathbb{C}$. Let $w_0\in\Omega_1$ and $w_1\in\Omega_2$, and let $\gamma:[0,1]\to\mathbb{C}$ be a path in $\Omega$ with $\gamma(0)=w_1$ and $\gamma(1)=w_2$. Let
\begin{equation}
t^*=\sup_{t\in [0,1]} \{t:\gamma(s)\in\Omega_1,\,0\leq s<t\}.
\end{equation}
If $\gamma(t^*)\in\Omega_1$, there is some $\varepsilon>0$ so that $D_\varepsilon(\gamma(t^*))\subset\Omega_1$, namely, $\gamma(t^*+\varepsilon)\in\Omega_1$, which is a contradiction. But since $\Omega_2$ is open, $\mathbb{C}\setminus\Omega_2$ is closed so it must contain its limit points, $\gamma(t^*)$ is a limit point of $\Omega_1\subset \mathbb{C}\setminus\Omega_2$, and so $\gamma(t^*)\in \Omega_1$, which is a contradiction.
I feel uneasy with the last point of the proof, and was wondering if there was any way I could fix it. Any help/hints/feedback would be greatly appreciated.

A: Your proof looks perfectly good to me; it's essentially the standard proof that a path-connected space (no matter whether it is a subset of $\mathbb C$ or not) is connected.
I would probably insert a new paragraph starting with

On the other hand, assume $\gamma(t^*)\notin \Omega_1$.

after the first "... which is a contradiction." But that's just style polishing.
It could also make the proof just a smidge clearer if the first "... which is a contradiction" used a few words too say it is specifically a contradiction with the definition of supremum that gave you $t^*$.


text:
Q: Errors while accessing the EDB My Exchange Server is delivering outgoing mails without attachments. Strange to my surprise I am also encountering ESE (Extensible Storage Engine) errors while accessing the EDB (Exchange Server Database) file. Why it is so and how to overcome from such issue?

A: Well, the problem you are witnessing indicates about the corruption of Exchange Server database. You need to go for Exchange Server Recovery to get your database repaired, if an updated and complete backup is not in place. However, the most probable reasons for facing such problems could be –

*

*Transactions are not committed to the hard drive by Disk Caching and
the Exchange Server is crashed.

*List item In the process of restoring database wrong log files were replayed.

To overcome from such issue, you just got to go through the steps:

*

*If your hard drive has logical problems, run ChkDsk utility to detect
and fix hard drive related errors.

*In case of database corruption and other database related issues,
run DBCC CHECKDB.

By following these steps you would be able to fix the corruption issue quite easily. If not fix then you can use the professional software. For more detail http://exchangeserver.tumblr.com/ and
some professional tools
http://www.nucleustechnologies.com/Exchange-Server-Data-Recovery.html

A: I think that for the error handling you should try this thing. And if your Exchange database is corrupt then you can try one of many third-party tools to repair your EDB files.


text:
Q: Ajax progress bar with a big list I have an ajax call that is grabbing a large json list.  Is there any way I can make a progress bar that gets the real value of json load (for example a status bar that says 1 out of 200 loaded)?
Right now I have a pretty basic Ajax call
function SendAjax(urlMethod, jsonData, returnFunction) {
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: urlMethod,
        data: jsonData,
        dataType: "json",
        success: function (msg) {
            if (msg != null) {
                ReturnJson(msg);
            }
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.

            var err = eval("(" + xhr.responseText + ")");

            // Display the specific error raised by the server
            alert(err.Message);
        }
    });
}

A: Try using AjaxStart on your application global scope. That means you can put the code in your layout file, and if the processing is long, it will show the progress indicator...
$(document).ajaxStart(function() {
   $( "#loading" ).show();
 });

You can see the example and answer at preload with percentage - javascript/jquery.

A: there are a few states in an ajax request, but they do not represent any percentage through the request.
The network traffic should really be your real problem, you do not want to send 200 separate requests (although this would allow for a progress bar, it would make the whole request take significantly longer, depending on your network connection to the server).
You are best off just showing an activity indicator and removing it when the request completes and try to optimise your code server side to return the 200 items as fast as possible.
If 200 items really is too big (larger than X seconds to return them), you could split it in half or quarters to show some progress however this will waste time with those extra requests on network, page headers, etc.

A: If your server-side code has a way of sharing application state (such as the $_SESSION in PHP) you could make 2 separate requests, one that asks for the data, and one that checks on progress of the first request. Repeat the second request on a timer until the first completes, and update the $_SESSION (or whatever works in your server code) as each item is processed.
For example:
The initial page must start a session, so that the subsequent AJAX calls have the cookie, and can access the shared data:
<?php
session_start();
session_write_close(); // close the session so other scripts can access the file (doesn't end the session)
// your page content here
?>

First AJAX Call to start the processing:
<?php
function updateSession($count){
    session_start(); // open the session file
    $_SESSION['progress'] = $count;
    session_write_close(); // let other requests access the session
}
// as you process each item, call the above function, ex:
for ($i = 1; $i <= 10; $i++) {
    updateSession($i);
}
?>

Second AJAX call (repeated every X seconds) looks like:
<?php
session_start(); // open the session file
echo @$_SESSION['progress'] or 0; // echo contents or 0 if not defined
session_write_close(); // let other requests access the session
?>

Sorry I don't know ASP.NET, but hopefully the above code is useful to you.


text:
Q: Adding a string to a column across multiple rows In my table I have a column called ImportKey. I want to update this column and add an A either before or after each number. So changing this:
ImportKey
---------
2345
1353
2474
4762
---------

to this:
ImportKey
---------
A2345
A1353
A2474
A4762
---------

or this:
ImportKey
---------
2345A
1353A
2474A
4762A
---------

The column is a string value, I'm just not sure of the syntax to update multiple rows and add something to each of them. Any help?

A: Just prepend or append the letter:
UPDATE dbo.Table1
SET dbo.Table1.ImportKey = 'A' + dbo.Table1.ImportKey

Prepend - Append
UPDATE (Transact-SQL)


text:
Q: что делать если мое сложения в js не работает а оно просто делает 2222 при сложении 22+22=2222 а е 44 что делать? если идет не сложения а просто слепливает все вместе в js 22+22=2222 f yt 44
let number1 = prompt("введите первое число")
let number2 = prompt("введите первое число")
let sum = number1 + number2
document.getElementById("result").textContent = number1 + " + " + number2 + " = " + sum

A: Потому что prompt считывает строку, нужно явное приведение к типу Number.

let number1 = prompt("введите первое число")
let number2 = prompt("введите первое число")
let sum = parseInt(number1) + parseInt(number2)
console.log(sum)

A: Используй унарный плюс для приведения к числу.
let number1 = +prompt("введите первое число")
let number2 = +prompt("введите первое число")


text:
Q: Getting checkbox and text values to questions using bs4 and python Im trying to scrape the different values (answers to questions) on the following website. 'https://www.unpri.org/organisation/schroders-144205', more specifically the report attached to the website. https://reporting.unpri.org/surveys/PRI-Reporting-Framework-2016/6a23ed84-6bbf-4416-9d0b-6c49f63bc9ac/79894dbc337a40828d895f9402aa63de/html/2/?lang=&a=1.
In the case that the question is unanswered i would like to add a blank space to the list, and add the answer in case it is answered. I have tried many different ways now, and will put up the code on here even though it is a freaking mess.
**So the question is - How can i scrape answers to the question on the report link, and in the question is not answered, add a blank element? All answers or blank aelements should be added to a list.
urls = ['https://www.unpri.org/organisation/schroders-144205']

for i in urls:
    browser.visit(i)
    window = browser.windows[0]
    window.is_current = True
    temp_list = []
    sourcenew = browser.html
    soupnew = bs.BeautifulSoup(sourcenew, 'lxml')
    temp_list.append(browser.url)

for info in soupnew.find_all('span', class_ = 'org-type' ):
        string_com = str(info.text)
        if len(string_com) == 16:
            string_com = string_com.replace(' ', ' ')[1:-1]
        elif len(string_com) == 11:
            string_com = string_com.replace(' ', ' ')[1:-1]
        elif len(string_com) == 10:
            string_com = string_com.replace(' ', ' ')[1:-1]
        elif len(string_com) == 12:
            string_com = string_com.replace(' ', ' ')[1:-1]
        elif len(string_com) == 13:
            string_com = string_com.replace(' ', ' ')[1:-1]
        else:
            string_com = string_com.replace(' ', ' ')[40:-37]
            temp_list.append(string_com)
        if len(browser.find_by_xpath('//*[@id="main-
content"]/div[2]/div/div/div[2]/p/a')) > 0:
        browser.find_by_xpath('//*[@id="main-
content"]/div[2]/div/div/div[2]/p/a').click()
        time.sleep(2)
        if len(browser.windows) > 1:
            window = browser.windows[1]
            window.is_current = True

            sourcenew2 = browser.html
            soupnew2 = bs.BeautifulSoup(sourcenew2, 'lxml')

            parent = soupnew2.select('div[class="indent type_^ parent_S"]')
            header_values = []

            for r in parent:
                headers = r.find_all("h3")
                for header in headers:
                    if header is not None:
                        fake_radio_button = r.find("img", src="/Style/img/checkedradio.png")
                        real_radio_button = r.select("input[checked='checked']")

                        if fake_radio_button == None:
                            if real_radio_button == None:
                                header_values.append('')
                            else:
                                if len(real_radio_button) > 0:
                                    header_values.append(
                                    real_radio_button[0].attrs["data-original"])
                                else:
                                    header_values.append("")
                        else:
                            header_values.append( fake_radio_button.parent.find(
                            "span").get_text(strip=True))

            text_values1 = []
            text_values2 = []

            for r in parent:
                headers = r.find_all("h3")
                for header in headers:
                    if header is not None:
                        fake_radio_button = r.find_all("img", src="/Style/img/checkedcheckbox.png")
                        real_radio_button = r.select("input[checked='checked']")

                        for b in fake_radio_button:
                            if b == None:

                                if real_radio_button == None:
                                    text_values1.append('')
                            else:
                                   if len(real_radio_button) > 0:
                                       text_values1.append(
                                       real_radio_button[0].attrs["data-original"])
                                   else:
                                       text_values1.append("")
                        else:
                            text_values1.append( b.parent.find(
                                  "span").get_text(strip=True))

            for r in parent:
                headers = r.find_all("h3")
                for header in headers:
                    if header is not None:
                        fake_radio_button1 = r.find("img", src="/Style/img/checkedcheckbox.png")
                        real_radio_button1 = r.select("input[checked='checked']")

                        if fake_radio_button1 == None:

                            if real_radio_button1 == None:
                                text_values2.append('')
                            else:
                                if len(real_radio_button1) > 0:
                                 text_values2.append(
                                 real_radio_button1[0].attrs["data-original"])
                                else:
                                    text_values2.append("")
                        else:

text_values2.append(fake_radio_button1.parent.find(
                              "span").get_text(strip=True))

            text_values3 = []

            for r in parent:
                headersss = r.find_all("span", class_ = 'n-text-p response')
                for headerss in headersss:
                    if headerss is not None:

                        text_values3.append(headerss.get_text(strip=True))

            for r in parent:
                headersss = r.find_all("span", class_ = 'response number')
                for headerss in headersss:
                    if headerss is not None:

                        text_values3.append(headerss.get_text(strip=True))
                    else:
                        text_values3.append('')

            for r in parent:
                headersss = r.find_all("span", class_ = 'response date')
                for headerss in headersss:
                    if headerss is not None:

                        text_values3.append(headerss.get_text(strip=True))
                    else:
                        text_values.append('')

            list_final = []

           def f7(seq):
                seen = set()
                seen_add = seen.add
                return [x for x in seq if not (x in seen or seen_add(x))]

            list_final.append(f7(temp_list))
            list_final.append(f7(header_values))
            list_final.append(f7(text_values1))
            list_final.append(f7(text_values2))
            list_final.append(f7(text_values3))

            print(list_final)

A: I had a look at your link, and the checkboxes are not actual checkbox elements, but rather images, but what you want can still be done. If you look,
This is the image in the checked radio buttons

And this is the image tags for the unchecked ones

Hence, you can pick checked or unchecked answers based on that somewhat like this:
    all_question_blocks = soup_obj.findAll("div",{"class":"question-block"})
    for question_block in all_question_blocks:
        checked = question_block.findAll("a",{"src=":"/Style/img/checkedradio.png"}
        #all your checked attributes, if empty then not answered
        unchecked = question_block.findAll("a",{"src=":"/Style/img/uncheckedradio.png"}

You can then move upwards in the HTMLtree and get parent elements one by one if you wish to extract other attributes.
Hope this helps!


text:
Q: Android studio listview doesn't show Hello Im new to android studio and i probably made a silly mistake which i cant find.
So basicaly i have made a tabbed activity with all the days and i want to make a list (I wanna make a custom schedule app which will have all the activities i do daily).My ListView doesn't show :(. What have i done wrong?
EditActivity class code : https://hastebin.com/amajusutid.java
package com.timemanagement.restrictedpower.timemanagement;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class EditActivity extends AppCompatActivity {
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private  ViewPager mViewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_edit, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static String day(int id){
        switch (id) {
            case 1:
                return "Monday";
            case 2:
                return "Tuesday";
            case 3:
                return "Wednesday";
            case 4:
                return "Thirsday";
            case 5:
                return "Friday";
            case 6:
                return "Saturday";
            case 7:
                return "Sunday";
        }
        return null;
    }
    public static class PlaceholderFragment extends Fragment {
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_edit, container, false);

            ListView lv = (ListView) v.findViewById(R.id.Activities);
            List<String> fruits_list = new ArrayList<String>();
            fruits_list.add("Apple");
            fruits_list.add("Strawberry");
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, fruits_list);
            lv.setAdapter(arrayAdapter);
            lv.invalidateViews();
            View rootView = inflater.inflate(R.layout.fragment_edit, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.Day);
            int id = getArguments().getInt(ARG_SECTION_NUMBER);
            String day = day(getArguments().getInt(ARG_SECTION_NUMBER));
            textView.setText(day);
            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
            return rootView;
        }
    }
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 7;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
                case 2:
                    return "SECTION 3";
                case 3:
                    return "SECTION 4";
                case 4:
                    return "SECTION 5";
                case 5:
                    return "SECTION 6";
                case 6:
                    return "SECTION 7";
            }
            return null;
        }
    }
}

Xml code: https://hastebin.com/yapepideme.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1234">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/Activities"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        style="@android:style/Widget.DeviceDefault.ExpandableListView" />
</LinearLayout>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_height="60dp"
    android:layout_width="match_parent">

    <TextView
        android:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="5mm"
        android:id="@+id/Day" />

    <TextView
        android:id="@+id/section_label"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:textColor="#FFCC91"
        android:textSize="6mm"
        android:gravity="center"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>

A: I have solved your problem, you have to change the height of the linear layout because it is hidden when the app bar layout is applied.Your listview should placed below the app bar layout.I have changed                    android:layout_height="300dp" ,
            android:layout_marginTop="100dp"  in your linear layout.Now your listview is appearing.
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1234">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_marginTop="100dp"
    android:layout_weight="1">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/Activities"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        style="@android:style/Widget.DeviceDefault.ExpandableListView" />
</LinearLayout>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_height="60dp"
    android:layout_width="match_parent">

    <TextView
        android:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="5mm"
        android:id="@+id/Day" />

    <TextView
        android:id="@+id/section_label"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:textColor="#FFCC91"
        android:textSize="6mm"
        android:gravity="center"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</android.support.design.widget.AppBarLayout>


text:
Q: How to click on button in popup dialog that isn't in page source I want to write a script to legitimately mine coins in Agar.io by clicking the "Free Coins" button once every hour. To do this, I'm using Selenium's Firefox webdriver in Python:
from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://agar.io")
browser.find_element_by_id("freeCoins").click()
browser.find_element_by_xpath("//canvas/button[1]").click()
browser.quit()

By viewing the HTML source of the Agar.io webpage, I was able to find the ID of the "Free Coins" button to click on it, but in order to harvest the coins I need to click on the first button in the popup dialog that comes up:

I can't find the source code for the popup dialog, so I don't know how to find the "20 Coins" button to click it using Selenium.
In addition, there is often a popup dialog on the webpage when it first loads advertising some sort of sale on game purchases. It has a close button which I would also need to click using Selenium, but again I can't find the source code for it so I don't know how to.
Is there a way that I can click on these buttons using Selenium without being able to see their IDs or classes in the webpage's source code?


text:
Q: WPF Button Command for right mouse button? I am learning about MVVM and Commands in WPF. I have a couple of buttons and I want to trigger similar commands depending on the fact if the buttons are clicked with the left or right mouse button.
Until now I used Event Handlers and I was able to determine which mouse button was pressed by checking the MouseButtonEventArgs.
<Button Content="Command Test" PreviewMouseDown="Button_PreviewMouseDown"/>

Current code behind:
private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    if (e.LeftButton == MouseButtonState.Pressed) {
        Debug.Print("Left");
    }
    else {
        Debug.Print("Right");
    }
}

But I don't see anything similar if I use Commands.
How can I set different commands for a button? One command when the left mouse button is clicked and another command when the right mouse button is clicked?
<Button Content="Command Test" Command="{Binding PressLetterCommand, Mode=OneWay}"/>

Currently the Command only fires when the left mouse button is clicked. If the command would also be fired if the right mouse button is clicked and I can find out which button was clicked that would be also a solution.
I searched and I found this question and answer which uses Decorator. How do I bind a command to e.g. the right mouse button in a ControlTemplate in WPF? I tried it but as far as I understand this won't work for my buttons.
Any suggestions?

A: Try this
<Button Content="Command Test">
    <Button.InputBindings>
        <MouseBinding Gesture="RightClick" Command="{Binding PressLetterCommand}" />
    </Button.InputBindings>
</Button>


text:
Q: Google Speech-To-Text with React I'm working on a simple speech to text web app, I already have working server-side nodejs code and simple react page, but I don't have any idea how to glue them together, I was trying to implement various different weird stuff and either the react app doesn't get any data in return either there is error 500.
I would like to implement stop() function for the recorder after getting the transcription from Google as it is set to be listening only short commands, but the only solution that I could implement was the setTimeout function which is not exactly what I wanted.
EDIT: I have solved the problem with stopping recorder after getting the command and it works pretty good, however, any improvements are welcome. The solution was quite easy, I just modified the threshold from null to 0.5, thresholdEnd: 0.5. Still not resolved the front end for this express app.
EDIT 2: Funny thing, I accidentally discover this stuff and it is exactly what I wanted... So much effort just to find this amazing and super easy solution, especially if you follow this medium article.
Can anybody help me, please?
Server-side code:
'use strict';

const express = require('express');
const app = express();
const port = 3002;

const cors = require('cors')

// Node-Record-lpcm16
const recorder = require('node-record-lpcm16');

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech');

function speechFunction() {
    const encoding = 'LINEAR16';
    const sampleRateHertz = 16000;
    const languageCode = 'en-US';
    const command_and_search = 'command_and_search';
    const keywords = ['turn on', 'turn off', 'turn it on', 'turn it off'];

    const request = {
        config: {
            encoding: encoding,
            sampleRateHertz: sampleRateHertz,
            languageCode: languageCode,
            model: command_and_search,
            speech_contexts: keywords
        },
        singleUtterance: true,
        interimResults: false // If you want interim results, set this to true
    };

    // Creates a client
    const client = new speech.SpeechClient();

    // Create a recognize stream
    const recognizeStream = client
    .streamingRecognize(request)
    .on('error', console.error)
    .on('data', data =>
        // process.stdout.write(
        console.log(
        data.results[0] && data.results[0].alternatives[0]
            ? `Transcription: ${data.results[0].alternatives[0].transcript}\n`
            : `\n\nReached transcription time limit, press Ctrl+C\n`
        )
    );

    // Start recording and send the microphone input to the Speech API
    recorder
    .record({
        sampleRateHertz: sampleRateHertz,
        threshold: 0, //silence threshold
        recordProgram: 'rec', // Try also "arecord" or "sox"
        silence: '5.0', //seconds of silence before ending
        endOnSilence: true,
        thresholdEnd: 0.5
    })
    .stream()
    .on('error', console.error)
    .pipe(recognizeStream);

    console.log('Listening, press Ctrl+C to stop.');
    // [END micStreamRecognize]
}

app.use(cors());

app.use('/api/speech-to-text/',function(req, res){
    speechFunction(function(err, result){
        if (err) {
            console.log('Error retrieving transcription: ', err);
            res.status(500).send('Error 500');
            return;
        }
        res.send(result);
    })
});

// app.use('/api/speech-to-text/', function(req, res) {
//     res.speechFunction();
// });

// app.get('/speech', (req, res) => res.speechFunction);

app.listen(port, () => {
    console.log(`Listening on port: ${port}, at http://localhost:${port}/`);
});

React
import React, { Component } from 'react';
import './App.css';

class App extends Component {

  constructor() {
    super()
    this.state = {
    }
  }

  onListenClick() {
    fetch('http://localhost:3002/api/speech-to-text/')
      .then(function(response) {
        console.log(response);
        this.setState({text: response});
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  render() {
    return (

        <button onClick={this.onListenClick.bind(this)}>Start</button>

{this.state.text}

    );
  }
}

export default App;

A: Replace onListenClick() code with the following
async onListenClick(){
const response= await axios.get('http://localhost:3002/api/speech-to-text/')
console.log(response)
this.setState(text:response.data)
}

I am trying to figure out how to stop the google api by clicking on a button. But above code will bring data on the react


text:
Q: how to implement a QAbstractItemModel for an already existing tree-like data structure without copy? After reading the docs and examples of QAbstractItemModel and QModelIndex, I am still confused on how to properly implement the model for a QTreeView.
Since I want to provide a model for an existing hierarchical data structure, I'm avoiding using QTreeWidget or QStandardItemModel and the related issues with data duplication and synchronization. However, I failed to implement a working item model (too many issues, it is not useful to post my code).
After reading this answer it seems clear that QModelIndex does not contain hierarchical information, but simply relies on the model to tell the parent of a given index. Consequently it does not seem possible to provide an abstract tree model for an existing data structure without defining at least another helper class for storing such relation. But still, I cannot implement properly the model.
Suppose the data structure is this simple one:
struct Property {
    QString name;
    QString value;
};
struct Node {
    QString name;
    QVector<Property> properties;
};
struct Track {
    int length;
    QString channel;
};
struct Model {
    QVector<Node> nodes;
    QVector<Track> tracks;
};

where Model is the toplevel one, and it resembles a tree.
The tree displayed in the QTreeView could look like this:
Model
  ├─Nodes
  │  ├─Node "node1"
  │  │  └─Properties
  │  │     ├─Property property1 = value1
  │  │     └─Property property2 = value2
  │  └─Node "node2"
  │     └─Properties
  │        └─Property property1 = someValue
  └─Tracks
      ├─Track 1, ...
      ├─Track 2, ...
      └─Track 3, ...

How the QAbstractItemModel subclass should be implemented to access the existing data without copy?

A: Here's my solution to the problem.
First of all, my initial guess that QModelIndex is incapable of storing the parent-child relationship is correct. In fact the method QModelIndex::parent simply calls QAbstractItemModel::parent, and the task of implementing the parent method is left to the model class. When the underlying model is a proper tree, pointer to tree nodes can be stored in the QModelIndex class, but in my case we are dealing with a "virtual" tree and this relationship is not available. Thus we are forced to introduce some kind of extra storage to be able to tell where we are in the tree. If QModelIndex natively supported having a pointer to the parent index, this problem would have been solved much more easily. But since QModelIndex is a value class, we cannot have a pointer to parent, but rather we have to store all the parent indices inside the QModelIndex class, and maybe the Qt developers had some good way to not do so. So I stored a QVector<QModelIndex> in the internal-pointer field of QModelIndex. There are some things to take care of, like avoiding allocating more than necessary of such indices, and also to remember freeing the memory when those are no more needed (we can't use QObject hierarchy here). There may be additional problems to take care of when the model is read-write, but in this case I'm dealing with a read-only model.
My implementation follows. Methods rowCount and data define this specific virtual tree. The other methods can be abstracted away in a class that can be re-used.
class MyModel : public QAbstractItemModel
{
    Q_OBJECT

private:
    struct IndexData
    {
        QVector<QModelIndex> parents;
    };

public:
    explicit MyModel(QObject *parent = nullptr);
    ~MyModel();

    QVariant data(const QModelIndex &index, int role) const override;
    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
    QModelIndex parent(const QModelIndex &index) const override;
protected:
    IndexData * indexData(const QModelIndex &index) const;
    QList<int> indexPath(const QModelIndex &index) const;
    QString indexString(const QModelIndex &index) const;
    QString indexString(int row, int column, const QModelIndex &parent) const;
public:
    int indexDepth(const QModelIndex &index) const;
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    Qt::ItemFlags flags(const QModelIndex &index) const override;

private:
    QMap<QString, IndexData*> indexData_;
    Model model;
};

implementation:
MyModel::MyModel(QObject *parent)
    : QAbstractItemModel(parent)
{
    model.nodes.resize(2);
    model.nodes[0].name = "node1";
    model.nodes[0].properties.resize(2);
    model.nodes[0].properties[0].name = "property1";
    model.nodes[0].properties[0].value = "value1";
    model.nodes[0].properties[1].name = "property2";
    model.nodes[0].properties[1].value = "value2";
    model.nodes[1].name = "node2";
    model.nodes[1].properties.resize(1);
    model.nodes[1].properties[0].name = "property1";
    model.nodes[1].properties[0].value = "someValue";
    model.tracks.resize(3);
    model.tracks[0].length = 2;
    model.tracks[0].channel = "A";
    model.tracks[1].length = 4;
    model.tracks[1].channel = "B";
    model.tracks[2].length = 3;
    model.tracks[2].channel = "C";
}

MyModel::~MyModel()
{
    for(auto v : indexData_) delete v;
}

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid() || role != Qt::DisplayRole) return {};

    int d = indexDepth(index);
    auto path = indexPath(index);

    if(d == 1) return "Model";
    if(d == 2 && path[0] == 0 && path[1] == 0) return "Nodes";
    if(d == 2 && path[0] == 0 && path[1] == 1) return "Tracks";
    if(d == 3 && path[0] == 0 && path[1] == 0) return QString("Node \"%1\"").arg(model.nodes[path[2]].name);
    if(d == 4 && path[0] == 0 && path[1] == 0) return "Properties";
    if(d == 5 && path[0] == 0 && path[1] == 0 && path[3] == 0) return QString("Property %1 = %2").arg(model.nodes[path[2]].properties[path[4]].name, model.nodes[path[2]].properties[path[4]].value);
    if(d == 3 && path[0] == 0 && path[1] == 1) return QString("Track %1...").arg(index.row() + 1);
    return {};
}

QModelIndex MyModel::index(int row, int column, const QModelIndex &parent) const
{
    QString dataKey = indexString(row, column, parent);
    auto it = indexData_.find(dataKey);
    IndexData *data;
    if(it == indexData_.end())
    {
        data = new IndexData;
        const_cast<MyModel*>(this)->indexData_.insert(dataKey, data);
        if(parent.isValid())
        {
            data->parents.append(parent);
            data->parents.append(indexData(parent)->parents);
        }
    }
    else
    {
        data = it.value();
    }
    return createIndex(row, column, data);
}

QModelIndex MyModel::parent(const QModelIndex &index) const
{
    if(!index.isValid()) return {};
    auto data = indexData(index);
    if(data->parents.empty()) return {};
    return data->parents.at(0);
}

MyModel::IndexData * MyModel::indexData(const QModelIndex &index) const
{
    if(!index.internalPointer()) return nullptr;
    return reinterpret_cast<IndexData*>(index.internalPointer());
}

QList<int> MyModel::indexPath(const QModelIndex &index) const
{
    QList<int> path;
    auto data = indexData(index);
    for(int i = data->parents.size() - 1; i >= 0; i--)
        path.push_back(data->parents[i].row());
    path.push_back(index.row());
    return path;
}

QString MyModel::indexString(const QModelIndex &index) const
{
    return indexString(index.row(), index.column(), index.parent());
}

QString MyModel::indexString(int row, int column, const QModelIndex &parent) const
{
    QString pre = parent.isValid() ? indexString(parent) + "." : "";
    return pre + QString("[%1,%2]").arg(row).arg(column);
}

int MyModel::indexDepth(const QModelIndex &index) const
{
    if(!index.isValid()) return 0;
    return 1 + indexDepth(index.parent());
}

int MyModel::rowCount(const QModelIndex &parent) const
{
    if(!parent.isValid()) return 1; // root item

    int d = indexDepth(parent);
    auto path = indexPath(parent);

    //if(d == 0) return 1; // root item
    if(d == 1) return 2;
    if(d == 2 && path[0] == 0 && path[1] == 0) return model.nodes.size();
    if(d == 2 && path[0] == 0 && path[1] == 1) return model.tracks.size();
    if(d == 3 && path[0] == 0 && path[1] == 0) return 1;
    if(d == 4 && path[0] == 0 && path[1] == 0 && path[3] == 0) return model.nodes[path[2]].properties.size();
    return 0;
}

int MyModel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

Qt::ItemFlags MyModel::flags(const QModelIndex &index) const
{
    if(index.isValid()) return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
    return {};
}

A: You are incorrect, you can totally expose any tree structure as QAbstractItemModel without any additional structuring information. You do however have to bend the rules and abuse things a little. You can in fact have a perfectly usable model with an implementation of parent() that returns a default constructed invalid index, while it is an abstract method and it has to be implemented, it doesn't really need to do actually do anything meaningul.
As you already mentioned - the index does give you an opaque pointer to store a data reference. And since tree models have a fixed column count of 1, this leaves the column in the index free to use as some typeid or index. Now you have a way of knowing what each of those opaque pointers actually points to, so you can select the proper code path to retrieve row count and data. Those are the ones that you really do need to implement. Most likely index() too if you want to use some stock model view, but if you explicitly request children indices in a parent delegate, you can even get away with a dud implementation for index() as well.
Now, if your tree nodes do not keep references to their parents, obviously you will not be able to go down the tree directly. What you can do tho is, whatever your current index is, do not have it just free floating, but keep a stack of all the parent indices up from the root node. And now you can go down, by simply keeping breadcrumbs as you went up. You may not even need an explicit stack, in most cases you will be able to get the relevant information to construct the parent index from the parent delegate.


text:
Q: How can I create dynamic text views according to a selected integer from a spinner?
03-05 11:31:07.042    1897-1897/com.example.project.a D/AndroidRuntime﹕ Shutting down VM
      --------- beginning of crash
  03-05 11:31:07.050    1897-1897/com.example.project.a E/AndroidRuntime﹕ FATAL
EXCEPTION: main
      Process: com.example.project.a, PID: 1897
      java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.project.a/com.example.project.a.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.removeAllViews()' on a null object reference
              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)

public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) {
        //   Toast.makeText(getApplicationContext(),"The day qqq"+arg0.getItemAtPosition(arg2).toString(),Toast.LENGTH_LONG).show();
        String control2=arg0.getItemAtPosition(arg2).toString();

       int  noOfBulb= (int) spinner1.getSelectedItem();
        final TextView tryText2=(TextView)findViewById(R.id.textView);
        tryText2.setText("No"+noOfBulb);

        mdynamiclayout = (LinearLayout) findViewById(R.id.dynamiclayout);
        mdynamiclayout.removeAllViews();//need to remove the view before it create
        for (int i = 0; i < noOfBulb; i++) {//6 is your selected item from spinner it can be any nymber
            TextView t = new TextView(MainActivity.this);
            t.setText("value" + i);
            //  t.setTextSize(20);
            //  t.setTextColor(Color.BLUE);
            mdynamiclayout.addView(t);
        }

    }

    public  void onNothingSelected(AdapterView<?> arg0){}

}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
        SelectBulbs();

    rl = (RelativeLayout) findViewById(R.id.rl);

    tv1 = new TextView (MainActivity.this);

    tv1.setText("Dynamic TextView");

    tv1.setTextColor(Color.RED);

    tv1.setTextSize(20);

    RelativeLayout.LayoutParams params1=new RelativeLayout.LayoutParams
            ((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
    params1.leftMargin=115;
    params1.topMargin=120;

   rl.addView(tv1);

public class Unit {
    private  String  _bulbNo;

    public  Unit(String bulbNo) {

        _bulbNo = bulbNo;

    }
    public  String getBulbNo(){
        return  _bulbNo;
    }

}
// I created this class

 private  void addBulbsFans(String bulb)
    {
        Units.add(new Unit(bulb));
    }

//I add this method to MainActivity.java .After this i need to know how  to pass the spinner value from a buttonclick event.

A: You can simply convert selected String to integer by following
 int value = Integer.valueOf(spiner.getselecteditem);

A: You use Integer.valueOf(), in your case it would be like that:
String[] bulbs = {"0","1","2","3","4","5"};
Integer[] bulbsConvert = new Integer[6];
//Array to int
for(String item : bulbs){
   bulbsConvert.add(Integer.valueOf(item));
}

A: If you want to create a dynamic textview in vertical order then create LinearLayout in xml and Orientation as Vertical as like below
  <LinearLayout
        android:id="@+id/dynamiclayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/registerlayout"
        android:layout_below="@+id/registerlayout"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="34dp"
        android:orientation="vertical" >
    </LinearLayout>

Then add below line of code in your activity
private LinearLayout mdynamiclayout;

mdynamiclayout = (LinearLayout) findViewById(R.id.dynamiclayout);

        mdynamiclayout.removeAllViews();//need to remove the view before it create
        for (int i = 0; i < 6; i++) {//6 is your selected item from spinner it can be any nymber
            TextView t = new TextView(MainActivity.this);
            t.setText("value" + i);
            mdynamiclayout.addView(t);
        }

Passing one activity to another activity :
Intent intent_value = new Intent(Mainactivity.this,
                yoursecondactivity.class);
        intent_value.putExtra("key", value);
        intent_value.putExtra("key2", value2);
        startActivity(intent_value);

Retrieve value:
 Intent getValues = getIntent();
    String value1 = getValues.getStringExtra("key");

Let me know if you need any help


text:
Q: MDX / Excel CUBEMEMBER() with condition on other table I'd like to select a string value from column [foo] where the condition of [bar] is true. The "cube" is actually a Power BI model which i'm trying to select more dynamically with cube functions because a pivot table isn't suitable for all requirements.
Both tables have a simple n:1 relationship and playerid is the key.
tbl_1.[playerid], tbl_1.[foo]
tbl_2.[playerid], tbl_2.[bar]
Dynamic value for the condition comes from excel cell A1 in this mockup.
This is what i'm trying to do but i can't figure out the syntax and google does not offer many references (feel free to link anything that could help because i can't seem to find anything).
=CUBEMEMBER("myModel";"[tbl_1].[foo].&[tbl_2].[bar].["& A1 &"]")

I would be delighted to have a solution which would accept more than 1 condition.
I also tried to go from "convert to formulas" button in Excel -> Pivot Table -> OLAP-Tools but this hardcodes the condition and puts curly braces around it, so no cell reference is possible. If someone could explain the curly braces syntax, that would be nice too. Thanks.
=CUBEELEMENT("myModel";{"[tbl_2].[bar].&[playerid]"."[tbl_1].[foo].&[HardcodedValueImTryingToGet]"})


text:
Q: How do I make index.php will control anything in PHP Firstly, I don't know what to call this thing :) I want to know the key, structure and example how to achieve my goal.
Example, I don't want create separate file like register.php, login.php, about.php faq.php. Here I want the register, login about, faq ,etc will handle by index.php by example, maybe something like index.php?p=register
How do I create page something like that and what this structure called in PHP programming. Let me know.

A: In index.php?p=register the part after ? is called "Query String". PHP will by default parse it for you and provides the superglobal $_GET. Just try it out yourself
var_dump($_GET);

A: I'm not sure what the whole thing is called, but if you're using index.php like that, it's called a FrontController. It's how MVC frameworks work:
/index.php?q=ctrl/action
/index.php/ctrl/action
/ctrl/action

They're all handled by/in index.php using "ctrl/action"

A: To provide a more appropriate answer using Neals code, use basename to filter out non-essential file information:
$page = isset($_GET['p'])?basename($_GET['p']):'main';

include_once "$page.php";

You could also create a "white list" to ensure that only the proper files get included:
 $whiteList = array('faq', 'register', 'profile');
 $page = (isset($_GET['p']) && in_array($_GET['p'], $whiteList))?basename($_GET['p']):'main';

 include_once "$page.php";

Both ways should be secure, obviously, the white list will be a bit more so. This tact, depending on how you do is generally referred to as "BootStrapping" IE, one entrance page to access the rest.

UPDATE
To further the security, I would set a variable, $included would be sufficient, to add to the pages that are being included. This would prevent direct access to them (assuming that register_globals is turned off like it should be, so something like:
 $whiteList = array('faq', 'register', 'profile');
 $page = (isset($_GET['p']) && in_array($_GET['p'], $whiteList))?basename($_GET['p']):'main';

 $included = true;
 include_once "$page.php";

Then on $page.php at the top you would have something like:
<?php

if (!$included)
       die('Accessing the file directly is not allowed.');

Which would prevent calls to http://yoursite.com/register.php from being allowed to dish out the file. This has it's negatives to it. Instead of putting the files you are going to be including in the webroot, I would put them outside of the webroot or in an .htaccess protected directory, which would ensure that users could not access them directly and must access them through the index.php.

A: You want to look up php templates or even html iframe.  There are several ways to do this, but some are better than others.  In asp.net it's called a MasterPage.  Hopefully some of these terms help you out.

A: If you really want to do something like this, then you can use the get field, but you need to predefine your pages, so for this request: index.php?p=my_page
<?php

$page = $_GET['p'];

$pages = array(
   'my_page' => 'mypage.php',
   'another_page' => 'another.php',
   ...
);

$include = $pages[$page];

if(!empty($include)) {
   include_once($include);
} else {
   echo 'No such page';
}
?>

This keeps the include completely separate from what is passed on the URL so there is no chance for risky things to get passed.


text:
Q: Outputting a string of HTML I'm adding my HTML to a var:
$html = '';
$html .= '
';
$html .= '
hello
';
$html .= '
';
....
echo $html

When I view the page's source the above is all output on one line. How can I fix it so that we see the layout as you would if it was written:

hello

    ...

A: Could always do this:
?>

hello

<?php

BUT keep in mind that there is an important difference between "all mashed together" and "nicely spaced out": whitespace will cause empty text nodes to be added, which may interfere with layouts (if using display:inline-block) or JavaScript (if using childNodes). It also takes up extra unnecessary bandwidth. Use what is most appropriate.

A: Add newlines with \n and tabs with \t:
$html = '';
$html .= "
\n";
$html .= "\t
hello
\n";
$html .= "
\n";

A: You can add all at once:
$html = '

hello

';

A: Try using the PHP constant PHP_EOL.
$html = '';
$html .= '
' . PHP_EOL;
$html .= '
hello
' . PHP_EOL;
$html .= '
' . PHP_EOL;


text:
Q: Busca em Profundidade com Prolog - como limitar profundidade? Estou implementando uma busca em profundidade em grafos em Prolog, já tenho o seguinte:
%arestas:

edge(c4,b4).
edge(b4,b3).
edge(b3,a3).
edge(b3,c3).

%determina que o grafo é nao direcionado
edge(V1, V2) :- edge(V2, V1).

%busca em profundidade
dfsB(Node,Solution) :- dfsB3(Node, [], Solution).
dfsB3(Node, History, [Node|History]) :- goal(Node).

dfsB3(Node,History,Solution) :- sucessor(Node, Node1), not(member(Node1,History)), dfsB3(Node1,[Node|History],Solution).

sucessor(X,Y) :- edge(X,Y). %esta certo?

Na dfs, History é uma lista dos nós que já foram visitados.
Estou em dúvida se a sucessor(X,Y) está implementada corretamente.
E ao rodar uma consulta dfs(c4,a3) (que era pra rodar porque tem caminho) o SWI-Prolog fica executando e não termina. Assim, acredito que eu preciso limitar a profundidade da busca... como posso fazer isso?

A: Na realidade, ao utilizar History e verificar se o nó já faz ou não parte de History, você já está limitando a busca e evitando nós repetidos. Não é necessário limitar artificialmente a profundidade (tipo buscar até uma profundidade X arbitrária).
Seu problema é que você usa tanto fatos edge para representar seu grafo quanto uma regra edge que visita o caminho inverso. E é essa regra que entra num loop infinito, pois nela você não checa o histórico pra ver se um nó já foi visitado ou não. Seria melhor não ter a regra:
edge(V1, V2) :- edge(V2, V1). % Causa loop infinito!

E sim fazer essa visita em duas direções na relação sucessor:
sucessor(X,Y) :- edge(X,Y). % sim, esta certo!
sucessor(X,Y) :- edge(Y,X). % faz a simetria aqui

Isso deve ser suficiente pra resolver seu problema. Mas se ainda assim quiser saber como limitar a profundidade de busca, sugiro colocar um parâmetro adicional Profundidade e verificar se ele é ou não maior que zero antes de continuar a busca:
dfsB(Node,Solution) :- dfsB3(Node, [], Solution, 5). % Máximo de 5 níveis de profundidade

dfsB3(_, _, _, 0) :- !, fail. % Falha imediatamente se o nível chegou a zero
dfsB3(Node, History, [Node|History], _) :- goal(Node).
dfsB3(Node,History,Solution,Profundidade) :-
    sucessor(Node, Node1),
    not(member(Node1,History)),
    P1 is Profundidade - 1, % Diminui 1 na profundidade máxima de busca
    dfsB3(Node1,[Node|History],Solution,P1).


text:
Q: R: Extract values that have the same row and header names I am trying to extract the values (from a table) that have the same row and column headers. For example, I have a table like this:
    A   B   B   C   D   E   E
A   1   2   3   4   5   6   7
B   8   9   10  11  12  13  14
C   15  16  17  18  19  20  21
D   22  23  24  25  26  27  28
E   29  30  31  32  33  34  35

And I want to extract values to get something like this:
A   1
B   9
B   10
C   18
D   26
E   34
E   35

Any ideas on how I could do this? It has to work for any number of rows and columns, and there could be more than two columns with same headers.

A: You can sapply across the row/column names to test equality, and then use that index to assemble the data.frame:
i <- sapply(colnames(mat), `==`, rownames(mat))    # or i <- outer(rownames(mat), colnames(mat), `==`)

i
##          A     B     B     C     D     E     E
## [1,]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
## [2,] FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE
## [3,] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
## [4,] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE
## [5,] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE

df <- data.frame(name = colnames(mat)[colSums(i) > 0],    # if unsure of dimensions, name = if(nrow(mat) > ncol(mat)){rownames(mat)[rowSums(i) > 0]}else{colnames(mat)[colSums(i) > 0]}
                 value = mat[i])

df
##   name value
## 1    A     1
## 2    B     9
## 3    B    10
## 4    C    18
## 5    D    26
## 6    E    34
## 7    E    35

Data
mat <- structure(c(1L, 8L, 15L, 22L, 29L, 2L, 9L, 16L, 23L, 30L, 3L,
    10L, 17L, 24L, 31L, 4L, 11L, 18L, 25L, 32L, 5L, 12L, 19L, 26L,
    33L, 6L, 13L, 20L, 27L, 34L, 7L, 14L, 21L, 28L, 35L), .Dim = c(5L,
    7L), .Dimnames = list(c("A", "B", "C", "D", "E"), c("A", "B",
    "B", "C", "D", "E", "E")))

A: tab = structure(c(1L, 8L, 15L, 22L, 29L, 2L, 9L, 16L, 23L, 30L, 3L, 10L, 17L, 24L, 31L, 4L, 11L, 18L, 25L, 32L, 5L, 12L, 19L, 26L, 33L, 6L, 13L, 20L, 27L, 34L, 7L, 14L, 21L, 28L, 35L), .Dim = c(5L, 7L), .Dimnames = list(c("A", "B", "C", "D", "E"), c("A", "B", "B", "C", "D", "E", "E")))
cols = colnames(tab)[col(tab)]
rows = rownames(tab)[row(tab)]
ind = (cols == rows)
a = tab[ind]
names(a) = cols[ind]


text:
Q: Changing code in node_modules does not work in hot reload regardless of the bundler So I've been trying to debug library code (@mui/material) in a sandbox project in Chrome, but it doesn't work with either Vite or CRA - placing a console.log or debugger line inside library code (yes, I tried build folders of other libraries too) does not work. On the other hand, setting breakpoints on the same code in DevTools DOES work. WHat is the issue here, can it be hardware or something else I am misusing?

A: Specifically talking about Webpack which is used by CRA, it makes assumption that node_modules is not changed by the application. It is only meant to be changed by package managers (npm, yarn, etc.) during installation process.
In case of HMR, it generate a snapshot of your filesystem (keeping files in memory) for performance reasons. You can opt-out of this by using snapshot.managedPath property:
// webpack.config.js
module.exports = {
  // ...other configuration
  snapshot: {
    managedPaths: []
  },
};

Read this comment for further details on why it is not recommended.


text:
Q: Business Objects - Containers or functional? This is a question I asked a while back on SO, but it may get discussed better here...
Where I work, we've gone back and forth on this subject a number of times and are looking for a sanity check. Here's the question: Should Business Objects be data containers (more like DTOs) or should they also contain logic that can perform some functionality on that object.
Example - Take a customer object, it probably contains some common properties (Name, Id, etc), should that customer object also include functions (Save, Calc, etc.)?
One line of reasoning says separate the object from the functionality (single responsibility principal) and put the functionality in a Business Logic layer or object.
The other line of reasoning says, no, if I have a customer object I just want to call Customer.Save and be done with it. Why do I need to know about another class to save a customer if I'm consuming the object?
Our last two projects have had the objects separated from the functionality, but the debate has been raised again on a new project.
Which makes more sense and why??

A: If you consider that a Customer is a part of the domain model, then it makes sense (especially within the context of DDD but not limited to it) to have have both properties and operations for that object.
With that said, however, I think that the example you've used is a poor one, and is a cause of the argument. If you're talking about persistence, then Customers generally don't 'save' themselves; whatever you're using for persistence will. It makes sense that any kind of persistence should belong to the persistence layer/partition. This is generally the thinking behind the repository pattern.** A method like Customer.UpgradeWarranty() or Customer.PromoteToPreferred() makes the argument clearer.
This also doesn't remove the possibility for having DTOs. Consider the situation where you're going to pass customer information to a remote service for instance. It may not make sense for a customer to create a DTO of itself for transport, that's an architectural concern, but a case could be made for it in the persistence or network layer/partition/code/what-have-you. In that case, such an objectcould have methods that look like this
public static CustomerDTO GetDTO(Customer c) { /* ... */ }

public static Customer GetCustomer(CustomerDTO cdto) { /* ... */ }

So, in summary, it makes perfect sense to have operations on a domain object that are congruent with logical operations in the domain.
Google for 'Persistence Ignorance' for a number of good discussions on the matter (this SO question, and its accepted answer is a good place to start).
** This gets a bit muddied with certain OR/M software where you are forced to inherit from a persistent base that has a 'Save' method.

A: I actually just recently reworked some code to separate the objects from the data. The reason is that the data is obtained through a separate service, and it is much easier to just pass the raw data to/from the server instead of passing the entire object back and forth and having to deal with validation errors on the server.
For small projects, having objects contain their business logic and data is probably fine, but for large projects, or projects that might expand over time, I'd definitely separate the layers.

A: I think both ways of doing it can have their benefits, but I would look at it from an object oriented or domain driven view: what are the responsibilities of the different classes and objects.
So, I would ask myself this, in your concrete case: should a customer know how to save itself?
To me, the answer would be no: logically to me it doesn't make sense, and a customer should not have to know anything about any persistence framework at all (separation of responsibilities).
As for SnOrfus' examples with Customer.UpgradeWarranty() or Customer.PromoteToPreferred(), they are obviously more business logic oriented than Customer.Save(). There are different approaches to this, but again if you ask yourself if a customer is supposed to be able to upgrade his warranty, the answer might be both yes or no, depending on how you look at it:

*

*yes: a customer can of course upgrade his warranty

*no: a customer could ask to be upgraded, but the upgrade is done by someone else

Back to your original question; which way makes more sense will probably depend on who you ask and their preferred method, but the most important thing is probably to stick to one way of doing it.
In my experience, though, separating data and (business) logic makes for a simpler architecture, although not as exciting.

A: I think you're specifically talking about the difference between the ActiveRecord pattern and the Repository pattern.  In the former, the entities know how to persist themselves, and in the latter, the repository knows about persistence.  I think the latter offers a better separation of concerns.
In a broader sense, if the entities act more like a data structure, then they shouldn't have behaviors, but if they have behaviors, then they shouldn't be used like a data structure.  Example:
Data Structure:
class CustomerController
{
    public int MostRecentOrderLines(Customer customer)
    {
        var o = (from order in customer.Orders
                orderby order.OrderDate desc
                select order).First();
        return o.OrderLines.ToList().Count;
    }
}

Non-Data Structure:
class Customer
{
    public int MostRecentOrderLines()
    {
        // ... same ...
    }
}

In the first case, you can navigate the data structure tree of your model without a problem, from anywhere in your working code, and that's ok, because you're treating it like a data structure.  In the latter case, Customer is more like a service for a given customer, so you shouldn't call methods on the result.  All the things you want to know about the Customer should be available by calling a method on the Customer object.
So do you want your entities to be data structures or services?  For consistency, it seems better to stick with one.  In the former case, put your "service"-type logic somewhere else, not in the entity.

A: I cannot really answer your question but I find it funny we are also having this discussion in one of our projects at school. Myself would like to seperate logic from data. But lots of my classmates say the object has to hold all the logic AND data.
I will try to summerize the facts they bring up:

*

*A business class object represents a thing, so all data AND logic should be contained. (eg if you want to open a door, you do it yourself, you don't ask someone else. bad example I know)

*Easier to understand the code and functionality of a bu object.

*Less complexity in the design
I am telling them they are lazy and I would make it like this:

*

*Yes business classes represents things, so it holds data. But it feels wrong to save yourself, or even copy. You cant do that in rl.

*Making the object responsible for everything makes it not good for durability and maintibility in the future. If you have a seperate class that is responsible for saving, if you add a new object to the design, youcan easily implement its save funtion. instead of coding it all again in that class.

*By having one object able to persist data, that object can hold a database connection and all database traffic is guided at that object. (basiccally its the data acces layer) otherwise all the Business object would have to hold a connection. (which adds complexity)
Well one way or another, I am going to ask a teacher. When I have done that, I will post his answer here too if you would like. ;)
edit:
I forgot to mention this project was about a book store.

A: The answer is really going to depend on what your architecture/design is - a DDD architecture with a domain model is going to be very different from a CRUD data-centric model when it comes to object design.
In general though, bear in mind that in object-orientated-design you are trying to encapsulate state and expose behaviour. This means that you will usually try to get the state associated with a behaviour as close as possible to that behaviour - when you fail to do this you are forced to expose state in one form or another.
In a domain model you want to separate out the business model from infrastructure concerns - so you absolutely want to avoid methods like '.Save'. I don't remember the last time I "saved" a customer in real life!
In a CRUD application then the data is the first class citizen so a ".Save" is entirely appropriate.
Most sizable real-world applications will have a mixture of these paradigms - domain model where there are rapidly changing or complex business rules, DTOs for transferring data across boundaries, CRUD (or something between CRUD and a domain model, such as activerecord) elsewhere. There is no one-size fits all rule.

A: I've been mulling over the same question for a while - I think the data component and the logic component must be seperate. I believe this because it gets you into the right frame of mind as regarding business logic as an interface to the data that provides meaning.
I'd also mod up Scott Whitlock's point from above (except I have no points being a new member), data or business logic classes shouldn't really have to worry about how the object is stored persistantly.
That being said, if you're dealing with an existing product, as long as you have clean, contractual interfaces - that's OK and maintainable too...


text:
Q: How to make Yahoo Messenger work? Just curious if anyone has had any luck or made any progress getting Yahoo Messenger to work with Ubuntu?  I know empathy and Viber and a lot of other work, but there are parts of Yahoo that make it a better fit for some of the people I am trying to convince to switch to Ubuntu.

A: The best you can get currently seems to be gyache. Even though it is old and not maintained anymore. From the website:

This Yahoo! client for Linux operating system supports almost all of the features you would expect to find on the official Windows Yahoo! client: Voice chat, webcams, faders, 'nicknames', audibles, avatars, display images, and more. Yet, it remains very light-weight and memory-friendly. GyachE Improved uses Gtk-2 for its user interfaces (Gtk-2 2.0.6 or better required).

You need to install from source though. From install.txt:
Steps for building a gyachi executable

*

*use the autogen script to generate a configure script:
./autogen.sh

*run configure, with any options that you might prefer:
./configure --disable-rpath --enable-maintainer-mode --prefix /usr

*To generate a spec file
make gyachi.spec

*To build an image that will be installed over existing executables
(not recommended):
make
make install

A: Pidgin
You can also use Pidgin for meeseging in Yahoo.
Can installed with :
sudo apt-get install pidgin


text:
Q: Return error from php to dropzone.js I would like to return an error on a case from my php code that handles the upload.
Currently if the php upload fails the JS still thinks it successes which I presume is to do with the fact it returned fine.
I have tried returning false instead of a string but that still runs the this.on('success') function.
PHP
public function imageUpload(){
    //Сheck that we have a file

    if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {

      //Check if the file is JPEG image and it's size is less than 350Kb
      $filename = basename($_FILES['file']['name']);
      $ext = substr($filename, strrpos($filename, '.') + 1);

      if (($ext == "jpg") && ($_FILES["file"]["type"] == "image/jpeg") &&
        ($_FILES["file"]["size"] < 3500000)) {

        //Determine the path to which we want to save this file
          $newname = '/home/anglicvw/public_html/newdev/app/templates/default/images/testimages/'.$filename;
          //Check if the file with the same name is already exists on the server

          if (!file_exists($newname)) {

            //Attempt to move the uploaded file to it's new place
            if ((move_uploaded_file($_FILES['file']['tmp_name'],$newname))) {
               echo "It's done! The file has been saved as: ".$newname;
            } else {
               echo "Error: A problem occurred during file upload!";
            }
          } else {
             echo "Error: File ".$_FILES["file"]["name"]." already exists";
          }
      } else {
         echo "Error: Only .jpg images under 350Kb are accepted for upload";
      }
    } else {
     echo "Error: No file uploaded";
    }
}

JS
$(document).ready(function(){

            Dropzone.autoDiscover = false;

            var myDropzone = new Dropzone('div#imagesdropzone', { url: '/admin/imageUpload',
            parallelUploads: 100,
            maxFiles: 100,});
        });

        Dropzone.options.imagesdropzone = {
            init: function() {
                this.on('success', function( file, resp ){
                  console.log( file );
                  console.log( resp );
                });
                this.on('error', function( e ){
                  console.log('erors and stuff');
                  console.log( e );
                });
            }
        };

A: Yes, its right. You have to set an HTTP Header.
Have a look at:
https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-an-error-returned-by-the-server
If you have an HTTP Error and want to show it in the hover error message of DropzoneJS you can:
myDropzone.on("error", function(file, message, xhr) {
    var header = xhr.status+": "+xhr.statusText;
    $(file.previewElement).find('.dz-error-message').text(header);
  });

(You need jQuery for that code [$().find();])
The other way would be to return a JSON error message via PHP:
//define text for error message
$output['error'] = 'No Token';

//return right HTTP code
if( $error ){
    http_response_code (401);
}
else{
    http_response_code (200);
}

//set Content-Type to JSON
header( 'Content-Type: application/json; charset=utf-8' );
//echo error message as JSON
echo json_encode( $output );

A: Where does this.on('success') take the information about the success/failure of the (internal) PHP upload process?
I guess from the HTTP header's status code, which is 200 (OK) even if the upload failed (it just prints some error text).
I recommend you to set a 500 header if the upload fails.

A: Use below php code snippet
public function imageUpload(){
    //Сheck that we have a file

    if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {

      //Check if the file is JPEG image and it's size is less than 350Kb
      $filename = basename($_FILES['file']['name']);
      $ext = substr($filename, strrpos($filename, '.') + 1);

      if (($ext == "jpg") && ($_FILES["file"]["type"] == "image/jpeg") &&
        ($_FILES["file"]["size"] < 3500000)) {

        //Determine the path to which we want to save this file
          $newname = '/home/anglicvw/public_html/newdev/app/templates/default/images/testimages/'.$filename;
          //Check if the file with the same name is already exists on the server

          if (!file_exists($newname)) {

            //Attempt to move the uploaded file to it's new place
            if ((move_uploaded_file($_FILES['file']['tmp_name'],$newname))) {
               echo "It's done! The file has been saved as: ".$newname;
            } else {
               header('Error: A problem occurred during file upload!', true, 500);
               //echo "Error: A problem occurred during file upload!";
            }
          } else {
            header("Error: File ".$_FILES["file"]["name"]." already exists", true, 500);
             //echo "Error: File ".$_FILES["file"]["name"]." already exists";
          }
      } else {
        header("Error: Only .jpg images under 350Kb are accepted for upload", true, 500);
         //echo "Error: Only .jpg images under 350Kb are accepted for upload";
      }
    } else {
      header("Error: No file uploaded", true, 500);
     //echo "Error: No file uploaded";
    }
}