text:
Q: Setting a C# variable during a TFS build phase I'm really new to C# and TFS, I've setup a basic WPF app that uses continuous integration. The problem is that some users are not updating when they should, and we have no versioning control so to speak of. What I want to do is have a variable in the code like this.
public static string BuildNumber = "";

And have it populated during the online build process. That way we can show it in the title bar and when they call, we know instantly what we are dealing with. I assume this can be done in the "process variables" section. But really need step by step help here. Just want it to have the same format as the build that is "$(date:yyyyMMdd)$(rev:.r)_$(SourceBranchName)"
We are really new to this and know that we should be using proper build versions like 1.0.0.1 type thing. But are just really looking for a quick fix. So unless setting up proper versioning is really easy. Please don't try and steer me down that path, already on a steep learning curve here.
Thanks.

A: Caveat: I assume that you are using TFS 2015 or later and Build vNext (i.e. not using a Xaml Build).
Your question is easily solved using a Powershell Task as the first step of your build. At that point the build number is know and available in the ${env:BUILD_BUILDNUMBER} variable.
Say that the file containing the public static string BuildNumber = ""; line is in the root of your source directory and named BuildNumber.cs.
Then the Powershell code is similar to the following:
$pathToBuildNumber = "${env:BUILD_SOURCESDIRECTORY}\BuildNumber.cs"
$source = Get-Content $pathToBuildNumber
$source -replace 'public static string BuildNumber = "(.*)";',$env:BUILD_BUILDNUMBER | Out-File $pathToBuildNumber

A: According to my understanding, seems you want to overwrite your Build number with variables, you could do this through powershell script by using build variables:
1) First create a Powershell script like this

$FinalVersion=Some-Function-To-Calculate-Version
$BuildDefName = $Env:BUILD_DEFINITIONNAME
Write-Host "##vso[build.updatebuildnumber]$($BuildDefName)-$($FinalVersion)"

2) In your vNext build definition, for "Build number format" set
  it to anything.  It doesn't matter because the Build Number will be
  overwritten.
3) In the same vNext build definition steps, add the first step as a
  Powershell step, and set your script from step 1 to be executed.  You
  can later customize if you want to pass variables in order to
  calculate your build number.
4) Queue your build and see the results.

Another way please take a look at this similar question: Accessing the build revision number in Powershell script during TFS build


text:
Q: Jest: How to mock angular percentage pipe inside custom pipe? pipe.ts:
import { PercentPipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'conversion' })
export class ConversionPipe implements PipeTransform {
constructor(private readonly percentPipe: PercentPipe) {}

transform(value: number, info?: string): string {
if (!value) {
  return '';
}

return this.percentPipe.transform(value, info);

}

pipe.spec.ts:
import { PercentPipe } from '@angular/common';
import { LOCALE_ID }
from '@angular/core';
import { MockBuilder, MockRender } from
'ng-mocks';
import { ConversionPipe } from './conversion.pipe';

describe('ConversionPipe', () => {
   beforeEach(() =>
     MockBuilder(PercentPipe)
   );

   it('Add given digit count after the decimal point in final percentage value', () => {
     const fixture = MockRender(
       '{{ value | conversion : info }}',
       {
          value: 0.00431,
          info: '1.0-2'
       }
    ).nativeElement as HTMLElement;
   expect(fixture.innerHTML).toBe('+4.3%');
   });
});

it is throwing an error " ASSERTION ERROR: Expected localeId to be
defined [Expected=> null != undefined <=Actual]"

redpajama_set_name: RedPajamaStackExchange


text:
Q: findChessboardCorners gives unexpected results Here is my code
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include<opencv2/opencv.hpp>

#include<iostream>
//#include<vector>

using namespace cv;
using namespace std;

int main()
{
    VideoCapture cap = VideoCapture(0);
    int successes = 0;

    int numBoards = 0;
    int numCornersHor = 6;
    int numCornersVer = 4;

    int numSquares = (numCornersHor - 1) * (numCornersVer - 1);
    Size board_sz = Size(numCornersHor, numCornersVer);

    vector<Point2f> corners;

    for (;;)
    {
        Mat img;
        cap >> img;
        Mat gray;
        cvtColor(img, gray, CV_RGB2GRAY);
        if (img.empty()) break; // end of video stream
        imshow("this is you, smile! :)", gray);
        if (waitKey(1) == 27) break; // stop capturing by pressing ESC

    bool found = findChessboardCorners(gray, board_sz, corners, CALIB_CB_ADAPTIVE_THRESH);
    if (found == 1)
    {
        cout << corners.size()<<"\n";

        cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1));
        drawChessboardCorners(gray, board_sz, corners, found);
    }

    }

    cap.release();
        waitKey();
        return 0;
    }

The code is capturing frames from a webcam. If a chessboard is detected, the total number of found corners is printed out (I did it because I was not getting the same output as in the tutorial code and I wanted to find where the bug is).
The output:

A: First you should follow some ground rules:

*

*Do not use loose papers -> print/glue the chessboard on a flat plate

*Print it with a big white border to improve detection

*The chessboard has to be completly inside the image (not as in your example)

*Take several images with different positions of your chessboard

Second, you cant draw your contours into a 8-bit grayscale image, use an 8-bit color image instead.
And if i count correctly (count inner corners) your chessboard has the size (8,6).

A: I have the same problem, the number of corners is HUGE. After some search i found this solution Here.
For some reason findChessboardCorners function resizes the corners vector. I tried the solution above, it worked well with the output corners, but i still have assertion failed problem with cornerSubPix function.


text:
Q: Can Gram-Schmidt algorithm be applied to every set of vectors in ${\rm I\!R}^{n}$? I have the following question: "Can Gram-Schmidt algorithm be applied to every set of vectors in ${\rm I\!R}^{n}$?".I know that in the general case we apply it to the finite independent set of the vectors. But can we do that with the infinite set or dependent?

A: If the vectors are not linearly independent (which is automatically the case when there are more than $n$ vectors), at some step the algorithm asks you to divide by $0$. Indeed, the algorithm "makes" each input vector orthogonal to all previous ones by translating it parallel to the span of the previous ones. If the vectors is already in the subspace spanned by the previous vectors, this orthogonal vector must be the zero vector.


text:
Q: use jquery to capture form data and post using ajax call Newbie here. I am building an app in rails and I'm trying to use jquery to capture the values of multiple select boxes within a form. I've tried to simplify this down as much as possible.
form html:
<form action="/units" data-remote="true" id="add_form" method="post">

<select class="select_box" id="box_1">
<option value="1">1</option>
<option selected="selected" value="2">2</option>
<option value="3">3</option>
</select>

<select class="select_box" id = "box_2"
<option value="1">1</option>
<option value="2">2</option>
<option selected="selected" value="3">3</option>
</select>

*... additional select boxes...*

<input disable_with="Loading..." name="commit" type="submit" value="Submit" />

</form>

In my application.js I want to capture the selected value of each select box.
I've tried using serialize() but can't get it to work since the form is dynamically generated using javascript (i.e. is not part of the DOM when the page is initially loaded).
Since there a lot of form elements (~20) I want to avoid working through the form elements one-by-by to capture the data, e.g.
var val_1 = $("#box_1").find(":selected").val()
var val_2 = $("#box_2").find(":selected").val()
...

Is there some way I can capture all of the selected values of a given class of elements (i.e. .select_box) and store them in an array?
perhaps something along the lines of:
var form_data = $(".select_box").find(":selected").data()

or somehow loop through the elements of class .select_box ?
Just can't quite get my head around this one. Thanks!

A: The data() method is used to get the values of an element's data attributes.
You can use the serialize() method on the form element to retrieve the values of all elements within the form.
Or you can use the val() method to retrieve the value of each element.
i.e: $("#textfield_id").val(); // gets the value of a textfield

A: This is how you can get your relevant data:
var form_data = $(".select_box").find(":selected").map(function (index) {
            return ($(this))[0].value;
        });

and this is how you can convert it to JSON for sending to server:
JSON.stringify(form_data.get())

A: You should use serialize() to serialize (as Kyle said) form data, and then post the form. Try this:
$.post( "yourPageUrl", $( "#add_form" ).serialize() );


text:
Q: Method names for getting data containing a filter argument Me and our developers are no native english speakers and are not sure how to name methods that have arguments that are used to filter the return value.
Here are some example from our .NET code:
GetUserByRoleId(string roleId);

GetUsersFromGroupId(string groupId);

GetUserByGivenLicenseId(string licenseId);

*

*By

*From

*ByGiven

*FromGiven

What is a good convention to name such methods?

A: I would use ...By... because it is

*

*correct

*meaningful

*concise

However, i think this is primarily opinion based.


text:
Q: how to get specific key/value as environment variable into pod in kubernetes I have k8s configmap as below.
apiVersion: v1
kind: ConfigMap
metadata:
  name: config-map-data-test
  namespace: test
data:
  example1.properties: |
    profile_id=val1
    ENDPOINT=val2
    SECRETS_FILE_DIR=val3
  example2.properties: |
    key1=val11
    key2=val22

I want to use only profile_id from example1.properties inside pod as environment variable. How to get only specific key/value in this case?


text:
Q: WKWebView not working in Cocoa Touch Framework I have created sample app for Cocoa Touch Framework and have passed WKWebView with sample url. I have used that framework in one of the app, and try to open wkwebview from main class. Below is my code of cocoa touch framework. Its always showing me Could not signal service com.apple.WebKit.Networking: 113: Could not find specified service this message in console.
import UIKit
import WebKit

public class ConnectedAppController: UIViewController, WKNavigationDelegate {

    var webView : WKWebView!

  override public func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

    }

  public func opensampleWebView() {

    let myBlog = "https://www.google.com/"
    let url = NSURL(string: myBlog)
    let request = URLRequest(url: url! as URL)

    // init and load request in webview.
    webView = WKWebView(frame: self.view.frame)
    webView.navigationDelegate = self
    self.view.addSubview(webView)
    webView.load(request)
  }

  private func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
    print(error.localizedDescription)
  }
  public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print("Strat to load")
  }
  public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("finish to load")
  }

A: It's not obvious from your question, but I suspect you're calling opensampleWebView from a prepareForSegue call in another class.
Although you're correctly calling self.view.addSubview(webView) before webView.load(request), I suspect the view that you're attempting to add to hasn't been loaded yet.
If you call opensampleWebView() in viewDidLoad is there any difference?
override public func viewDidLoad() {
    super.viewDidLoad()
    opensampleWebView()
 }

A: You need to override the function loadView()
Swift 4
public class ConnectedAppController: UIViewController, WKNavigationDelegate {

    var webView : WKWebView!

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.webView.allowsBackForwardNavigationGestures = true
        let myBlog = "https://www.google.com/"
        if let url = URL(string: myBlog) {
            self.webView.load(URLRequest(url: url))
        }

    }

}


text:
Q: grep/print value of a key in json that is stored in a variable I have a variable with nested json,
a={
  "version": "3.0",
  "user": "unknown_unknown",
  "dateGenerated": "2020-07-08T11:53:23Z",
  "status": "OK",
  "data": [
    {
      "parameter": "t_2m:C",
      "coordinates": [
        {
          "lat": 39.23054,
          "lon": 9.11917,
          "dates": [
            {
              "date": "2020-07-08T15:53:23Z",
              "value": 25.1
            }
          ]
        }
      ]
    }
  ]
}

Looking for a way to grep the "value"  in the nested json (like the one highlighted) in variable a.
I'am using grep and jq but I can't show value, it shows "dates"
(echo $result | grep -Po '"dates":.*?[^\\],.*?[^\\]"')
but not just the value.
Any help?

A: You may also want to consider installing gron, which is a utility to "Make JSON greppable!".
With a defined as in your question,
echo $a | gron

returns
json.data = [];
json.data[0] = {};
json.data[0].coordinates = [];
json.data[0].coordinates[0] = {};
json.data[0].coordinates[0].dates = [];
json.data[0].coordinates[0].dates[0] = {};
json.data[0].coordinates[0].dates[0].date = "2020-07-08T15:53:23Z";
json.data[0].coordinates[0].dates[0].value = 25.1;
json.data[0].coordinates[0].lat = 39.23054;
json.data[0].coordinates[0].lon = 9.11917;
json.data[0].parameter = "t_2m:C";
json.dateGenerated = "2020-07-08T11:53:23Z";
json.status = "OK";
json.user = "unknown_unknown";
json.version = "3.0";

which does indeed make it easy to process:
$ echo $a | gron | sed -n '/value/{s/.* //; s/;//; p;}'
25.1

$ echo $a | gron | awk '/value/ {sub(/;/,""); print $NF;}'
25.1

A: Using Miller, with its default JSON array flattening:
$ mlr --ijson --onidx cut -f 'data:0:coordinates:0:dates:0:value' <<<"$a"
25.1

or regex-matching the flattened element name
$ mlr --ijson --onidx cut -r -f 'value$' <<<"$a"
25.1

A: You want the "value" from (the first object in the "dates" array) from (the first object in the "coordinates" array) from (the first object in the "data" array)
$ a='{"version":"3.0","user":"unknown_unknown","dateGenerated":"2020-07-08T11:53:23Z","status":"OK","data":[{"parameter":"t_2m:C","coordinates":[{"lat":39.23054,"lon":9.11917,"dates":[{"date":"2020-07-08T15:53:23Z","value":25.1}]}]}]}'
$ echo "$a" | jq -r '.data[0].coordinates[0].dates[0].value'
25.1


text:
Q: Multiple VirtualHosts files for subdomains in apache2 I'm new with apache2 and virtualHosts and all these things, I'm trying to set multiple subdomains, each in one file.
For example, I'll have
quentin-dommerc.com file in site-available :
<VirtualHost quentin-dommerc.com:80>
              DocumentRoot /var/www/
              ServerName quentin-dommerc.com
</VirtualHost>

and en.quentin-dommerc.com file in site-available :
<VirtualHost en.quentin-dommerc.com:80>
              DocumentRoot /var/www/en/
              ServerName en.quentin-dommerc.com
</VirtualHost>

But whatever the subdomain I go to, I'm always on quentin-dommerc.com :(
Note that I've a2ensite my files and they're well in site-enabled. I've also reloaded/restarted apache2. My CNAME are also set.

A: Try changing your VirtualHost entries to use your ip address instead of domain name. e.g. if you ip address is 1.1.1.1
<VirtualHost 1.1.1.1:80>
          DocumentRoot /var/www/
          ServerName quentin-dommerc.com
</VirtualHost>

<VirtualHost 1.1.1.1:80>
          DocumentRoot /var/www/en/
          ServerName en.quentin-dommerc.com
</VirtualHost>

You may also have to update your Listen lines to reflect using the ip address.


text:
Q: gtkmm + cmake (windows) Приветствую дамы и господа. Не могу автоматически "зацепить" директорию gtkmm с помощью CMake. CMakeList, CMake выводит, что gtkmm не найден (хотя gtkmm на C:/) и соответственно переменные пусты. В чем проблема и как ее решить?

A: Добрый день!
Проблема может быть в нескольких местах:

*

*Зависимости gtkmm3(например gtk-3) не установлены

*Отсутствует PkgConfig файл, указывающий где можно найти gtkmm3

*Переменная окружения(не windows, а POSIX окружения) PKG_CONFIG_PATH не охватывает директорию файла gtkmm-3.0.pc

Было бы прекрасно увидеть Ваш вывод команды
pkg-config --list-all | grep -i gtk
, чтобы понимать куда двигаться дальше


text:
Q: How to retrieve result set from postgres stored procedure(or function) using pg Hi I am working on a web app that uses postgres and some of the sql is in stored procedure/functon. If a function returns a cursor, how can we retrieve and process the resultset in nodejs? I am using pg (node-postgres). Following is the code for the test procedure that I would like to call from nodejs code.
drop table if exists tmp;
create table tmp
(
  x integer
);
drop function if exists t1;

create or replace function t1( p_value integer)
returns refcursor
language plpgsql
as $$
declare
  ref refcursor;
begin
  --insert into tmp(x) values(p_value);
  open ref for select x from tmp;
  return ref;
end
$$;

A: This is not how this is done in Postgres. Change it to a set-returning function:
create or replace function t1(p_value integer)
   returns table (x integer) --<< adjust here for the real column list
language sql
as $$
  insert into tmp(x) values(p_value)
  returning x; --<< adjust here for the real column list
$$;

Then use it as part of a SELECT statement:
select *
from t1(42);

Obviously the 42 can be a parameter from your programming language.


text:
Q: Android - getSupportFragmentManager returns null I am trying to get a specific instance of a fragment using it's tag, but I am using a viewpager, which makes things difficult. I used:
public Fragment getFragmentByPosition(int pos) {
    String tag = "android:switcher:" + R.id.pager + ":" + pos;
    FragmentManager fragmentManager = this.getSupportFragmentManager();
    Fragment fragment = fragmentManager.findFragmentByTag(tag);
    return fragment;
}

to find the fragment, but getSupportFragmentManager is returning null.
the above method is in the activity, outside of the viewpager adapter class, and I am so lost as to what to do here. Any help would be highly appreciated, thanks!

A: You can use SmartViewPager from here
https://gist.github.com/jacek-marchwicki/d6320ba9a910c514424d
Extend your view pager from this class and get the fragment using getActiveFragment method. You can also change the implementation of this method to get your fragment by TAG name.
public Fragment getActiveFragment(String name) {
    final Fragment fragmentByTag = fragmentManager.findFragmentByTag(name);
    if (fragmentByTag == null) {
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        fragmentManager.dump("", null, new PrintWriter(outputStream, true), null);
        final String s = new String(outputStream.toByteArray(), Charsets.UTF_8);
        throw new IllegalStateException("Could not find fragment via hacky way.\n" +
                "We were looking for name: " + name + "\n" +
                "Fragment with this name does not exists, or hack stopped working.\n" +
                "Current fragment manager dump is: " + s);
    }
    return fragmentByTag;
}


text:
Q: How do I get my gamble command to work? Or is there another way to write one? @commands.group(invoke_without_command=True)
@commands.cooldown(1, 8, commands.BucketType.user)
async def bet(self, ctx, amount=0):
  if amount == 0:
    await ctx.send("Please enter a valid amount you want to bet!")
  else:
    db = sqlite3.connect("main.sqlite")
    cursor = db.cursor()
    cursor.execute(f"SELECT money FROM main WHERE member_id = {ctx.message.author.id}")
    result = cursor.fetchone()
    if result is None:
      sql = ("INSERT INTO main(member_id, money, user, dildo, vibrator, butt_plug, rope, ball_gags, earth,star_blaster, purple_guy, bomb, gun, sword, halberd) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
      val = (ctx.message.author.id, 250, ctx.message.author.name, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
      cursor.execute(sql, val)
      await ctx.send("Because you didn't have an account, I just made one for you! Use the command again to see your money.")
      db.commit()
    elif amount > int(result[0]):
      await ctx.send("You don't have the money for this!")
    elif amount > 1:
      randomchoice = randint(1, 2)
      if randomchoice == 2:
        amountbad = int(result[0]) - amount
        sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
        val = (amountbad, ctx.message.author.id)
        cursor.execute(sql, val)
        db.commit
        await ctx.send(f"Sorry, you lost {amount}")
      elif randomchoice == 1:
        amountgood = int(result[0]) + (amount * 2)
        resultgood = amount * 2
        sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
        val = (amountgood, ctx.message.author.id)
        cursor.execute(sql, val)
        db.commit
        await ctx.send(f"Woohoo! You just won ${resultgood}!")
      elif amount > 1000:
        randomchoice2 = randint(1, 3)
        if randomchoice2 == 1:
          amountgood1 = int(result[0]) + (amount * 2)
          resultgood1 = amount * 2
          sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
          val = (amountgood1, ctx.message.author.id)
          cursor.execute(sql, val)
          db.commit
          await ctx.send(f"Woohoo! You just won ${resultgood1}!")
        else:
          amountbad1 = int(result[0]) - amount
          sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
          val = (amountbad1, ctx.message.author.id)
          cursor.execute(sql, val)
          db.commit
          await ctx.send(f"Sorry, you lost {amount}")
      elif amount > 10000:
        randomchoice3 = randint(1, 5)
        if randomchoice3 == 1:
          amountgood2 = int(result[0]) + (amount * 2)
          resultgood2 = amount * 2
          sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
          val = (amountgood2, ctx.message.author.id)
          cursor.execute(sql, val)
          db.commit
          await ctx.send(f"Woohoo! You just won ${resultgood2}!")
        else:
          amountbad2 = int(result[0]) - amount
          sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
          val = (amountbad2, ctx.message.author.id)
          cursor.execute(sql, val)
          db.commit
          await ctx.send(f"Sorry, you lost {amount}")
      elif amount > 100000:
        randomchoice4 = randint(1, 7)
        if randomchoice4 == 1:
          amountgood3 = int(result[0]) + (amount * 2)
          resultgood3 = amount * 2
          sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
          val = (amountgood3, ctx.message.author.id)
          cursor.execute(sql, val)
          db.commit
          await ctx.send(f"Woohoo! You just won ${resultgood3}!")
        else:
          amountbad3 = int(result[0]) - amount
          sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
          val = (amountbad3, ctx.message.author.id)
          cursor.execute(sql, val)
          db.commit
          await ctx.send(f"Sorry, you lost {amount}")
      else:
        if amount > 100001:
          randomchoice4 = randint(1, 30)
        if randomchoice4 == 1:
          amountgood3 = int(result[0]) + (amount * 2)
          resultgood3 = amount * 2
          sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
          val = (amountgood3, ctx.message.author.id)
          cursor.execute(sql, val)
          db.commit
          await ctx.send(f"Woohoo! You just won ${resultgood3}!")
        else:
          amountbad3 = int(result[0]) - amount
          sql = (cursor.execute("UPDATE main SET money = ? WHERE member_id = ?"))
          val = (amountbad3, ctx.message.author.id)
          cursor.execute(sql, val)
          db.commit
          await ctx.send(f"Sorry, you lost {amount}")
          cursor.close
          db.close

The command stops working am assuming at "elif amount > 1" because nothing else happens after that point. if there's any other way I could write this gamble command then please send it to me, or maybe this has an easy fix once again, please help me! I'm tried on this for a while and I can't find a way for this to work...


text:
Q: Upload limit and Exception when uploading files via Client Object Model We have an windows application that uploads files to SharePoint 2010 via client object model. We have raised the upload limit as in the following article: http://msdn.microsoft.com/en-us/library/ff599489.aspx.
We have done this via powershell:
$ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService

$ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 78643200  #75MB

$ws.Update()

This works fine for files up to approximately 40 MB. After that we receive the following exception:

The remote server returned an error: (401) Unauthorized.
System.Net.WebExceptionStatus.ProtocolError
at System.Net.HttpWebRequest.GetResponse()    at
  Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute()    at
  Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder
  sb)    at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()
  at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()
  at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()    at
  UploadClient.FileUpload.Service.SharePointService.CreateFile

We have also tried increasing the upload size via:
    public static void IncreaseUploadSize()
    {
        SPWebService contentService = SPWebService.ContentService;

        /* Must set this to -1, else, the MaxReceivedMessageSize value for
        SPWebService.ContentService.WcfServiceSettings["client.svc"] will not be used.*/
        contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = -1;

        // SPWcfServiceSettings has other Properties that you can set.
        SPWcfServiceSettings csomWcfSettings = new SPWcfServiceSettings();
        csomWcfSettings.MaxReceivedMessageSize = 146800640; // 140MB
        csomWcfSettings.MaxBufferSize = 146800640; // 140MB
        csomWcfSettings.TransferMode = System.ServiceModel.TransferMode.Streamed;
        contentService.WcfServiceSettings["client.svc"] = csomWcfSettings;

        contentService.Update();
    }

We have set transfermode to both Streamed and Buffered but with the same result.
Are there any other changes in form of config files that we have to update for this?
Thankful for any sugggestions / netify

A: Generally when I have to change the upload size, there is 2 things I check:

*

*The global settings of the web application in the central administration, there is a param for the maximum upload size

*The second is in the web.config:

<httpRuntime maxRequestLength="51200" />

Hope this would help.
But according to your error 401... I'm not sure this is due to the file size...

A: You may want to look at the <httpRuntime maxRequestLength="x" /> and <requestLimits maxAllowedContentLength="y"/> entries in web.config

A: I has this problem. I recommended SaveBinaryDirect method for you.
using (MemoryStream memoryStream=new MemoryStream(sourceFile.OpenBinary()))
                {
                    clientContext.ExecuteQuery();
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext,
                        targetUrl,memoryStream, true);
                    clientContext.ExecuteQuery();
                }


text:
Q: Python using Kalman Filter to improve simulation but getting worse results I have questions on the behavior I am seeing with applying Kalman Filter (KF) to the following forecast problem.  I have included a simple code sample.
Goal: I would like to know if KF is suitable for improving forecast/simulation result for a day ahead (at t+24 hours), using the measurement result obtained now (at t).  The goal is to get the forecast as close to measurement as possible
Assumption:
We assume the measurement is perfect (ie. if we can get the forecast matches the measurement perfectly, we are happy).
We have a single measurement variable (z, real wind speed), and a single simulated variable (x, predicted wind speed).
The simulated wind speed x is produced from a NWP (numerical weather prediction) software using a variety meteorological data (black box to me).  Simulation file is produced daily, containing data every half an hour.
I attempt to correct the t+24hr forecast, using the measurement I obtained now and the forecast data now (generated t-24 hr ago) using a scalar Kalman filter.  For reference, I used:
http://www.swarthmore.edu/NatSci/echeeve1/Ref/Kalman/ScalarKalman.html
Code:
#! /usr/bin/python

import numpy as np
import pylab

import os

def main():

    # x = 336 data points of simulated wind speed for 7 days * 24 hour * 2 (every half an hour)
    # Imagine at time t, we will get a x_t fvalue or t+48 or a 24 hours later.
    x = load_x()

    # this is a list that will contain 336 data points of our corrected data
    x_sample_predict_list = []

    # z = 336 data points for 7 days * 24 hour * 2 of actual measured wind speed (every half an hour)
    z = load_z()

    # Here is the setup of the scalar kalman filter
    # reference: http://www.swarthmore.edu/NatSci/echeeve1/Ref/Kalman/ScalarKalman.html
    # state transition matrix (we simply have a scalar)
    # what you need to multiply the last time's state to get the newest state
    # we get the x_t+1 = A * x_t, since we get the x_t+1 directly for simulation
    # we will have a = 1
    a = 1.0

    # observation matrix
    # what you need to multiply to the state, convert it to the same form as incoming measurement
    # both state and measurements are wind speed, so set h = 1
    h = 1.0

    Q = 16.0    # expected process variance of predicted Wind Speed
    R = 9.0 # expected measurement variance of Wind Speed

    p_j = Q # process covariance is equal to the initial process covariance estimate

    # Kalman gain is equal to k = hp-_j / (hp-_j + R).  With perfect measurement
    # R = 0, k reduces to k=1/h which is 1
    k = 1.0

    # one week data
    # original R2 = 0.183
    # with delay = 6, R2 = 0.295
    # with delay = 12, R2 = 0.147
    # with delay = 48, R2 = 0.075
    delay = 6

    # Kalman loop
    for t, x_sample in enumerate(x):

        if t <= delay:
            # for the first day of the forecast,
            # we don't have forecast data and measurement
            # from a day before to do correction
            x_sample_predict = x_sample
        else: # t > 48
            # for a priori estimate we take x_sample as is
            # x_sample = x^-_j = a x^-_j_1 + b u_j
            # Inside the NWP (numerical weather prediction,
            # the x_sample should be on x_sample_j-1 (assumption)

            x_sample_predict_prior = a * x_sample

            # we use the measurement from t-delay (ie. could be a day ago)
            # and forecast data from t-delay, to produce a leading residual that can be used to
            # correct the forecast.
            residual = z[t-delay] - h * x_sample_predict_list[t-delay]

            p_j_prior = a**2 * p_j + Q

            k = h * p_j_prior / (h**2 * p_j_prior + R)

            # we update our prediction based on the residual
            x_sample_predict = x_sample_predict_prior + k * residual

            p_j = p_j_prior * (1 - h * k)

            #print k
            #print p_j_prior
            #print p_j
            #raw_input()

        x_sample_predict_list.append(x_sample_predict)

    # initial goodness of fit
    R2_val_initial = calculate_regression(x,z)
    R2_string_initial = "R2 initial: {0:10.3f}, ".format(R2_val_initial)
    print R2_string_initial     # R2_val_initial = 0.183

    # final goodness of fit
    R2_val_final = calculate_regression(x_sample_predict_list,z)
    R2_string_final = "R2 final: {0:10.3f}, ".format(R2_val_final)
    print R2_string_final       # R2_val_final = 0.117, which is worse

    timesteps = xrange(len(x))
    pylab.plot(timesteps,x,'r-', timesteps,z,'b:', timesteps,x_sample_predict_list,'g--')
    pylab.xlabel('Time')
    pylab.ylabel('Wind Speed')
    pylab.title('Simulated Wind Speed vs Actual Wind Speed')
    pylab.legend(('predicted','measured','kalman'))
    pylab.show()

def calculate_regression(x, y):
    R2 = 0
    A = np.array( [x, np.ones(len(x))] )
    model, resid = np.linalg.lstsq(A.T, y)[:2]
    R2_val = 1 - resid[0] / (y.size * y.var())
    return R2_val

def load_x():
    return np.array([2, 3, 3, 5, 4, 4, 4, 5, 5, 6, 5, 7, 7, 7, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11,
     11, 10, 8, 8, 8, 8, 6, 3, 4, 5, 5, 5, 6, 5, 5, 5, 6, 5, 5, 6, 6, 7, 6, 8, 9, 10,
     12, 11, 10, 10, 10, 11, 11, 10, 8, 8, 9, 8, 9, 9, 9, 9, 8, 9, 8, 11, 11, 11, 12,
     12, 13, 13, 13, 13, 13, 13, 13, 14, 13, 13, 12, 13, 13, 12, 12, 13, 13, 12, 12,
     11, 12, 12, 19, 18, 17, 15, 13, 14, 14, 14, 13, 12, 12, 12, 12, 11, 10, 10, 10,
     10, 9, 9, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 8, 8, 8, 6, 5, 5,
     5, 5, 5, 5, 6, 4, 4, 4, 6, 7, 8, 7, 7, 9, 10, 10, 9, 9, 8, 7, 5, 5, 5, 5, 5, 5,
     5, 5, 6, 5, 5, 5, 4, 4, 6, 6, 7, 7, 7, 7, 6, 6, 5, 5, 4, 2, 2, 2, 1, 1, 1, 2, 3,
     13, 13, 12, 11, 10, 9, 10, 10, 8, 9, 8, 7, 5, 3, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6,
     7, 7, 7, 6, 6, 6, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 1, 5, 5, 3, 2, 1, 2, 6, 7,
     7, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 9, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7,
     7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 11, 11, 11, 11, 10, 10, 9, 10, 10, 10, 2, 2,
     2, 3, 1, 1, 3, 4, 5, 8, 9, 9, 9, 9, 8, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
     7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 5, 5, 5, 5, 5, 6, 5])

def load_z():
    return np.array([3, 2, 1, 1, 1, 1, 3, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 1, 1, 2, 2, 2,
     2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 4, 4, 5, 5, 5, 6, 6,
     6, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 10, 9, 9, 10, 10, 9,
     9, 10, 9, 9, 10, 9, 8, 9, 9, 7, 7, 6, 7, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 7, 6, 7,
     8, 8, 7, 8, 9, 9, 9, 9, 10, 9, 9, 9, 8, 8, 10, 9, 10, 10, 9, 9, 9, 10, 9, 8, 7,
     7, 7, 7, 8, 7, 6, 5, 4, 3, 5, 3, 5, 4, 4, 4, 2, 4, 3, 2, 1, 1, 2, 1, 2, 1, 4, 4,
     4, 4, 4, 3, 3, 3, 1, 1, 1, 1, 2, 3, 3, 2, 3, 3, 3, 2, 2, 5, 4, 2, 5, 4, 1, 1, 1,
     1, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3, 4, 3, 4, 3, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4,
     4, 4, 5, 5, 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 1, 2, 2, 3, 3, 1, 2, 1, 1, 2, 4, 3, 1,
     1, 2, 0, 0, 0, 2, 1, 0, 0, 2, 3, 2, 4, 4, 3, 3, 4, 5, 5, 5, 4, 5, 4, 4, 4, 5, 5,
     4, 3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 4, 5, 5, 5, 4, 5, 5, 5, 5, 6, 5, 5, 8, 9, 8, 9,
     9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 9, 10, 9, 8, 8, 9, 8, 9, 9, 10, 9, 9, 9,
     7, 7, 9, 8, 7, 6, 6, 5, 5, 5, 5, 3, 3, 3, 4, 6, 5, 5, 6, 5])

if __name__ == '__main__': main()  # this avoids executing main on import your_module

-------------------------
Observations:
1)  If yesterday's forecast is over-predicting (positive bias), then today, I would make corrections by subtracting away the bias.  In practice, if today I happen to be under-predicting, then subtracting the positive bias lead to an even worse prediction.  And I actually observe a wider swing of data with poorer overall fit.  What is wrong with my example?
2)  Most Kalman filter resource indicates that Kalman filter minimizes the a posteriori covariance p_j = E{(x_j – x^_j)}, and has the proof selecting K to minimize the p_j.  But can someone explain how minimizing the a posteriori covariance actually minimizes the effects of the process white noise w?  In a real time case, let's say the actual wind speed and measured wind speed is 5 m/s.  The prediction wind speed is 6 m/s, ie. there was a noise of w = 1 m/s.  The residual is 5 – 6 = -1 m/s.  You correct by taking the 1 m/s from your prediction to get back 5 m/s.  Is that how the effect of the process noise is minimized?
3) Here is a paper that mentioned applying KF to smooth weather forecast. http://hal.archives-ouvertes.fr/docs/00/50/59/93/PDF/Louka_etal_jweia2008.pdf.  The interesting point is on pg 9 eq (7) that "as soon as the new observation value y_t is known, the estimate of x at time t becomes x_t = x_t/t-1 = K(y_t – H_t * x_t/t-1) ".  If I were to paraphrase it in reference to actual time, then "as soon as the new observation value is known now, the estimate now becomes x_t …. "  I get how KF can bring your data close to measurement in real time.  But if you are correcting the forecast data at t=now, with measurement data from t=now, how is that a forecast anymore?
Thanks!
UPDATE1:
4) I have added a delay in the code to investigate how much later can the forecast be than the current bias calculated from the current measurement, if we want the R2 between the Kalman processed data vs measure data time series to improve from the unprocessed data vs. measure data.  In this example, if the measurement is used to improve the forecast 6 time step (3 hours from now) it is still useful (R2 goes from 0.183 to 0.295).  But if the measurement is used to improve the forecast 1 day from now, then it destroys the correlation (R2 goes down to 0.075).

A: I updated my test scalar implementation, without making the assumption of perfect measurement R of 1, which was what reduced the kalman gain to a constant value of 1.  Now I am seeing an improvement on the time series with reduced RMSE error.
#! /usr/bin/python

import numpy as np
import pylab

import os

# RMSE improved
def main():

    # x = 336 data points of simulated wind speed for 7 days * 24 hour * 2 (every half an hour)
    # Imagine at time t, we will get a x_t fvalue or t+48 or a 24 hours later.
    x = load_x()

    # this is a list that will contain 336 data points of our corrected data
    x_sample_predict_list = []

    # z = 336 data points for 7 days * 24 hour * 2 of actual measured wind speed (every half an hour)
    z = load_z()

    # Here is the setup of the scalar kalman filter
    # reference: http://www.swarthmore.edu/NatSci/echeeve1/Ref/Kalman/ScalarKalman.html
    # state transition matrix (we simply have a scalar)
    # what you need to multiply the last time's state to get the newest state
    # we get the x_t+1 = A * x_t, since we get the x_t+1 directly for simulation
    # we will have a = 1
    a = 1.0

    # observation matrix
    # what you need to multiply to the state, convert it to the same form as incoming measurement
    # both state and measurements are wind speed, so set h = 1
    h = 1.0

    Q = 1.0     # expected process noise of predicted Wind Speed
    R = 1.0     # expected measurement noise of Wind Speed

    p_j = Q # process covariance is equal to the initial process covariance estimate

    # Kalman gain is equal to k = hp-_j / (hp-_j + R).  With perfect measurement
    # R = 0, k reduces to k=1/h which is 1
    k = 1.0

    # one week data
    # original R2 = 0.183
    # with delay = 6, R2 = 0.295
    # with delay = 12, R2 = 0.147
    # with delay = 48, R2 = 0.075
    delay = 6

    # Kalman loop
    for t, x_sample in enumerate(x):

        if t <= delay:
            # for the first day of the forecast,
            # we don't have forecast data and measurement
            # from a day before to do correction
            x_sample_predict = x_sample
        else: # t > 48
            # for a priori estimate we take x_sample as is
            # x_sample = x^-_j = a x^-_j_1 + b u_j
            # Inside the NWP (numerical weather prediction,
            # the x_sample should be on x_sample_j-1 (assumption)

            x_sample_predict_prior = a * x_sample

            # we use the measurement from t-delay (ie. could be a day ago)
            # and forecast data from t-delay, to produce a leading residual that can be used to
            # correct the forecast.
            residual = z[t-delay] - h * x_sample_predict_list[t-delay]

            p_j_prior = a**2 * p_j + Q

            k = h * p_j_prior / (h**2 * p_j_prior + R)

            # we update our prediction based on the residual
            x_sample_predict = x_sample_predict_prior + k * residual

            p_j = p_j_prior * (1 - h * k)

            #print k
            #print p_j_prior
            #print p_j
            #raw_input()

        x_sample_predict_list.append(x_sample_predict)

    # initial goodness of fit
    R2_val_initial = calculate_regression(x,z)
    R2_string_initial = "R2 original: {0:10.3f}, ".format(R2_val_initial)
    print R2_string_initial     # R2_val_original = 0.183

    original_RMSE = (((x-z)**2).mean())**0.5
    print "original_RMSE"
    print original_RMSE
    print "\n"

    # final goodness of fit
    R2_val_final = calculate_regression(x_sample_predict_list,z)
    R2_string_final = "R2 final: {0:10.3f}, ".format(R2_val_final)
    print R2_string_final       # R2_val_final = 0.267, which is better

    final_RMSE = (((x_sample_predict-z)**2).mean())**0.5
    print "final_RMSE"
    print final_RMSE
    print "\n"

    timesteps = xrange(len(x))
    pylab.plot(timesteps,x,'r-', timesteps,z,'b:', timesteps,x_sample_predict_list,'g--')
    pylab.xlabel('Time')
    pylab.ylabel('Wind Speed')
    pylab.title('Simulated Wind Speed vs Actual Wind Speed')
    pylab.legend(('predicted','measured','kalman'))
    pylab.show()

def calculate_regression(x, y):
    R2 = 0
    A = np.array( [x, np.ones(len(x))] )
    model, resid = np.linalg.lstsq(A.T, y)[:2]
    R2_val = 1 - resid[0] / (y.size * y.var())
    return R2_val

def load_x():
    return np.array([2, 3, 3, 5, 4, 4, 4, 5, 5, 6, 5, 7, 7, 7, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11,
     11, 10, 8, 8, 8, 8, 6, 3, 4, 5, 5, 5, 6, 5, 5, 5, 6, 5, 5, 6, 6, 7, 6, 8, 9, 10,
     12, 11, 10, 10, 10, 11, 11, 10, 8, 8, 9, 8, 9, 9, 9, 9, 8, 9, 8, 11, 11, 11, 12,
     12, 13, 13, 13, 13, 13, 13, 13, 14, 13, 13, 12, 13, 13, 12, 12, 13, 13, 12, 12,
     11, 12, 12, 19, 18, 17, 15, 13, 14, 14, 14, 13, 12, 12, 12, 12, 11, 10, 10, 10,
     10, 9, 9, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 8, 8, 8, 6, 5, 5,
     5, 5, 5, 5, 6, 4, 4, 4, 6, 7, 8, 7, 7, 9, 10, 10, 9, 9, 8, 7, 5, 5, 5, 5, 5, 5,
     5, 5, 6, 5, 5, 5, 4, 4, 6, 6, 7, 7, 7, 7, 6, 6, 5, 5, 4, 2, 2, 2, 1, 1, 1, 2, 3,
     13, 13, 12, 11, 10, 9, 10, 10, 8, 9, 8, 7, 5, 3, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6,
     7, 7, 7, 6, 6, 6, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 1, 5, 5, 3, 2, 1, 2, 6, 7,
     7, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 9, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7,
     7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 11, 11, 11, 11, 10, 10, 9, 10, 10, 10, 2, 2,
     2, 3, 1, 1, 3, 4, 5, 8, 9, 9, 9, 9, 8, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
     7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 5, 5, 5, 5, 5, 6, 5])

def load_z():
    return np.array([3, 2, 1, 1, 1, 1, 3, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 1, 1, 2, 2, 2,
     2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 4, 4, 5, 5, 5, 6, 6,
     6, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 10, 9, 9, 10, 10, 9,
     9, 10, 9, 9, 10, 9, 8, 9, 9, 7, 7, 6, 7, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 7, 6, 7,
     8, 8, 7, 8, 9, 9, 9, 9, 10, 9, 9, 9, 8, 8, 10, 9, 10, 10, 9, 9, 9, 10, 9, 8, 7,
     7, 7, 7, 8, 7, 6, 5, 4, 3, 5, 3, 5, 4, 4, 4, 2, 4, 3, 2, 1, 1, 2, 1, 2, 1, 4, 4,
     4, 4, 4, 3, 3, 3, 1, 1, 1, 1, 2, 3, 3, 2, 3, 3, 3, 2, 2, 5, 4, 2, 5, 4, 1, 1, 1,
     1, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3, 4, 3, 4, 3, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4,
     4, 4, 5, 5, 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 1, 2, 2, 3, 3, 1, 2, 1, 1, 2, 4, 3, 1,
     1, 2, 0, 0, 0, 2, 1, 0, 0, 2, 3, 2, 4, 4, 3, 3, 4, 5, 5, 5, 4, 5, 4, 4, 4, 5, 5,
     4, 3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 4, 5, 5, 5, 4, 5, 5, 5, 5, 6, 5, 5, 8, 9, 8, 9,
     9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 9, 10, 9, 8, 8, 9, 8, 9, 9, 10, 9, 9, 9,
     7, 7, 9, 8, 7, 6, 6, 5, 5, 5, 5, 3, 3, 3, 4, 6, 5, 5, 6, 5])

if __name__ == '__main__': main()  # this avoids executing main on import your_module

A: This line is not respecting the Scalar Kalman Filter:
residual = z[t-delay] - h * x_sample_predict_list[t-delay]

In my opinion you should have done:
 residual = z[t -delay] - h * x_sample_predict_prior


text:
Q: Mercurial not working after TortoiseHg update I recently updated TortoiseHg to 2.0.3 (with Mercurial 1.8.2). After updating, Mercurial no longer works via the command line (Windows 7 x64), but does work via the TortoiseHg GUI. Trying to use any Hg commands via the command line results in the error message 'hg' is not recognized as an internal or external command, operable program or batch file.'
I'm guessing I need to make some change to a setting in TortoiseHg or Windows 7 so that Windows will recognize hg commands, but I'm not sure what that change is. I am very new to using Hg - I installed it a few months ago (thus the need for an update), but only recently started using it.

A: TortoiseHg v2.X.X no longer uses the hg command, instead try thg.
Your install path might be different, but typically thg.CMD exists at:
C:/Program Files/TortoiseHg/bin/
If you've installed Mercurial independent of TortoiseHg you may still have access to the hg executable, but most people just install TortoiseHg and take the associated copy of Mercurial, in which case you would need to use the thg commands.

A: I fixed this by removing the "/" at the end of the Path:
From
"C:\Program Files\TortoiseHg\"

to
"C:\Program Files\TortoiseHg"

A: I had to remove the leading quotation mark - the PATH variable contained:
...;"C:\Program Files\TortoiseHg

and I changed it to
...;C:\Program Files\TortoiseHg

to make it work with Red-Gate SQL Source control.


text:
Q: How to display YouTubePlayerView in a ListView in Android? The following shows error:

NullPointerException: Cannot start activity component(a.b.YoutubeActivity)

Please check it out. Passing single videoID as of now stuck with NullPointerException. Following is my VideoAdapter:
public class VideoAdapter extends BaseAdapter implements YouTubePlayer.OnInitializedListener {

    public static final String API_KEY = "Xxxx-pcD82qk8";
    public static final String VIDEO_ID = "7UpbJKeiv_Y";
    Context context;
    LayoutInflater inflater;
    JSONArray jArray = null;
    ArrayList<YouTubeItem> list;
    private YouTubePlayer youTubePlayer;
    private YouTubePlayerView youTubePlayerView;

    public VideoAdapter(Activity context,
                        JSONArray jArray) {
        // TODO Auto-generated constructor stub

        parseResponse(jArray);
    }

    private void parseResponse(JSONArray jArray) {
        if (jArray != null && jArray.length() > 0) {
            String date;
            String title;
            String link;
            JSONObject jsonObject;
            list = new ArrayList<YouTubeItem>();

            for (int i = 0; i < jArray.length(); i++) {
                try {
                    jsonObject = jArray.getJSONObject(i);
                    date = jsonObject.getString("date");
                    title = jsonObject.getString("title");
                    link = jsonObject.getString("link");

                    if (date != null && title != null && link != null) {
                        list.add(new YouTubeItem(date, title, link));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }
        String[] date = new String[jArray.length()];
        String[] title = new String[jArray.length()];
        String[] link = new String[jArray.length()];

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Log.i("adapter 1", "");

        View rowView = convertView;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rowView = inflater.inflate(R.layout.youtube_view, parent, false);

        }
        Log.i("adapter 3", "");
        youTubePlayerView = (YouTubePlayerView) rowView
                .findViewById(R.id.youtubeplayerview);
        Log.i("adapter 4", "");
        youTubePlayerView.initialize(API_KEY, this);
        Log.i("adapter 5", "");
        TextView d = (TextView) rowView.findViewById(R.id.textView1);
        Log.i("adapter 6", "");
        TextView t = (TextView) rowView.findViewById(R.id.textView2);
        Log.i("adapter 7", "");
        TextView l = (TextView) rowView.findViewById(R.id.textView3);
        Log.i("adapter 8", "");
        d.setText(list.get(position).getDate());
        Log.i("adapter 9", "");
        t.setText(list.get(position).getTitle());
        Log.i("adapter 10", "");
        l.setText(list.get(position).getLink());
        Log.i("adapter 11", "");

        return rowView;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int i) {
        // TODO Auto-generated method stub
        return i;
    }

    private class YouTubeItem {
        private String date;
        private String title;
        private String link;

        private YouTubeItem(String date, String title, String link) {
            this.date = date;
            this.title = title;
            this.link = link;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getLink() {
            return link;
        }

        public void setLink(String link) {
            this.link = link;
        }
    }

    @Override
    public void onInitializationFailure(Provider arg0,
                                        YouTubeInitializationResult arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onInitializationSuccess(Provider provider,
                                        YouTubePlayer player, boolean wasRestored) {
        // TODO Auto-generated method stub
        youTubePlayer = player;

        if (!wasRestored) {
            player.cueVideo(VIDEO_ID);
        }
    }
}

A: Replace you Adapter with this one
public class VideoAdapter extends BaseAdapter {

Context context;
LayoutInflater inflater;
JSONArray jArray = null;
ArrayList<YouTubeItem> list;

public VideoAdapter(YoutubeActivity youtubeActivity,
                    int activityYouTubeApi, JSONArray jArray) {
    // TODO Auto-generated constructor stub

    parseResponse(jArray);
}

private void parseResponse(JSONArray jArray) {
    if (jArray != null && jArray.length() > 0) {
        String date;
        String title;
        String link;
        JSONObject jsonObject;
        list = new ArrayList<>();

        for (int i = 0; i < jArray.length(); i++) {
            try {
                jsonObject = jArray.getJSONObject(i);
                date = jsonObject.getString("date");
                title = jsonObject.getString("title");
                link = jsonObject.getString("link");

                if (date != null && title != null && link != null) {
                    list.add(new YouTubeItem(date, title, link));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }
    String[] date = new String[jArray.length()];
    String[] title = new String[jArray.length()];
    String[] link = new String[jArray.length()];

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.youtube_view, parent, false);
    YouTubePlayerView you = (YouTubePlayerView) rowView.findViewById(R.id.youtubeplayerview);
    TextView d = (TextView) rowView.findViewById(R.id.textView1);
    TextView t = (TextView) rowView.findViewById(R.id.textView2);
    TextView l = (TextView) rowView.findViewById(R.id.textView3);

    d.setText(list.get(position).getDate());
    t.setText(list.get(position).getTitle());
    l.setText(list.get(position).getLink());

    return rowView;
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int i) {
    // TODO Auto-generated method stub
    return i;
}

private class YouTubeItem {
    private String date;
    private String title;
    private String link;

    private YouTubeItem(String date, String title, String link) {
        this.date = date;
        this.title = title;
        this.link = link;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }
}
}

Instead of creating three different Arrays, I created an Object called YouTubeItem. This will be more readable and easier to manipulate, avoid any problems if you have lost one attribute of any of the three arrays and make the parsing individual process (Invalid object will not affect the whole process)
Let me know if you have any more questions


text:
Q: zoom mapView to a certain bounding box on osmdroid I want to use the zoomToBoundingBox method to zoom a map to a specific bounding box.
The method does nothing but display the map on zoom level 0.
In the mapView.java source code I found this:

/**
           * Zoom the map to enclose the specified bounding box, as closely as possible.
           * Must be called after display layout is complete, or screen dimensions are not known, and
           * will always zoom to center of zoom  level 0.
           * Suggestion: Check getScreenRect(null).getHeight() > 0
           */

I checked getScreenRect(null).getHeight() > 0 and it gives me false.
How do you complete display layout programmatically?
What can I do so that the above predicate gives me true?

A: I had the same problem. I addressed it by calling the zoomToBoundingBox() call at the end of the onLayout() method.
I have my own subclass of MapView that I use to insulate me from the map library choice. This class has a clearPoints / addPoint / layoutPoints style of interface. Within the layoutPoints() method I create the itemized overlay lay from the collection of points and create the bounding box that is stored in an instance method of the class.
public class MyMapView extends MapView {

// The bounding box around all map points
// Used to determine the correct zoom level to show everything
private int minLat = Integer.MAX_VALUE;
private int minLon = Integer.MAX_VALUE;
private int maxLat = Integer.MIN_VALUE;
private int maxLon = Integer.MIN_VALUE;

private BoundingBoxE6 boundingBox;

My onLayout() override has:
/* (non-Javadoc)
 * @see org.osmdroid.views.MapView#onLayout(boolean, int, int, int, int)
 */
@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    super.onLayout(arg0, arg1, arg2, arg3, arg4);

    // Now that we have laid out the map view,
    // zoom to any bounding box
    if (this.boundingBox != null) {
        this.zoomToBoundingBox(this.boundingBox);
    }
}

I'm not sure if this is the best way of doing it, but it seems to work for me (except that the zoom appears to be a little too far out, but that's another problem for another time).


text:
Q: How to use generic with interface in dart, flutter I am trying to use generic with interface in dart lang in flutter framework.
Basically, I would like to set the type of the generic to an implementation of ITestClass.
in the typedef definition, I am setting the "T" type to extend ITestClass (because you cannot implement with generic in dart). But when I actually use this typedef in the build method, it throws following error
The argument type 'TestClass' can't be assigned to the parameter type 'T'.
From my knowledge, TestClass is an implementation of ITestClass so type error should not be thrown. How can I overcome this problem?
import 'package:flutter/material.dart';

class ITestClass {}

class TestClass implements ITestClass {}

typedef TestTypedef<T extends ITestClass> = Widget Function(T model);

void main() {
  runApp(
    MaterialApp(
      home: TestWidget(
        testTypedef: (model) => Container(),
      ),
    ),
  );
}

class TestWidget<T extends ITestClass> extends StatelessWidget {
  final TestTypedef<T> testTypedef;

  TestWidget({
    required this.testTypedef,
  });

  Widget build(BuildContext context) {
    return Scaffold(
      body: testTypedef(
        TestClass(),  // error here
      ),
    );
  }
}


text:
Q: Eslint (Airbnb) indentation issues with React code(JSX) I'm fighting with a minor issue with my eslint, it seems to work fine most of the time, but there are some cases that it doesn't work weel with React code.
Let take as example this code:
const cellPLay = (name, src) => (
  <Table.Cell>
    <Modal trigger={<Button icon><Icon name="video play" size="large" /></Button>}>
      <Modal.Header>
        {name}
      </Modal.Header>
      <Modal.Content image>
        <Modal.Description>
          <video src={src} controls style={{ width: 910 }} />
        </Modal.Description>
      </Modal.Content>
    </Modal>
  </Table.Cell>
);

Gives errors like that:

/my-path/MyFile.js:18:7:
  Expected indentation of 8 space characters but found 6.
  [Error/react/jsx-indent]

For some reason, eslint thinks Modal.Content should be indented in after Modal.Header, but even if I fix all indentation it asks it says the indentation of some closing tag is wrong:

Expected closing tag to match indentation of opening

My eslint config file:
{
  "extends": "./my-eslint/index.js"
}

The actual eslint code:
module.exports = {
  extends: require.resolve('eslint-config-airbnb'),
  env: {
    browser: true,
    jest: true,
    es6: true,
  },
  parserOptions: {
    ecmaVersion: 8,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  rules: {
    strict: 'error',
    'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx'] }],
    'no-plusplus': 'off',
    'jsx-a11y/media-has-caption': 'off',
    'jsx-a11y/anchor-is-valid': [
      'error',
      {
        components: ['Link'],
        specialLink: ['to'],
      },
    ],
  },
};

I have tried adding manually the rule for jsx indent
'react/jsx-indent': [2, 2],

Didn't solve it.
Any other idea?
On a side note, VSCode was doing it correctly regarding the indentation, but when I run eslint manually it fails, and I need to fix it because there is code style automation running. I followed some answers and installed prettier on VSCode, it seems that now they got to the same page, but I need to fix the indentation issue.
UPDATE 1
As suggested by @a-jar-of-clay I tried to upgrade my packages, eslint to 5.4.0, airbnb to 17.1.0 and airbnb-base to 13.1.0
Now I got new error messages, probably due to some incompatibility:

Error: config-airbnb/rules/react.js:  Configuration for rule
  "react/jsx-no-bind" is invalid:   Value
  {"ignoreRefs":true,"allowArrowFunctions":true,"allowFunctions":false,"allowBind":false,"ignoreDOMComponents":true}
  should NOT have additional properties.

UPDATE 2
As asked by @matt-dell, the command that I'm using to run manually is:
./node_modules/.bin/eslint --fix --format unix  --config my-eslint/index.js

It's definitely picking up my config, as it reacts when I change some rule.

A: I had the same problem and I fixed it with some packages:
By using the eslint plugins and extending the react-app eslint it was fixed.
package.json
    "babel-eslint": "^7.2.3",

    "eslint": "^4.19.1",
    "eslint-config-react-app": "^2.1.0",
    "eslint-plugin-flowtype": "^2.50.1",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^5.1.1",
    "eslint-plugin-react": "^7.11.1",

.eslintrc.js
 "env": {
    "browser": true,
    "es6": true
},
"extends": ["react-app", "eslint:recommended"],
"parserOptions": {
    "ecmaFeatures": {
        "experimentalObjectRestSpread": true,
        "jsx": true
    },
    "sourceType": "module"
},
"globals": {
    "React": true
},
"plugins": [
    "react"
],
"rules": {/* define your rules here...*/}

Good luck!


text:
Q: Mostrar en el Admin Django Fields de distintos modelos Les comento tengo 2 modelos
1 - es el User(AbstractUser)
2 - Profile
class Profile(models.Model):
   user = models.OneToOneField(User,  on_delete=models.CASCADE)
   user_in_charge = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='users', verbose_name='Ejecutivo a Cargo', on_delete=models.CASCADE, null=True)
   phone_number = models.CharField('Telefono de Contacto', max_length=12, blank=True)
   profile_image = models.ImageField(default='default-avatar.png', upload_to='users/', null=True, blank=True)
   role = models.ForeignKey(Role, verbose_name='Rol', on_delete=models.CASCADE, null=True)

   def __str__(self):
       return '%s %s' % (self.user.first_name, self.user.last_name)

   class Meta:
       ordering = ['id']

y en el Admin.py tengo
class UserProfileInline(admin.StackedInline):
   model = Profile
   fk_name = 'user'
   fields = ('role', 'user_in_charge', 'phone_number', )

class UserAdmin(admin.ModelAdmin):
   list_display = ('id', 'first_name', 'last_name', 'email', 'is_staff',)
   list_select_related = True
   inlines = [ UserProfileInline, ]
   readonly_fields = [
       'last_login',
       'date_joined',
   ]

   fields = ('first_name', 'last_name', 'email', 'password', )

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

Necesito Mostrar en el list_display por ejemplo role que es de Profile en ves de ser de User para que en la tabla del admin se pueda ver con todos los datos posibles
quizás estoy hablando cualquier cosa y no es posible pero necesito sacarme la duda
EDIT:
en el admin.py cuando pongo:
list_display = ('id', 'first_name', 'last_name', 'email', 'is_staff',)
el tema es que necesito que se vea asi:
list_display = ('id', 'first_name', 'last_name', 'email', 'is_staff', 'role', 'user_in_charge')
pero estos últimos 2 son de otro modelo y no se como poder meterlos dentro de esta vista

A: Desde Django3.2+ puede usar el decorador display() para mostrar contenido personalizado:
class UserAdmin(admin.ModelAdmin):
    list_display = (
        'id', 'first_name', 'last_name', 'email',
        'is_staff', 'role', 'user_in_charge'
    )

    @admin.display(ordering='last_name', description='Role')
    def role(self, obj):
        return obj.profile.role

    @admin.display(ordering='last_name', description='Ejecutivo a Cargo')
    def user_in_charge(self, obj):
        return obj.profile.user_in_charge

para versiones anteriores:
class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'role', 'user_in_charge')

    def role(self, obj):
        return obj.profile.role
    role.short_description = 'Role'
    role.admin_order_field = 'last_name'

    def user_in_charge(self, obj):
        return obj.profile.user_in_charge
    user_in_charge.short_description = 'Ejecutivo a Cargo'
    user_in_charge.admin_order_field = 'last_name'


text:
Q: Nsis ExecWait command under the hood There's a nsis exe that I know it using Nsis ExecWait to run a process.I need to hook it so I could replace the exe it Exec.
The problem is I'm not sure about what api to hook.And I've try dive into Nsis source codes till now find nothing:(. So Is there anyone familiar with nsis source codes give me some clue so I could find what ExecWait command under the hood API?

A: ExecWait is currently just CreateProcess+WaitForSingleObject.
In the NSIS source this instruction is called TOK_EXECWAIT in the compiler (script.cpp) and it maps to the EW_EXECUTE opcode in the installer stub (exehead/exec.c)...


text:
Q: How can I use my own data for calculations in Pine Script - Tradingview? there I am new to Pine Script and the Rest API.  The Rest API is for brokers. Have you implemented the Rest API.  I need to do this:

*

*I am getting OHLC data from a different source.  I want to send this custom data to PINE script in Trading View and let it use my OHLC data to calculate all indicators.

*Send this indicators values back to brokerage Rest API and I do trading or give custom signals from there
Who can help me with this?


text:
Q: java.lang.AbstractMethodError on Loading XML Configuration (Log4j 2) I am trying to load XML Configuration from servletContext path, but it somehow just wouldn't load the config. The code is:
LoggerContext loggerContext  = (LoggerContext) LogManager.getContext(false);

File configFile = new File(logConfigurationFilePath);
loggerContext.setConfigLocation(configFile.toURI());

Its the setConfiguration() method that throws the exception. I found a somewhat similar thread to this. It suggested to add xercesImpl as a dependency, so I did, but that didn't fix it. The error stack trace is:
2019-11-06 14:52:50,199 Thread-13 ERROR Caught java.lang.AbstractMethodError setting feature http://xml.org/sax/features/external-general-entities to false on DocumentBuilderFactory oracle.xml.jaxp.JXDocumentBuilderFactory@67e46b6d: java.lang.AbstractMethodError java.lang.AbstractMethodError
    at org.apache.logging.log4j.core.config.xml.XmlConfiguration.setFeature(XmlConfiguration.java:204)
    at org.apache.logging.log4j.core.config.xml.XmlConfiguration.disableDtdProcessing(XmlConfiguration.java:197)
    at org.apache.logging.log4j.core.config.xml.XmlConfiguration.newDocumentBuilder(XmlConfiguration.java:186)
    at org.apache.logging.log4j.core.config.xml.XmlConfiguration.<init>(XmlConfiguration.java:89)
    at org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory.getConfiguration(XmlConfigurationFactory.java:46)
    at org.apache.logging.log4j.core.config.ConfigurationFactory.getConfiguration(ConfigurationFactory.java:272)
    at org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:408)
    at org.apache.logging.log4j.core.config.ConfigurationFactory.getConfiguration(ConfigurationFactory.java:293)
    at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:647)
    at org.apache.logging.log4j.core.LoggerContext.setConfigLocation(LoggerContext.java:637)
    at com.att.logicalprovisioning.atc.AnchoredCommonArea.initialize(AnchoredCommonArea.java:130)

and
2019-11-06 14:52:50,294 Thread-13 ERROR Caught java.lang.AbstractMethodError setting feature http://xml.org/sax/features/external-parameter-entities to false on DocumentBuilderFactory oracle.xml.jaxp.JXDocumentBuilderFactory@67e46b6d: java.lang.AbstractMethodError java.lang.AbstractMethodError
    at org.apache.logging.log4j.core.config.xml.XmlConfiguration.setFeature(XmlConfiguration.java:204)

and
2019-11-06 14:52:50,389 Thread-13 ERROR Caught java.lang.AbstractMethodError setting feature http://apache.org/xml/features/nonvalidating/load-external-dtd to false on DocumentBuilderFactory oracle.xml.jaxp.JXDocumentBuilderFactory@67e46b6d: java.lang.AbstractMethodError java.lang.AbstractMethodError
    at org.apache.logging.log4j.core.config.xml.XmlConfiguration.setFeature(XmlConfiguration.java:204)

Can you please let me know what can be going wrong here, that it doesn't work, whereas in the other app it does! Thanks!!


text:
Q: Can anyone help in finding the errror in the following code of quicksort,its's showing Segmentation Fault (SIGSEGV) CODE FOR QUICKSORT
I have used a partition function to get the pivot and after that which recursion solving the problem, but while compiling it is showing segmentation fault.
void swap(int* a,int* b)
{
    int temp=*a;
    *a=*b;
    *b=temp;
}

int partition (int arr[],int start,int end)
{
    int piviot=arr[end-1];
    int pindex=start;
    for(int i=start;i<end-1;i++)
        if(arr[i]<=piviot)
        swap(&arr[i],&arr[pindex++]);
    swap(&arr[end-1],&arr[pindex]);
    return pindex;
}

void quick_sort(int arr[],int start,int end)
{
    if(start<end)
    {
        int pindex=partition(arr,start,end);
        quick_sort(arr,start,pindex);
        quick_sort(arr,pindex,end);
    }

}

A: void quickSort(int arr[], int low, int high)

{
    if (low < high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        int pi = partition(arr, low, high);
    // Separately sort elements before
    // partition and after partition
    quickSort(arr, low, pi - 1);
    quickSort(arr, pi + 1, high);
}

}

A: Look at this code
void quick_sort(int arr[],int start,int end)
{
    if(start<end)
    {
        int pindex=partition(arr,start,end);
        quick_sort(arr,start,pindex);
        quick_sort(arr,pindex,end);
    }
}

If pindex equals start then quick_sort(arr,pindex,end); will call the quick sort function with the same parameters resuling in a stack overflow (ta da!!).
The point of quick sort is that the pivot element is in the correct position, so you recursively sort everything but the pivot element.
Something like
        int pindex = partition(arr, start, end);
        quick_sort(arr, start, pindex);
        quick_sort(arr, pindex + 1, end);

Untested.


text:
Q: Parse decimal number without loosing significant digits I need to parse user input as a number and store it in a decimal variable.
It is important for me to not accept any user input that cannot be properly represented by a decimal value.
This works fine for very large (or very small) numbers, since the Parse method throws an OverflowException in those cases.
However, when a number has too many significant digits the Parse method will silently return a truncated (or rounded?) value.
For example, parsing 1.23456789123456789123456789123 (30 significant digits) results in a value equal to 1.2345678912345678912345678912 (29 significant digits).
This is according to the specification that says that a decimal value has a precision of 28-29 significant digits.
However, I need to be able to detect (and reject) numbers that will be truncated when parsed, since loosing significant digits is unacceptable in my case.
What is the best way to go about this?

Please notice, that pre-parsing or post-validation by string comparison is not a simple way to go since I need to support all kinds of culture-specific input and all kinds of number styles (whitespace, thousand separators, parenthesis, exponent syntax, etc).
Therefore, I'm looking for a solution to this without duplicating the parsing code as provided by .NET.

I'm currently using this workaround to detect input with 28 or more significant digits. While this works, it effectively limit all input to at most 27 significant digits (instead of 28-29):
/// <summary>
///     Determines whether the specified value has 28 or more significant digits,
///     in which case it must be rejected since it may have been truncated when
///     we parsed it.
/// </summary>
static bool MayHaveBeenTruncated(decimal value)
{
    const string format = "#.###########################e0";
    string str = value.ToString(format, CultureInfo.InvariantCulture);
    return (str.LastIndexOf('e') - str.IndexOf('.')) > 27;
}

A: Let me first state that there is no "official" solution. Normally I would not rely on internal implementation, so I'm providing you the following just because you said it's very important to you to get that resolved.
If you take a look at the reference source, you'll see that all parse methods are implemented in a (unfortunately internal) System.Number class. Further investigating, the decimal related methods are TryParseDecimal and ParseDecimal, and they both use something like this
byte* buffer = stackalloc byte[NumberBuffer.NumberBufferBytes];
var number = new NumberBuffer(buffer);
if (TryStringToNumber(s, styles, ref number, numfmt, true))
{
   // other stuff
}

where NumberBuffer is another internal struct. The key point is that the whole parsing happens inside the TryStringToNumber method and the result is used to produce the result. What we are interested is a NumberBuffer field called precision which is populated by the above method.
With all that in mind, we can generate a similar method just to extract the precision after calling the base decimal method to ensure a normal validation/exceptions before we do our post processing.  So the method would be like this
static unsafe bool GetPrecision(string s, NumberStyles style, NumberFormatInfo numfmt)
{
    byte* buffer = stackalloc byte[Number.NumberBuffer.NumberBufferBytes];
    var number = new NumberBuffer(buffer);
    TryStringToNumber(s, styles, ref number, numfmt, true);
    return number.precision;
}

But remember, those types are internal, as well as their methods, so it's difficult to apply the normal reflection, delegate or Expression based techniques. Fortunately, it's not so hard to write such a method using System.Reflection.Emit. The full implementation is as follows
public static class DecimalUtils
{
    public static decimal ParseExact(string s, NumberStyles style = NumberStyles.Number, IFormatProvider provider = null)
    {
        // NOTE: Always call base method first
        var value = decimal.Parse(s, style, provider);
        if (!IsValidPrecision(s, style, provider))
            throw new InvalidCastException(); // TODO: throw appropriate exception
        return value;
    }

    public static bool TryParseExact(string s, out decimal result, NumberStyles style = NumberStyles.Number, IFormatProvider provider = null)
    {
        // NOTE: Always call base method first
        return decimal.TryParse(s, style, provider, out result) && !IsValidPrecision(s, style, provider);
    }

    static bool IsValidPrecision(string s, NumberStyles style, IFormatProvider provider)
    {
        var precision = GetPrecision(s, style, NumberFormatInfo.GetInstance(provider));
        return precision <= 29;
    }

    static readonly Func<string, NumberStyles, NumberFormatInfo, int> GetPrecision = BuildGetPrecisionFunc();
    static Func<string, NumberStyles, NumberFormatInfo, int> BuildGetPrecisionFunc()
    {
        const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic;
        const BindingFlags InstanceFlags = Flags | BindingFlags.Instance;
        const BindingFlags StaticFlags = Flags | BindingFlags.Static;

        var numberType = typeof(decimal).Assembly.GetType("System.Number");
        var numberBufferType = numberType.GetNestedType("NumberBuffer", Flags);

        var method = new DynamicMethod("GetPrecision", typeof(int),
            new[] { typeof(string), typeof(NumberStyles), typeof(NumberFormatInfo) },
            typeof(DecimalUtils), true);

        var body = method.GetILGenerator();
        // byte* buffer = stackalloc byte[Number.NumberBuffer.NumberBufferBytes];
        var buffer = body.DeclareLocal(typeof(byte*));
        body.Emit(OpCodes.Ldsfld, numberBufferType.GetField("NumberBufferBytes", StaticFlags));
        body.Emit(OpCodes.Localloc);
        body.Emit(OpCodes.Stloc, buffer.LocalIndex);
        // var number = new Number.NumberBuffer(buffer);
        var number = body.DeclareLocal(numberBufferType);
        body.Emit(OpCodes.Ldloca_S, number.LocalIndex);
        body.Emit(OpCodes.Ldloc, buffer.LocalIndex);
        body.Emit(OpCodes.Call, numberBufferType.GetConstructor(InstanceFlags, null,
            new[] { typeof(byte*) }, null));
        // Number.TryStringToNumber(value, options, ref number, numfmt, true);
        body.Emit(OpCodes.Ldarg_0);
        body.Emit(OpCodes.Ldarg_1);
        body.Emit(OpCodes.Ldloca_S, number.LocalIndex);
        body.Emit(OpCodes.Ldarg_2);
        body.Emit(OpCodes.Ldc_I4_1);
        body.Emit(OpCodes.Call, numberType.GetMethod("TryStringToNumber", StaticFlags, null,
            new[] { typeof(string), typeof(NumberStyles), numberBufferType.MakeByRefType(), typeof(NumberFormatInfo), typeof(bool) }, null));
        body.Emit(OpCodes.Pop);
        // return number.precision;
        body.Emit(OpCodes.Ldloca_S, number.LocalIndex);
        body.Emit(OpCodes.Ldfld, numberBufferType.GetField("precision", InstanceFlags));
        body.Emit(OpCodes.Ret);

        return (Func<string, NumberStyles, NumberFormatInfo, int>)method.CreateDelegate(typeof(Func<string, NumberStyles, NumberFormatInfo, int>));
    }
}

Use it on your own risk :)

A: Assuming the input is a string and it has been validated as numeric, you can use String.Split:
text = text.Trim().Replace(",", "");
bool neg = text.Contains("-");
if (neg) text = text.Replace("-", "");
while (text.Substring(0, 1) == 0 && text.Substring(0, 2) != "0." && text != "0")
    text = text.Substring(1);
if (text.Contains("."))
{
    while (text.Substring(text.Length - 1) == "0")
        text = text.Substring(0, text.Length - 1);
}
if (text.Split(".")[0].Length + text.Split(".")[1].Length + (neg ? 1 : 0) <= 29)
    valid = true;

You could override or replace Parse and include this check.

A: The problem is that the rounding is taken care of when you do the conversation i.e. Decimal myNumber = Decimal.Parse(myInput) will always return in a rounded number if there are more than 28 decimals.
You don't want to create a big parser either so what I would do is compare the input string value with the new decimal value as a string:
//This is the string input from the user
string myInput = "1.23456789123456789123456789123";

//This is the decimal conversation in your application
Decimal myDecimal = Decimal.Parse(myInput);

//This is the check to see if the input string value from the user is the same
//after we parsed it to a decimal value. Now we need to parse it back to a string to verify
//the two different string values:
if(myInput.CompareTo(myDecimal.ToString()) == 0)
    Console.WriteLine("EQUAL: Have NOT been rounded!");
else
    Console.WriteLine("NOT EQUAL: Have been rounded!");

This way C# will handle all the number stuff and you will only do a quick check.

A: You should have a look at the BigRational impelmentation. It is not (yet?) part of the .Net framework, but it is the aquivalent to the BigInteger class and provides a TryParse method. This way you should be able to compare if your parsed BigRational is equal to the parsed decimal.


text:
Q: sending data with the help of post method in ajax I am having a form with hidden field and want to send the value to another php page process the request and display it inside a div tag. But, AJAX doesn't seem to post the hidden field value
below is my form and ajax code
<form name='cc' method='post' onsubmit='return disp()'>
<input name='id' type='hidden' value='" . $id. "'/>
<input type='submit' name='btnr' value='Display' />
 </form>
 <script>
function disp(){
    var xmlhttp;

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("display").innerHTML=xmlhttp.responseText;
        }
    }
    var id=document.forms["cc"]["id"].value;
    xmlhttp.open("POST","fetch.php",true);

    xmlhttp.send(id);
}
</script>

A: It should be:
xmlhttp.send('id=' + urlencode(id));

You need to include the form element name, so that PHP can put that in $_POST.
You also need to put return false; at the end of disp(), to prevent normal form submission, which will reload the page.


text:
Q: Retrieve "Local" Named Range From sheet (not workbook) Apache POI I have a excel file (XLSX) I want to read with Apache POI with many sheets. I want to filter these sheets to read only the ones where a named range is defined let's say "section1" on the sheet.
For instance lets say there  5 sheets in the workbook and 3 of them have defined a local named range "section1" only these are relevant. I did not find how to that in Apache Poi we can only retrieve all names from the workbook.
What I want is iterate throught each relevant sheet and read the section for each one.


text:
Q: Magento Table Creation Using ORM Method I'm trying to create a new table in the Magento database using Magento's *Varien_Db_Ddl_Table*. Using fresh Magento 1.7.0.2 CE install for this.
I'm at a loss for syntax though. I'm trying to create a BOOLEAN field but I will also settle for a TINYINT if needs be. My createTable looks like this:
$table_one = $installer->getConnection()
->newTable($installer->getTable('my_module/table'))
->addColumn('id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
    'unsigned' => true,
    'identity' => true,
    'nullable' => false,
    'primary' => true,
), 'Entity id')
->addColumn('store_id', Varien_Db_Ddl_Table::TYPE_TEXT, 63, array(
    'nullable' => true,
    'default' => null,
), 'Store view id')
->addColumn('is_active', Varien_Db_Ddl_Table::TYPE_TINYINT, 1, array(
    'nullable' => false,
    'default' => 1,
), 'Status')
->addColumn('created_at', Varien_Db_Ddl_Table::TYPE_TIMESTAMP, null, array(
    'nullable' => true,
    'default' => null,
), 'Creation time')
->addIndex($installer->getIdxName(
    $installer->getTable('my_module/table'),
    array('store_id'),
    Varien_Db_Adapter_Interface::INDEX_TYPE_INDEX
),
array('store_id'),
array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_INDEX)
)
->setComment('My Module Table');
$installer->getConnection()->createTable($table_one);

The field I'm struggling with is is_active. MySQL tries to set as AUTO-INCREMENT and NULL?!?
Can anyone set me straight please or point me to some useful docs? I found these, but no syntax guidelines really :(
Thank you.

A: For future reference, the following syntax will add a TINYINT(1) field - for which BOOLEAN is a MySQL alias:
->addColumn('is_active', Varien_Db_Ddl_Table::TYPE_BOOLEAN, 1, array(
    'nullable' => false,
    'default' => 1,
), 'Status')

And the resulting field in MySQL:
Name, Type, Null, Default
is_active, tinyint(1), No, 1

Hope that helps a future visitor.

A: For the most part, Magento internals handle initial table creation with raw SQL on setup:
app/code/core/Enterprise/Cms/sql/enterprise_cms_setup/mysql4-install-1.6.0.0.0.php
$installer->run("CREATE TABLE IF NOT EXISTS `{$installer->getTable('enterprise_cms/hierarchy_metadata')}` (
  `node_id` INT(10) UNSIGNED NOT NULL,
  `meta_first_last` TINYINT(1) NOT NULL DEFAULT '0',
  `meta_next_previous` TINYINT(1) NOT NULL DEFAULT '0',
  `meta_chapter` TINYINT(1) NOT NULL DEFAULT '0',
  `meta_section` TINYINT(1) NOT NULL DEFAULT '0',
  `pager_visibility` TINYINT(4) UNSIGNED NOT NULL,
  `pager_frame` SMALLINT(6) UNSIGNED NOT NULL,
  `pager_jump` SMALLINT(6) UNSIGNED NOT NULL,
  `menu_visibility` TINYINT(4) UNSIGNED NOT NULL,
  `menu_levels_up` TINYINT(4) UNSIGNED NOT NULL,
  `menu_levels_down` TINYINT(4) UNSIGNED NOT NULL,
  `menu_ordered` TINYINT(4) UNSIGNED NOT NULL,
  `menu_list_type` VARCHAR(50) NOT NULL DEFAULT '',
  PRIMARY KEY (`node_id`),
  CONSTRAINT `FK_ENTERPRISE_CMS_HIERARCHY_METADATA_NODE` FOREIGN KEY (`node_id`) REFERENCES `{$installer->getTable('enterprise_cms/hierarchy_node')}` (`node_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");

You see the TINYINT type being added quite often via addColumn which is available through getConnection() in $installer:
Mage/Core/Catalog/sql/catalog_setup/mysql4-upgrade-0.7.72-0.7.73.php
$installer->getConnection()->addColumn($installer->getTable('catalog/product_super_attribute_label'),
    'use_default', 'tinyint(1) UNSIGNED DEFAULT 0 AFTER store_id');

Which is usually called on an existing table.
There's nothing wrong with using TINYINT(1) as a boolean. If you're dead set against the SHOW CREATE copy-pasta method of popuplating table schema with $installer->run, avoid the setup woes you're having and run the addColumn later as an update in your module:
mysql4-upgrade-0.1.0-0.1.1:
$installer->getConnection()->addColumn($installer->getTable('yourresource/model'),
    'is_active', 'TINYINT(1) UNSIGNED DEFAULT 0 AFTER store_id');


text:
Q: Centralizar div no Bootstrap Olá, tenho uma página em PHP no qual estou usando o Bootstrap para fazer uma simples tela de pesquisa.

            <form class="status">
                <fieldset>

                        Ordre de service:
                        <input class="form-control" id="code" name="code" type="text" placeholder="Ordre de service" value="" onkeypress="return searchKeyPress(event);">

                </fieldset>
            </form>
            <button class="btn btn-success center-block" id="submit">Recherche</button>

http://www.bootply.com/kCqrqsHQ8V
Na página acima é possível ver como está ele..
PS: Estou usando a versão 3.3.6
Gostaria de centralizar horizontalmente e verticalmente a partir da div aonde contém a classe Well, como é possível realizar isso?
Não consigo usando apenas o center-block como usei na imagem.

A: Uma solução seria usar o poder da propriedade transform. Com uma pequena combinação à outras propriedades é possessível ter um alinhamento horizontal e vertical. Se deseja que as imagens tenham um alinhamento semelhante envolva todas as divs em um contêiner e aplique as formatações da classe well a esse contêiner, conforme pode ver abaixo.
.container {
   position: relative;
}

.well {
   position: absolute;
   top: 50%;
   right: 50%;
   transform: translate(50%, 50%);
}

Essa solução resulta no alinhamento em relação a div pai. Ou seja a div.well estará no centro da div.container. Enfim o tamanho e a posicao da div container influenciará na centralização da div filha(well).


text:
Q: error: "Cannot read property 'name' of undefined" The code works fine(for get request) till I want to save data via post request in mongoDb ,  when I use router.post(productController.postProduct)
I get this error :Cannot read property 'name' of undefined"
The export function is:

exports.postProduct=async (req,res)=>{
    try{

    const newProduct=new Products()
    newProduct.save({
        name: req.body.name,
        price:req.body.price
    })

        res.status(201).json({
            status:'success',
            data:{
                tour:newProduct
            }
        })}
        catch(err){
            res.status(404).json({
                status:'fail',
                message:err.message

            })
        }
    }

`The tour Model is

const mongoose=require('mongoose');
const slugify=require("slugify")

const productSchema=new mongoose.Schema({

    name:{
        type:String,
        unique:true,
        required:[true,"A Product  must have name"],
        maxLength:[40,"A Product name mus havr less than or equal to 40"],
        minLength:[10,"A Product name must have atleast 10 characherts"],

    },

    slugify:{
        type:String,
    },

    ratingAverage:{

        type:Number,
        default:4.5,
        min:[1,"The rating must begreater than 0"],
        max:[5,"The rating must be less than 5"],
    },
    ratingQuantity:{
        type:Number,
        default:0
    },
    price:{type:Number,
        required:[true,"A Product must have price"]
    },

     priceDiscount:{
            type:Number,

        },
    summary:{
            type:String,
            trim:true
        },
    description:{
        type:String,
        trim:true
    },

    images:[String],
    createdAt:{
        type:Date,
        default:Date.now()
    },
    startDate:[Date],

},

)

And app.js is:

const express=require('express');
const fs=require("fs")
const app=express()
const mongoose=require("mongoose")
const dotenv=require("dotenv")
dotenv.config({path:"./process.env"})
const morgan =require("morgan")
const productsRoute=require("./Routes/productRoutes")

const DB=process.env.DATABASE.replace(
    "<password>",
    process.env.DATABASE_PASSWORD
)

mongoose.connect(DB,
    {

        useNewUrlParser:true,
        useCreateIndex:true,
        useFindAndModify:false,
        useUnifiedTopology: true
    })
    .then(console.log("DB connection successfull"))

app.use(morgan('dev'))

var port=3000
app.listen(port,()=>{
    console.log(`App is running on the port ${port}`);
})

app.use("/api/v1/products",productsRoute)

All the other HTTP seems to work fine except the post request

A: try putting this app.use(express.urlencoded({extended:false})) in app.js on top of all your routes


text:
Q: ETS table select all records matching id
Hey I have an ets table transactions, part of the table is looking like this.
[
  {"txn_05h0f14877a091yj7358a",
   %{
     account_id: "acc_f5f3f6y7t8s7a5htj78ty",
     amount: 289,
     date: ~D[2022-03-16],
     details: %{
       details: %{
         category: "transport",
         counterparty: %{name: "UBER", type: "organization"},
         processing_status: "complete"
       }
     },
     links: %{
       account: "http://localhost:4000/accounts/acc_f5f3f6y7t8s7a5htj78ty",
       self: "http://localhost:4000/accounts/acc_f5f3f6y7t8s7a5htj78ty/balances/transactions/txn_f5f3f6y7t8s7a5htj78ty"
     },
     running_balance: 100000,
     status: "posted",
     type: "card_payment"
   }}
]

I would like to select all records that are matching account_id and I'm doing something like this
iex(23)> fun = :ets.fun2ms(fn {_, {account_id}} when account_id == "acc_f5f3f6y7t8s7a5htj78ty" -> account_id end)
[{{:_, {:"$1"}}, [{:==, :"$1", "acc_f5f3f6y7t8s7a5htj78ty"}], [:"$1"]}]
iex(24)> :ets.select(:transactions, fun)
[]

but the query is not working properly. What will be a proper way of selecting all records matching account_id?

A: Your approach works but your pattern doesn't match the shape of the data: it expects records of the shape {"txn_05h0f14877a091yj7358a", {"acc_f5f3f6y7t8s7a5htj78ty"}}.
You need to lookup the map :account_id key:
iex> fun = :ets.fun2ms(fn {_, transaction} when transaction.account_id == "acc_f5f3f6y7t8s7a5htj78ty" -> transaction end)
[
  {{:_, :"$1"},
   [{:==, {:map_get, :account_id, :"$1"}, "acc_f5f3f6y7t8s7a5htj78ty"}],
   [:"$1"]}
]
iex> :ets.select(:transactions, fun)
[
  %{
    account_id: "acc_f5f3f6y7t8s7a5htj78ty",
    amount: 289,
    ...
  }
]

Note: The when transaction.account_id == guard needs Elixir >= 1.11, you can also use when :erlang.map_get(:account_id, transaction) == if you are on an older version.


text:
Q: How to access a fab in host activity from fragment in Kotlin? I want to acces the host main activity fab from another fragment and perform some action. How can I do this in Kotlin?
MainActivity
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<fragment
        android:id="@+id/fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation"/>

<com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_baseline_add_24" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: You can get the Activity and cast it to your MainActivity type. The Activity is nullable because only part of the Fragment lifecycle overlaps with being attached to an Activity. Basically, don't access this in property declarations or from lifecycleScope unless using lifecycleScope.launchWhenStarted.
Example:
val activityFab: FloatingActionButton
    get() = (activity as? MainActivity)?.binding?.fab ?:
        error("Can only access if attached to MainActivity")

Just an example. For better encapsulation, you could expose a fab property from the MainActivity instead of the whole binding.


text:
Q: Postgres REASSIGN OWNED for only 1 database I want to use the REASSIGN OWNED query to change all objects in 1 database from owner A to owner B.
Let say I have the following databases:
 postgres              | postgres        | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0             | postgres        | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                       |                 |          |             |             | postgres=CTc/postgres
 template1             | postgres        | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                       |                 |          |             |             | postgres=CTc/postgres
 db1                   | user1           | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 db2                   | user1           | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 db3                   | user2           | UTF8     | en_US.UTF-8 | en_US.UTF-8 |

I want to db1 and all objects inside so they are owned by user2. I run:
postgres=# \c db1
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
You are now connected to database "db1" as user "postgres".
db1=# REASSIGN OWNED BY user1 TO user2;
REASSIGN OWNED

The owner changed as it should for db1 and all of its objects. But the command also changed the owner of db2. Not the objects in db2, just the database (like and ALTER DATABASE statement):
 postgres              | postgres        | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0             | postgres        | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                       |                 |          |             |             | postgres=CTc/postgres
 template1             | postgres        | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                       |                 |          |             |             | postgres=CTc/postgres
 db1                   | user2           | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 db2                   | user2           | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 db3                   | user2           | UTF8     | en_US.UTF-8 | en_US.UTF-8 |

Is this the normal behaviour? How can I run the REASSIGN OWNED without altering other databases?

A: The documentation quoted in the comment by Daniel Vérité states:
old_role

The name of a role. The ownership of all the objects within the current database, and of all shared objects (databases, tablespaces), owned by this role will be reassigned to new_role.

so this is per spec.  If this is not what you want, I think you need to state your use case more fully.


text:
Q: What is the best way to create related types at runtime? How do I determine the type of a class that is related to another class at runtime?
I have figured out a solution, the only problem is that I ended up having to use a define that has to be used in all of the derived classes.
Is there a simpler way to do this that doesn't need the define or a copy paste?
Things to note: both the class and the related class will always have their respective base class, the different classes can share a related class, and as in the example I would like the control class to own the view.
#include <iostream>
#include <string>

class model;

class view {
public:
  view( model *m ) {}
  virtual std::string display() {
    return "view";
  }
};

#define RELATED_CLASS(RELATED)\
typedef RELATED relatedType;\
virtual relatedType*createRelated(){\
return new relatedType(this);}

class model {
public:
  RELATED_CLASS(view)
  model() {}
};

class otherView : public view {
public:
  otherView( model *m ) : view(m) {}
  std::string display() {
    return "otherView";
  }
};

class otherModel : public model {
public:
  RELATED_CLASS(otherView)
  otherModel() {}
};

class control {
public:
  control( model *m ) : m_(m),
      v_( m->createRelated() ) {}
  ~control() { delete v_; }
  std::string display() {
    return v_->display();
  }
  model *m_;
  view  *v_;
};

int main( void ) {
  model m;
  otherModel om;

  model *pm = &om;

  control c1( &m );
  control c2( &om );
  control c3( pm );

  std::cout << c1.display() << std::endl;
  std::cout << c2.display() << std::endl;
  std::cout << c3.display() << std::endl;
}

A: You are trying to implement your own custom RTTI.
However, You can use in built C++ RTTI typeid operator instead.

A: You could use templates instead to avoid #defines, but, either way, note that you're essentially overloading on return type with otherModel's createRelated method.
There's probably a better way to do what you're trying to do.
#include <iostream>
#include <string>

class model;

class view {
public:
  view( model *m ) {}
  virtual std::string display() {
    return "view";
  }
};

class model {
public:
  virtual view* createRelated() {  return new view (this); }
  model() {}
};

template <class Related>
class relatedModel : public model
{
  public:
    relatedModel() : model() {}
    virtual view* createRelated() { return new Related(this);}
} ;

class otherView : public view {
public:
  otherView( model *m ) : view(m) {}
  std::string display() {
    return "otherView";
  }
};

class control {
public:
  control( model *m ) : m_(m),
      v_( m->createRelated() ) {}
  ~control() { delete v_; }
  std::string display() {
    return v_->display();
  }
  model *m_;
  view  *v_;
};

int main( void ) {
  relatedModel<view> m;
  relatedModel<otherView> om;

  model *pm = &om;

  control c1( &m );
  control c2( &om );
  control c3( pm );

  std::cout << c1.display() << std::endl;
  std::cout << c2.display() << std::endl;
  std::cout << c3.display() << std::endl;
}