como eu faço para criar uma função no vbs que ao clicar no enter ele alterna duas janelas ou seja alt + tab

Question: esse é o codigo que estou usando
Set objShell = CreateObject("WScript.Shell")

set Window = CreateObject("InternetExplorer.Application")

Window.RegisterAsBrowser = True
Window.MenuBar = True
Window.ToolBar = True
Window.AddressBar = True
Window.StatusBar = True
Window.FullScreen = False
Window.Resizable = True
Window.Visible = True
Window.Width = 850
Window.Height = 720

Window.Navigate("www.microsoft.com")

wscript.sleep 5000

Window.Navigate2 "www.globo.com",navflags

'while 1<>2

if objShell.SendKeys "{ENTER}" then
    wscript.sleep 2000
    objShell.SendKeys "^{TAB}"

end if

'wend

Está dando erro no if. Alguém pode me dizer o que estou fazendo de errado?
Comment: Não me parece que o método SendKey retorna alguma coisa pra ser  usado no IF como você está fazendo. Retire o IF fora que deve funcionar.
Comment: como faço para executar o ^{TAB} só quando clicar no enter?
Comment: você precisa capturar o evento que ocorre quando o usuário pressiona a tecla enter. Dentro dessa rotina, você executa o TAB. Entretanto, é preciso ver se há como fazer isso via VBS.
Answer: Não conheço codigo no vbsScript que captura tecla: Eu consegui o efeito que você quer me página web em javaScript:


Creating a custom collection that can be bound to a DataGrid

Question: I work for an Architecture firm and I am creating a plug-in for a 3D modeling program to assist design. I have a Building class, and a Floor class. The building contains a reference to a FloorList collection of floors. I'm trying to figure out what to base the FloorList collection off of so that I can minimize the amount of work I need to do to create an interface to edit the collection.
The Floor collection represents a series of building floors that are stacked on top of one another. Each Floor has a Floor.Height property that is read write, and an Floor.Elevation property that is read only and set by totaling the floor heights below the current Floor. So, whenever a Floor is added, removed, moved, or changed in the collection the Floor.Elevation properties need to be updated.
In addition, I want to create a UI to edit this collection. I was thinking of using a DataGrid control where each Floor is listed with its Height and other properties as a row of the control. The user should be able to add, remove, and re order floors using the control. I'd like setting this up to be as easy and flexible as possible. Meaning I'd like to simply be able to bind the collection of Floors to the DataGrid and have the columns of the DataGrid populate based on the properties of the Floor class. If possible I'd like to be able to utilize the built in Add/Remove UI interface of the DataGrid control with out having to mess with setting up a bunch of event relationships between my collection and the DataGrid.
To complicate things further in the future I'll need to be able to allow the user to dynamically add custom properties to the Floors that I'll want them to be able to see and edit in the DataGrid as well. I think I'd end up doing that by having Floor class implement IExtenderProvider. So ultimately the DataGrid would look something like this:

Initial Properties      Future Custom User Properties

Height    Elevation     ProgramType    UnitType  UnitCount
15'       70'           Residential    Luxury    5
15'       55'           Residential    Luxury    5
15'       40'           Residential    Budget    10
20'       20'           Retail         N/A       2
20'       0'            Retail         N/A       3

My question now is what should I base my FloorList collection off of to allow for this functionality? The options I'm considering are as follows.
1) Inherit from List(Floor)

Methods such as Add/Remove are not vitrual and thus I can't not override them to update the elevations

2) Implement IList(Floor)

OnChange event is not built in so if the lists changes the DataGrid will not update (I think?)
I think this is probably the best option but what would I need to do the ensure that changes to the FloorList collection or DataGrid are synced with one another?

3) Inherit from BindingList(Floor)

Method like Add/Remove are not virtual so I can't modify them to update the floor elevations.

4) Implement IBindingList

IBindinglist is not generic and I only want my collection to contain Floor objects
Answer: You should use BindingList for your collection or implement IBindingList as this will notify back the DataGridView about any changes in the list.
Then implement INotifyPropertyChanged interface for Floor class, this will allow for a TwoWay binding mode between your individual Floor items and the DataGridView.
Eric, you could also do something like this
   public class MyFloorCollection : BindingList<Floor>
            {
                public MyFloorCollection()
                    : base()
                {
                    this.ListChanged += new ListChangedEventHandler(MyFloorCollection_ListChanged);

                }

                void MyFloorCollection_ListChanged(object sender, ListChangedEventArgs e)
                {

                 if (e.ListChangedType == ListChangedType.ItemAdded)
                 {

                    Floor newFloor = this[e.NewIndex] as Floor;

                    if (newFloor != null)
                    {
                        newFloor.HeightChanged += new Floor.HeightChangedEventHandler(newFloor_HeightChanged);
                    }
                  }

                }

                void newFloor_HeightChanged(int newValue, int oldValue)
                {
                    //recaluclate
                }

            }

Of course you can create your own HeightChangedEvent and subscribe to that, that way you dont have to go by property names in an if statement.
So your Floor class will look like this
 public class Floor : INotifyPropertyChanged
        {
            private int _height;

            public int Height
            {
                get { return _height; }
                set
                {
                    if (HeightChanged != null)
                        HeightChanged(value, _height);

                    _height = value;
                    OnPropertyChanged("Height");

                }
            }

            public int Elevation { get; set; }

            private void OnPropertyChanged(string property)
            {
                if (this.PropertyChanged != null)
                    this.PropertyChanged(this, new PropertyChangedEventArgs(property));
            }

            #region INotifyPropertyChanged Members

            public event PropertyChangedEventHandler PropertyChanged;

            #endregion

            public delegate void HeightChangedEventHandler(int newValue, int oldValue);
            public event HeightChangedEventHandler HeightChanged;
        }

this way you only have to subscribe to your HeightChanged variable, instead of to PropertyChanged. PropertyChanged will be consumed by the DataGridView to keep a TwoWay binding. I do believe this way is cleaner.
You can also change the delegate and pass the item as the sender.
public delegate void HeightChangedEventHandler(Floor sender, int newValue, int oldValue);

EDIT: To unsubscribe from HeightChanged event you need to override RemoveItem
  protected override void RemoveItem(int index)
        {
            if (index > -1)
                this[index].HeightChanged -= newFloor_HeightChanged;

            base.RemoveItem(index);
        }

Comment: But IBindingList is not generic and I'd prefer to not have to do a bunch of casting from Object types to my Floor type.
Comment: AHh ok that makes sense. So you are having the class respond to it's own ListChanged Event. However, if you were to remove a floor from the list wouldn't the the Event relationship remain and prevent the Floor from being disposed assuming the the event relationship was the only reference to the Floor.

Also the ListChanged event of the collection should be evoked when items in the list change. Do I need to manually link the Floor.PropertyChanged event to the FloorList.ListChanged event or does the BindingList do that automaticly?
Comment: Eric: please see my answer for removing Floor from the list. Its very dirty,but you get the idea. As far as PropertyChanged, I am pretty positive that as long as you implement INotifyPropertyChanged interface, DataGridView will automatically subscribe to it and unsubscribe when needed. You can see this, when you are adding a new Floor, step in and look at PropertyChanged..you'll see its not null.
Comment: When the item is being removed, FOR DEBUGGING PURPOSES make a reference to it -- Floor item = this[index]; in RemoveItem and then look at the item after base.RemoveItem(index) and you'll see PropertyChanged is null as well as HeightChanged. Do this just to see that the events are being unsubscribed, and remove the line after you're satisfied, because you don't need that reference ;)
Comment: hey, let me know if this helped you out. I am quite curious.
Answer: Implement IList(Floor), and have your new collection also implement INotifyPropertyChanged interface.
Answer: You could try exposing an ObservableCollection<Floor> property on some data containing class. Also, the Floor object would need to implement INotifyPropertyChanged to support two-way binding from the UI.


É possível conectar uma aplicação feita em C a algum banco de dados?

Question: Normalmente utilizamos arquivos para salvar dados utilizando linguagem C (eu pelo menos). É possível conectar um banco de dados relacional a alguma aplicação feita em C? Se sim, é preciso alguma biblioteca para isso e como é feita essa conexão? Preferencialmente MySQL.
Comment: Sim, só isso que quer saber?
Comment: De uma olhada neste [artigo](http://www.cyberciti.biz/tips/linux-unix-connect-mysql-c-api-program.html).
Comment: Gostaria de saber como fazer a conexão.
Comment: Em qual banco de dados?
Comment: Qualquer banco relacional, preferencialmente mySql
Answer: Por que não teria como?
Linguagens de programação são apenas mecanismos para se comunicar com o computador. O que faz a comunicação com bancos de dados são códigos geralmente organizados em bibliotecas. Cada banco de dados fornece sua maneira de fazer isso. Muitos banco de dados são escritos em C então é bem direto. Em outras linguagens que costuma ter alguma camada de adaptação.
Exemplo no MySQL:
<code>#include <my_global.h>
#include <mysql.h>

int main() {
    MYSQL *con = mysql_init(NULL);
    if (con == NULL) {
        fprintf(stderr, "%s\n", mysql_error(con));
        exit(1);
    }
    if (mysql_real_connect(con, "localhost", "root", "root_pswd", NULL, 0, NULL, 0) == NULL) {
        fprintf(stderr, "%s\n", mysql_error(con));
        mysql_close(con);
        exit(1);
    }
    if (mysql_query(con, "CREATE DATABASE testdb")) {
        fprintf(stderr, "%s\n", mysql_error(con));
        mysql_close(con);
        exit(1);
    }
    mysql_close(con);
}
</code>
Coloquei no GitHub para referência futura.
Documentação.
Download.
Answer: Sim tem como, o Postgresql mesmo usa muitas funções em C e possui uma library pra isso. Basta add #include
Você vai precisar descobrir onde se encontra o arquivo libpq-fe.h, depois, ao compilar o programa, passamos o diretório acima dentro da opção -I do gcc:
 gcc -o programa -I/usr/include/pgsql programa.c -lpq
Isso supondo que a sua biblioteca está em /usr/include/pgsql. Altere para o diretório onde se encontra a sua. Talvez seja necessário utilizar a opção -L e o diretório, ao invés da opção -I.
Maiores detalhes em:
fonte viva o linux


Auto Update Stats From SQL Database

Question: I'm trying to get an effect like the http://www.minecraft.net page where it auto updates sales from a database, I've been researching this for two months now and no luck.
I have a php file which finds how many results are in a database and displays them as a number, works fine http://tzeale.com/sandbox/stats/pull.php
What I'm trying to do is get the effect like minecraft.net where it auto updates without refreshing the page. Could anyone guide me on what to  do? I don't know what else to try.
Thanks.
Answer: hYou need to use AJAX.
setTimeout, alongside a AJAX call to that pull.php
If you are using jQuery, here is a good example on how to achieve what you want.
Added a simple logic to see if the server is dead, and eventually stop.
var failed = 0;
var limit_failed = 5;
(function updateSales( waitTime ){
   waitTime = waitTime || 1000; // Set to 1 second by default

   setTimeout(function(){
       $.ajax({
           url: 'pull.php',
           success: function( response ){
               // Update something with your response
                alert ("sales are now at: "+ response);
               updateSales(); // Recursion
           },
           error: function(){
                // Error handling - not necessary
               // If the request failed more then (limit_failed) times, you might want to stop it from checking after (limit_failed) times,
               // and in the meanwhile icnrease the wait time, so the server has more time to get back online.
               if( ++failed < limit_failed ){
                   waitTime += 1000;
                   updateSales( waitTime );
               }
           }
       });
   }, waitTime);
})();

Answer: You would use setTimeout and Ajax.  setTimeout would get the data every 1000 ms (or however you set it) using Ajax to get the data.
You would wrap your display count in your html like this for example:

Then your jQuery code would look something like this:
 setTimeout(function(){
   $.get("/sandbox/stats/pull.php",function(data){
      $("#mycount").html(data);
   });
 },1000);

1000 is one second, you can change it if you'd like.  I don't know how to make it animate like that, but it would go inside your $.get() function once you retreive the data.  Also this must be on the same domain as http://tzeale.com/ for the Ajax to work due to same origin policy

HOWEVER, After reviewing te minecraft.net site, I noticed they are loading this data into their page one time, instead of getting it every 1 second:

Then they are not getting live data with this.  They are just getting the current amount, then keep adding 1 to it.
They make it animate using this plugin: http://timeago.yarp.com/
And still using setTimeout() to keep adding 1 to it every second. I don't think this is real users, just a counter starting at the var totalUsers
Comment: Thank you so much! This has been bugging me for nearly three months now! :D

Auto Update Stats From SQL Database


Showing that $\frac{1}{n}\sum\limits_{j = 1}^{n} \left\lfloor \frac{n}{j} \right\rfloor \approx \log(n)$ (with error bounded by 1) using Riemann Sum

Question: Here is my solution so far, but it just doesn't seem right:
Define a function $\sigma_0(x) = \sum\limits_{d \mid x} 1$ on the interval $[1, N]$. The partitions for the Riemann Sum will be of equal length 1 from $[1, N]$. Further, let $x_j = j$ for $j = 1, 2, \ldots, N$. Define $$R_N = \sum\limits_{j = 1}^{N} \sum\limits_{d \mid j} \left( \frac{N}{j} - \left\lfloor\frac{N}{j}\right\rfloor\right)$$ Now, we can use Riemann Sums to estimate that $$\sum\limits_{j = 1}^{N} \sum\limits_{d \mid j} 1\approx \int_{1}^{N} \left[\sum\limits_{d \mid x} 1\right]dx = \sum\limits_{j = 1}^{N} \left\lfloor \frac{N}{j} \right\rfloor$$ Further, since $R_N$ is always greater than 0 but strictly less than $N$, we have that $$A(N) = \frac{1}{N} \sum\limits_{j = 1}^{N} \sum\limits_{d \mid j} 1 \approx \frac{1}{N} \sum\limits_{j = 1}^{N} \left\lfloor \frac{N}{j} \right\rfloor \approx \frac{1}{N} \log(N) + C$$ Recall that the error between the actual value of an integral and its approximation by a finite sum of rectangles is bounded by the width of the rectangles multiplied by the maximum value of the integrand. In our case, $\left\lfloor\frac{N}{j}\right\rfloor$ is the maximum value of the integrand and $\frac{1}{N}$ is the width of each rectangle. Thus, the error is at most $$\frac{1}{N} \left\lfloor\frac{N}{j}\right\rfloor$$ which is equal to 1 when $j = 1$. Therefore the error is bounded by 1.
I am quite lost, so if someone could please help correct my mistakes.
Answer: Just observe that:
$\left\lfloor \frac{n}{j} \right\rfloor$$\leq \frac{n}{j}$.
So, $$\frac{1}{n} \sum_{j=1}^{n} \left\lfloor \frac{n}{j} \right\rfloor < \frac{1}{n} \sum_{j=1}^{n} \frac{n}{j} = \sum_{j=1}^{n} \frac{1}{j} < \log(n) +1.$$
You can find the approximation of the harmonic sum here.


Refining Monte Carlo predictions using observed measurements

Question: I'm trying to build a monte-carlo simulation that can revise it's distribution of outcomes of a project based on observed measurements after the project has started.
I have a few questions about the best way to do this. I'm not a statistician, so please correct me if I am doing something wildly wrong.
For example, let's say I've observed that task x has been selected by person y (whose original 90% CI estimate for the task was [l,h]) , and that y has logged w hours of work to the task.
I can use that data to re-simulate the project under new constraints and compute a new, more accurate, distribution of outcomes.
For example, if w > l, then I know that the lower bound for the time to complete x is now w, not l, and can adjust the distribution used accordingly. However, w is not a 5% lower bound. It's a 0% lower bound (i.e. the limit), so using [w, h] as a 90% CI didn't quite seem correct. As a result I was thinking I could just pick some arbitrarily small number for p(w), say 0.0001, and continue using .05 for p(h) and then generate a new distribution for [w, h] (of course, I would just use the number of deviations for h and w rather than the probabilities).
Is that sound?
What's not immediately clear is what I would do in the case where w > h. I have calibrated estimates with a 90% CI, so I should expect to see this 5% of the time. If I ask: "what do I know in that case", I come up with the following:

I know w and I know my arbitrarily low p(w)
From the original confidence interval (which assumes a normal distribution), I can determinep(w + sigma).
So, I could produce: [w, w + sigma] as an interval, using p(w) and p(w + sigma), and then derive a normal distribution from that (again, just using the z-values).

Is that sound as well?
Comment: Are you familiar with Bayesian inference?
Comment: No. I had to look it up. Are you suggestion that I wouldn't need to re-run the simulation, but instead just adjust the output distribution using the formula here: http://en.wikipedia.org/wiki/Bayesian_inference?
Comment: Well, what's remarkable to me (as a statistician) is that you've already framed your problem in nearly Bayesian terms, wherein you have a basic idea of your quantity of interest and want to iteratively improve upon that idea as you receive more data. Whether you have to reevaluate your simulation or simply do a little algebra depends on the model you decide is "best" for your problem.
Comment: I'm also saying that an investment of time to understand Bayesian inference would provide you with a very flexible toolbox for understanding this and many, many other problems.
Comment: Thanks for the pointers. I think I may have figured out how to apply Bayesian inference to my case (see my 'answer' below).
Answer: Here's my attempt at a (self) answer, based on user777's hints.
At first I was confused by the P(E|H) term in the Bayesian inference formula, thinking P(E|H) is 0 whenever H > E, and I only care about cases where H > E when I'm computing P(H|E).
However, then I reformulated the problem slightly and said "what is the probability that it will take at least H given that it takes at least E". The probably of at least E given at least H is one, so that yields:
$\int {p(H|E)}{dH} = \frac{\int{p(H)}{dH}}{\int^E_0{p(x)}{dx}}$
I believe that means that if I compute a random number using the original normal distribution that I should just be able to multiply it by $\int^E_0{p(x)}{dx}$ to get my new random number.
Rationale:
The normal random number should be $inv(\int{p(x)}{dx})(rand())$. To get a random number corresponding to $p(H|E)$ I need $inv\bigl({\int {p(H|E)}{dH}}\bigr)(rand())$, which should be equal to $\int^E_0{p(x)}{dx}*inv\bigl({\int{p(H)dH}}\bigr)$.
That should be exactly equal to normal_rand(sigma, mu)*cdf(w).
Update:
This needs to be truncated somehow, as the df is only valid when x > w.  I'm not quite sure how to do that.
Update 2:
I ended up using the info here: http://en.wikipedia.org/wiki/Truncated_distribution
to produce a truncated normal distribution. I think I can use that, without the Bayesian update.
Comment: Since the quantity of interest is *additional* time required to a task, we might expect that the lower bound of this variable is zero (we can't go back in time). The gamma distribution is often used to accomplish this, of which the exponential distribution is a special case. But there are many other distributions with support over positive reals. Conversely, the normal distribution has support over the real line, so **any** choice of parameters will always have positive probability below zero.


Select2: Update option after selecting new tag

Question: I implemented a tagging system where you can choose from existing tags or add new tags. After a new tag has been selected it will persisted using an AJAX call.
For achieving this I use the callback createTag and the event select2:select. Because I like to create the tag only when it is selected I do an AJAX call for this if the event select2:select gets triggered.
The problem is that I need to update the already created option of select2 with the ID I get from persisting my new tag to the database. What's the cleanest solution for this?
Here's what I have:
$('select.tags').select2({
     tags: true,
     ajax: {
         url: '{{ path('tag_auto_complete') }}',
         processResults: function (data) {
             return {
                 results: data.items,
                 pagination: {
                     more: false
                 }
             };
         }
     },
     createTag: function (tag) {
         return {
             id: tag.term, // <-- this one should get exchanged after persisting the new tag
             text: tag.term,
             tag: true
         };
     }
 }).on('select2:select', function (evt) {
     if(evt.params.data.tag == false) {
         return;
     }

     $.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
        // ----> Here I need to update the option created in "createTag" with the ID
        option_to_update.value = data.id;

     }, "json");
 });

Comment: Have you tried triggering a change event once the tag is created?
Comment: @BuddhistBeast  should this help me exactly? If I listen to this event my ID is already gone? Or should I listen to the change event instead of the select event?
Comment: related http://stackoverflow.com/questions/23295168/how-do-i-fire-a-new-ajax-on-select2-new-remove-tag-event
Answer: My problem was that I did not add the new tag as an <option> tag to the native select field.
This is necessary because select2 checks for the values set trough select2.val(values) if an <option> tag with this value does exist. If not select2 silently throws the value out of the array and sets the array of values which have a corresponding option tag in the underlying select field.
So this is how it works correct now (for select2 4.0.x):
$('select.tags').select2({
     tags: true,
     ajax: {
         url: '{{ path('tag_auto_complete') }}',
         processResults: function (data) {
             return {
                 results: data.items,
                 pagination: {
                     more: false
                 }
             };
         }
     },
     createTag: function (tag) {
         return {
             id: tag.term,
             text: tag.term,
             tag: true
         };
     }
 }).on('select2:select', function (evt) {
     if(evt.params.data.tag == false) {
         return;
     }

     var select2Element = $(this);

     $.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
        // Add HTML option to select field
        $('<option value="' + data.id + '">' + data.text + '</option>').appendTo(select2Element);

        // Replace the tag name in the current selection with the new persisted ID
        var selection = select2Element.val();
        var index = selection.indexOf(data.text);

        if (index !== -1) {
            selection[index] = data.id.toString();
        }

        select2Element.val(selection).trigger('change');

     }, 'json');
 });

The minimal AJAX response (JSON format) has to look like this:
[
    {'id': '1', 'text': 'foo'},
    {'id': '2', 'text': 'bar'},
    {'id': '3', 'text': 'baz'}
]

You may add additional data to each result for let's say own rendering of the result list with additional data in it.
Answer: Just to update:
The new syntax is
e.params.args.data.id

not
e.params.data.id


Groovy method with optional parameters

Question: I would like to write a wrapper method for a webservice, the service accepts 2 mandatory and 3 optional parameters.
To have a shorter example, I would like to get the following code working
def myMethod(pParm1='1', pParm2='2') {
    println "${pParm1}${pParm2}"
}

myMethod();
myMethod('a')
myMethod(pParm2:'a') // doesn't work as expected
myMethod('b','c')

The output is:
12
a2
[pParm2:a]2
a2
bc

What I would like to achieve is to give one parameter and get 1a as the result.
Is this possible (in the laziest way)?
Answer: Can't be done as it stands...  The code
def myMethod(pParm1='1', pParm2='2'){
    println "${pParm1}${pParm2}"
}

Basically makes groovy create the following methods:
Object myMethod( pParm1, pParm2 ) {
    println "$pParm1$pParm2"
}

Object myMethod( pParm1 ) {
    this.myMethod( pParm1, '2' )
}

Object myMethod() {
    this.myMethod( '1', '2' )
}

One alternative would be to have an optional Map as the first param:
def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
    println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}

myMethod( 'a', 'b' )                // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd')    // prints 'a b 1 2nd'

Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)
Comment: Nope, other way round, as in the answer
Comment: Thanks, thinks looks like a way to go. I'll give it a shot and compare it with the effort when I use NULL values as default for optional parameters. Coming over from the java world I'm quite used to that...
Comment: Am I right, signature of the myMethod should be `def myMethod(String mandatory1, String mandatory2, Map map = [:])`?
Comment: the thing with the map is mentioned here: http://groovy-lang.org/objectorientation.html#_positional_parameters and http://groovy-lang.org/objectorientation.html#_named_parameters
Comment: how optional Map as first parm work ? is there any documentation for this?
Answer: You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}

if argument "optional" not exist, it turns to "null".
Comment: This what he/she already did. The problem is that only last arguments with default values can be omitted.
Answer: Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:
def someMethod(def args) {
    println "MANDATORY1=${args.mandatory1}"
    println "MANDATORY2=${args.mandatory2}"
    println "OPTIONAL1=${args?.optional1}"
    println "OPTIONAL2=${args?.optional2}"
}

someMethod mandatory1:1, mandatory2:2, optional1:3

with the output:
MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null

This looks nicer and the advantage of this is that you can change the order of the parameters as you like.
Comment: Your syntax is wrong, because of the last ?
Comment: I think you got the position of the ? wrong, it should have been:     println "OPTIONAL1=${args.optional1?}"
Answer: We can Deal with Optional parameters in 2 ways

Creating the method parameter with null values:

def generateReview(def id, def createDate=null) {
     return new Review(id, createDate ?: new Date()) // ?: short hand of ternary operator
    }

generateReview(id) // createDate is not passed
generateReview(id, createDate) // createDate is passed

Using Java Optional.of()

def generateReview(def id, Optional<Date> createDate) {
     return new Review(id, createDate.isPresent() ? createDate.get() : new Date())
    }

generateReview(id, Optional.empty()) // createDate is not passed
generateReview(id, Optional.of(createDate)) // createDate is passed

Answer: Had this problem for a Jenkinsfile.
You have 2 Options:

Using Named Parameter
Using Positioned Parameter

Named Parameter
def shouldDeploy(Map args) {
  def isBuilt = args.isBuilt ?: false
  def optional = args.optional ?: true
  echo "isBuilt: ${isBuilt}"
  echo "optional: ${optional}"
  return isBuilt && optional
}

and call it like this: shouldDeploy(isBuilt: true, optional: true)
Positioned Parameter
def shouldDeploy(isBuilt, optional=true) {
    echo "isBuilt: ${isBuilt}"
    echo "optional: ${optional}"
    return isBuilt && optional
}

and call it like this: shouldDeploy(true, true)
Answer: This question, quiet old, it is still searched and relevant. Some previous answers are giving solutions more related with Java but the questions is for Groovy and then you can use named parameters that let you provide default values for them. But, the most useful solution is pass a Map as first parameter and, as commented in the [documentation of Groovy][1]:

When the first argument is a Map, Groovy combines all named parameters
into a Map (regardless of ordering) and supplies the map as the first
parameter. This can be a good approach if your properties are declared
as final (since they will be set in the constructor rather than after
the fact with setters).

So you can provide as many optional parameters as you want as named parameters and, inside the function, give them default values if you want.
[1]: http://groovy-lang.org/objectorientation.html#:~:text=When%20the%20first,fact%20with%20setters).

Groovy method with optional parameters


The correct tool for testing statistically likely source of endpoint?

Question: Background
Whilst I have some experience in statistics, I am not trained in the field and so am at somewhat of a loss with respect to what tool I should employ in the following scenario.
I have a range of products, say, [A ... Z] which require a number of constituent components to be produced over a number of stages. I know what the constituent components are and the quantity of each required to do this. This is unchanging.
I have access to the complete stock (numbers and location) of all products. I also have access to data which enumerates the production and exchange of components. I do not have access to data which tracks individual components. That is, I can only track components as grouped batches.
Aim
My aim is twofold. First, to predict the likelihood of a base component being produced in a given area for the purposes of creating a given product. That is to say, which areas are most used in production for any product.
Secondly, once this has been found, I am trying to predict the likelihood a base component will be used in product A over, say, product Z or any other product.
A base component is the foundational component to produce all subsequent components, which are then used in turn to produce a product.
Analogy (not required to read but may help in explaining)
By way of analogy, let us say the city of Ankh-Morpok produces a number of items including the foobar and the boofar. The foobar ultimately requires 400 giblits, which are either used directly as components or made into other components (which again may be used in other components). The boofar ultimately requires 250 giblits. Each giblit must be extracted from the ground. Giblits are ubquitously available across the city.
My aim is to find which district of the city is likely to extract the most giblets over x time period. And also to predict where a giblit will likely end up; a foobar or a boofar over the same time period. It might seem the foobar would be the answer, but the boofar may be produced in larger quantities, for example, or larger time periods may cause greater stability or fluctuation.
Current attempt
From what little I know, my understanding is that I would require some kind of regression to predict the likely place of origin and likely final product for a given base component. I have been trying to read through statistics workbooks to contextualise my problem and see something similar but as time has gone on, I am under the impression that my question does not have a clear explanatory and response variable. I thought place would be the explanatory variable but perhaps I am wrong here.
Moreover, I am not sure which type of regression (if regression is indeed the correct tool) I should be using. When I read upon the different types, owing to the sheer number of components, places, and products, multivariate linear regression seemed the most apt so I have been working towards learning this, but is this correct?
Question
In the briefest possible terms, is multivariate linear regression the most apt tool for the scenario outlined above? If not, could you suggest materials for me to read, or a better suited tool or approach for the job?
Thank you very much for taking the time to read through this. I appreciate any and all responses.
Comment: Is it possible to have the dataset? I can try to resolve and show you a way. Jm
Comment: Hi @Jmbonni unfortunately, the dataset is under NDA. Is there another way I can present the data which would be useful? I could perhaps create a mock example if that would help? Or if there is anything that needs clarifying, more than happy to do so.
Answer: I'm not sure that this is a statistical problem. Suppose you know that 1000 cars have been made, using 10,000 kg of rubber; and 10,000 wellington boots have been made, using 5,000 kg of rubber. Then 1/3 of the rubber has been used to make boots.
Statistical methods are used when there is randomness - I didn't see any randomness in the problem as you describe it.
Comment: The problem here is that the transformation from the varying demand to the values you want to predict is complicated, so you are unlikely to get a closed form solution. You therefore need to do a simulation, then display the distribution of values from the simulation. The remaining choice is how to provide the demand to the simulation. If you have lots of data, then just use random samples from the actual data. If the actual data fits a well known distribution, then you can use samples from that distribution. If neither holds, then I would use samples from the actual data plus random noise.
Comment: Hi @chrishmorris. Sincere apologies for the delay, I was away and then forgot to reply. Thank you for the comment. I have marked your response as the answer. So if I have it right, the simulation removes potential complexities and then I feed the demand in from whichever is the case according to the three options you stated? Just to be clear, would the simulation simulate supply or something else too? Thank you very much for your help thus far and my apologies again.
Comment: Yes, simulate the supply.
Comment: Great, thank you very much for that. I will probably use random samples from the population although I will also check if it fits a well known distribution too, as per your suggestion.
Comment: Hi @chrishmorris, sorry I should have been clearer. What is static are the 'ingredients', so to speak, of each product. The randomness is in predicting future trends regarding the origin of materials and what they end up as. So how do we know rubber produced in location X will produce primarily cars, and how certain can we be of this? Similarly, how can we know a greater proportion of rubber will come from location Y over location X in the production of cars for example, and how certain can we be of this?
Comment: So the demand for products varies over time? And the figures you have for past demand are regarded as a sample from a distribution? And the question is, given this distribution, what is the distribution of e.g. "% of rubber from Malaya that becomes part of cars"?
Comment: Hi @chrishmorris. That is correct, the demand will vary. The past demand figures are the population data, not a sample. The question as you put it is correct; that is, how may I predict this and with what degree of confidence. Thank you very much for your help so far!


How can I make my public directory writable by nginx and user?

Question: I have my WordPress site newly hosted on a small Linux box with Nginx. Nginx runs as the user www-data just like apache, so I have the entire public_html directory owned by www-data so that WordPress can upload media files, install new plugins, etc.
My question is how can I setup the public_html directory so that a user logged in via SFTP can upload or edit files? I tried doing
chown -R myUserName:www-data public_html

but that didn't work.
Comment: What does "didn't work" mean?
Comment: It still wasn't writable by the server anymore, only the user.
Comment: You might want to look at the answers for [this question](http://serverfault.com/questions/357108/what-are-the-best-linux-permissions-to-use-for-my-website).
Answer: One thing is setting the owner and group - but you need to define whether or not the user and/or group can write.
This will do what you are asking
find /path/to/public_html -type d -exec chmod 775 {} \;
find /path/to/public_html -type f -exec chmod 664 {} \;

However, you don't want your webserver to be able to write to everything on a Wordpress installation.
You want to figure out exactly what directories you need to be writable by reading the Wordpress hardening guide
If you do not do this, rest assured that your site will be hacked at some point. Not necessarily defaced or changed, but attackers often just use a little space on your site to store a phishing page - which can be a pain to fix.
Comment: If the server is not writable to the WordPress install directory, then automatic updates will never work. I had already set the permissions on file, but this changes nothing.
Comment: Those commands will set all files and folders to be writable by user and group. And the group is www-data as you set with your chown, thus giving www-data write access to the files.


Prediction from gam model at X = 0 not equal to intercept

Question: I'm having a problem with GAM.  Specifically when I try to make a prediction at a new data value at the origin, my prediction is not equal to the intercept.  Can someone help me understand why this is happening?  Here is an example:
set.seed(42)
N = 1000
x = runif(N)
y = x^.22+rnorm(N)
m = gam(y~s(x))
summary(m)
predict(m,newdata = data.frame(x=0))

Family: gaussian
Link function: identity

Formula:
y ~ s(x)

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.78115    0.03164   24.69   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
       edf Ref.df     F  p-value
s(x) 2.158  2.687 13.79 7.61e-08 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.0344   Deviance explained = 3.65%
GCV score = 1.0043  Scale est. = 1.0011    n = 1000
1> predict(m,newdata = data.frame(x=0))
        1
0.3756038

I think the prediction should be equal to the intercept when x = 0, but it's not!
Answer: You think wrong since your are not considering the spline functions! Let's first evaluate the spline at your new data i.e. 0. To do that I will use the predict function but with the type argument as terms.
> spline.at.0=predict(m,newdata = data.frame(x=0), type = "terms")
> spline.at.0
        s(x)
1 -0.4055495
attr(,"constant")
(Intercept)
  0.7811533

Now lets look at the coefficients of your fitted model m
> coef(m)
  (Intercept)        s(x).1        s(x).2        s(x).3        s(x).4        s(x).5        s(x).6        s(x).7
 7.811533e-01 -5.353668e-02  1.676821e-02 -3.391826e-05 -1.724044e-02 -4.702938e-03 -1.383030e-02 -3.876392e-03
       s(x).8        s(x).9
 1.009809e-01  2.413780e-01

So the first one is actually the intercept. When you use the predict function (without specifying exactly the type argument), it gives you by default  the linear predictor i.e. :
> predict.at.0=coef(m)[1]+spline.at.0
> predict.at.0
       s(x)
1 0.3756038
attr(,"constant")
(Intercept)
  0.7811533

Which is basically the same as:
> predict(m,newdata = data.frame(x=0))
        1
0.3756038

I recommend you to see the help file ?predict.gam in package mgcv. BTW, you need to add the package you are using ... like require(mgcv) in your code since there are more than one package doing GAM.
Comment: thank you!  does this have something to do with the "identifiability constraints"?  I never understand what is meant by that.


Combine multiple metrics to evaluate / choose a ML Model

Question: I'm working on a credit binary classification task.For this business is something usual to meassure model's performance from two metrics:
ROC AUC and KS .This sounds reasonable until I have to choose between two models with "contradictory" results. Let's say I have the following:
Model 1 : AUC: .90 & KS: .70
 Model 2 : AUC: .85 & KS: .80
I have been thinking on a way to combine these two (or even more metrics) to make a final decision on which model is better.
Question:
1. What would be a correct way of combining multiple metrics to make a decision of a model to be selected?
2. What are the characteristics this combination should fulfill?
(limit to infinity 1 , limit to minus infinity 0)
EDIT:
I'm looking for either a formula to combine multiple metrics into one score to be able to make decisions based on that or a methodology to take into consideration more than one metric to make decisions
Comment: Are you looking for some sort of formula that you can apply, or more general ideas for an approach to consider the AUC and KS scores in model evaluation?
Comment: @hamedbh It would be great having both approaches
Comment: How are you using KS?
Comment: Take a look at the multi-metric evaluation on cross_val_score and GridSearchCV [here](https://scikit-learn.org/stable/auto_examples/model_selection/plot_multi_metric_evaluation.html). I believe this is exactly what you are looking for.
Answer: You could take a more general approach overall. Depending on the computational burden of the model you could use Leave One Out Cross Validation. This approach is desirable when the models are not nested, or when metrics provide contradictory results, as is your case.
Comment: How would you evaluate performance on the left-out data?
Answer: Are the two models parametric? If yes, you can weigh them with respective likelihood scores. This is equivalent to Bayesian aggregation (weighing with Bayesian scores) when the prior distribution over candidate models is uniform. Bayesian aggregation is a popular, scientific way of combining models when there is belief that each of them carries some useful information (when one model does not stochastically dominate another).
For example, my suggestion works if you have performed classification using logit or probit models. On the other hand, if you are using tree-based methods an extension of the aforementioned ideas is necessary.


I encountered a problem in the Flattening a linked list question. When I pass the arguments by reference in the merge function I get an error why?

Question: /*
 * Definition for linked list.
 * class Node {
 *  public:
 *      int data;
 *      Node *next;
 *      Node *child;
 *      Node() : data(0), next(nullptr), child(nullptr){};
 *      Node(int x) : data(x), next(nullptr), child(nullptr) {}
 *      Node(int x, Node *next, Node *child) : data(x), next(next), child(child) {}
 * };
 */

Node* merge(Node* &a, Node* &b){

    Node* temp = new Node(0);
    Node* ans = temp;

    while(a!=NULL && b!=NULL){

        if(a->data data){
            ans->child = a;
            ans = a;
            ans->next = NULL;
            a = a->child;
        }
        else{
            ans->child = b;
            ans = b;
            ans->next = NULL;
            b = b->child;
        }
    }

    while(a!=NULL){
        ans->child = a;
        ans = a;
        ans->next = NULL;
        a = a->child;
    }

    while(b!=NULL){
        ans->child = b;
        ans = b;
        ans->next = NULL;
        b = b->child;
    }

    temp = temp->child;
    ans->child = NULL;
    return temp;
}

Node* flattenLinkedList(Node* head)
{
    // Write your code here
    if (head == NULL || head->next==NULL) {
        return head;
    }

    return merge(head, flattenLinkedList(head->next));
}

Compilation Failed
In file included from runner.c++:21:0:
solution.h: In function 'Node* flattenLinkedList(Node*)':
solution.h:61:38: error: invalid initialization of non-const reference of type 'Node*&' from an rvalue of type 'Node*'
  return merge(head, flattenLinkedList(head->next));
                                      ^
solution.h:14:7: note:   initializing argument 2 of 'Node* merge(Node*&, Node*&)'
 Node* merge(Node* &a, Node* &b){
       ^

Comment: @JahnviAgarwal Do not tag `dsa`.  Did you read what the `dsa` tag means?
Comment: why does `merge` take two non-const references? Does merging two lists modify the heads of the two original lists?
Comment: I think [this](https://stackoverflow.com/a/8294009/2550406) answers your question. I found it by searching for your error `invalid initialization of non-const reference of type rvalue`
Comment: I did not understand.
Comment: if `merge` wants to modify its second parameter (ie its a non-const reference), then it does not make sense to pass it a temporary (the pointer returned from the `flattenLinkedList` function).
Comment: Yes after merging head is modified
Comment: @JahnviAgarwal I've tried to explain (below in an answer) what I've read in the Q&A I've linked but tbh I am not sure at all about my interpretation. It's just my best guess. I hope somebody else can clarify it better. I have retracted my close vote because while the questions might have the same answer, your question actually also needs additional explanation for the specific case you are presenting here
Comment: Your `merge` function leaks memory. Try implementing it without calling `new`.
Comment: Why do you need `merge` parameters to be references? After merging, both become null pointers. The caller doesn't get any new information from this.
Answer: Since you said the linked Q&A was not enough, here's my attempt. I hope it's not wrong, but it sounds plausible to me:
Your function signatures
Node* flattenLinkedList(Node* head)
Node* merge(Node* &a, Node* &b)

describe that flattenLinkedList returns a Node* - a pointer to a Node. And that merge takes a Node* by reference. The thing about taking a reference and using it is: the referenced object should still exist by the time you use it. In your case the referenced object is a pointer.
But because c++ is weird (in other words, I do not know enough to explain this) the scope of the argument is quite short-lived. Let's say you'd split it up, like they do in this question:
{
Node* temp = flattenLinkedList(head->next);
return merge(head, temp);
}

This conceptually does the same thing, except that temp has a clear scope: once you exit the function's {} block by returning, temp will no longer exist.
If you do it both in the same line though, as you have done
return merge(head, /* temp */ flattenLinkedList(head->next));

then the temp you return from flattenLinkedList might cease to exist immediately... This is the problem the compiler is pointing out (I think).
The linked question has a comment on this:

Note that there isn't a strict technical reason for this restriction. It would have been just as easy to implement to allow mutable references to temporaries. Forbidding it is a design decision of C++

Sidenote: what is the point of having a non-const reference as an argument if you discard temp anyway after it is modified? You could also make the second argument of merge a Node* b instead of a Node* &b, right?


Unable to connect to my newly created postgresql server in Azure

Question: After creating a new server in the Azure Database for PostgreSQL service, I get the following error when trying to connect to it. The server has been created since I see a notification on the Azure portal to the effect and can also view the server details on the Azure portal.
psql: FATAL:  no pg_hba.conf entry for host "<ipv4 address>", user "cloudsa", database "postgres",
Am I missing any steps in making my postgres server accessible to my client (pgadmin/psql)?
Answer: The most common reason for getting this error right after creating a new postgresql server in Azure is not setting up firewall rules correctly so your app/client has access to the newly created server. Read more about firewall settings in Azure and use either the portal or CLI to manage firewall rules for your newly created postgres server. Once you have setup firewall rules correctly, you should be able to connect to the server.


PHP: Automatically Saving a dynamic PDF to the remote server using DOMPDF

Question: I am using the dompdf library to create my table based PDF and I can view it online or I can have it download to the users folder of choice.
But what I would like to do is have it save it to the remote server( i dont need it to be save to the users PC), like an automatically upload script that would create the file then upload it to the remote server, so i can then use it within my application later on.
is it possible to point the $_FILES["file"] script say so fetch the php page that creates the pdf and it then uploads it from there.
Answer: You can do one thing like below which i am doing for my application. First create a folder in your server under the root directory for example. Then change read write permissions to that folder using chmod command.
Then get all the code in $html string.
$dompdf->load_html($html);
$dompdf->render();
$pdf = $dompdf->output();
$file_location = $_SERVER['DOCUMENT_ROOT']."app_folder_name/pdfReports/".$pdf_name.".pdf";
file_put_contents($file_location,$pdf);

Where pdfReports is the folder which i created to save all the pdf's. You can change to your folder name.
Comment: Thanks for this the file_put_contents has done the trick, i works on my simple page now to get it to work on my more complicated dynamic page, but thanks also thanks to Stephan, kufudo and Vincent Kelleher
Comment: i just need to create one page but the table will be long, but looking into using PHPExcel to do the heavy work then using dompdf to convert, which i am doing now, will just need to implement the same fiel upload code to it and it should all be done.
Comment: are you free to talk for 5 minutes
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/24439/discussion-between-simon-davies-and-venkat)
Answer: Quoted from PHP manual :

A URL can be used as a filename with this function if the fopen
  wrappers have been enabled.See fopen() for more details on how to
  specify the filename. See the Supported Protocols and Wrappers for
  links to information about what abilities the various wrappers have,
  notes on their usage, and information on any predefined variables they
  may provide.

Source: http://php.net/manual/en/function.file-put-contents.php
Answer: Is it feasible to create the PDF directly on the server instead, and let the client download it if he needs it? If so, you could use wkhtmltppdf to convert any HTML page into a PDF on the server and save it and/or stream it to the client.
http://code.google.com/p/wkhtmltopdf/
Answer: Can't you use the FTP functions of PHP ?


Android: Different appearience on UI of date and time picker

Question: I am using date and time picker in my application and referred the tutorial
from here but the problem is that when i run it on kitkat 4.2.2 it show output as follows: but when i run it on lollipop 5.1.1 it shows output
showing two different UI on same code i dont know how to fix this problem.I have also applied some validations on it but its working with first case but not with second case.Please help.
Comment: Is that really a problem? It adapts to the UI style normally used on the device.
Comment: @Henry yeah but in second UI Style it is not considering any validations applied by me
Comment: you can try to use different UI libraries for date pickers if you want
Answer: if you want it identical to the first one you can add
android:datePickerMode="spinner"
android:calendarViewShown="false"

Comment: is that same applied to timepicker as well?
Answer: This differs as per OS version in devices. It is a system date and time picker.
So it will be as per OS version and may - may not differ in each of the OS version.
Whatever you are seeing is correct and is OS level change.
Comment: but how to deal with validations with second screen because in my case validations not working for second approch
Comment: all validations i applied like date should not be less than todays date and time picker user can not select time less than current time for todays date
Comment: according to me it should work in both cases, in my app its working for all devices with different OS versions @Dhiraj OR show code
Comment: or else user can select time between 6AM-10PM For other dates for validation purpose on time picker i have used http://stackoverflow.com/questions/13516389/android-timepickerdialog-set-max-time this for reference
Comment: from this link, it should be working if you haved used it @Dhiraj
Comment: its working for datepicker validation but not for time picker validation
Comment: i am trying to work it but if it fails i will tell you
Comment: @ Amit Vaghela ok just trying
Answer: I think you can force it to look a certain way by changing compilessdkversion and the targetsdkversion accordingly in your gradle file.
edit: on second thought, I'm not 100% sure it'll work...might cause problems on some versions.
The 100% positive way to get the classic spinner is like Maxi said to set the attribute datepickermode atribute to spinner.
To answer whats been asked of Maxi regarding timePicker. You have to set the timePickerMode attribute to "spinner" in a similar fashion to avoid the round clock interface and get the classic spinner.
<TimePicker
    ...
     android:timePickerMode="spinner" />


Adventure game constructor method problems Java

Question: I'm creating a text adventure game in Java. I've created an exit, room, creature and an item class, and now I'm instantiating and putting values for them in my main class.
I'm getting this problem though: as I'm creating exits for my room, I'm getting a compiler error saying

Constructor Exit in class Exit cannot be applied to given types

This is the line of code I'm getting the compiler error for:
Exit exit1 = new Exit("Exit1", "Exit description", "Exit transition text");

and in my Exit class I have this constructor method:
public void Exit(String exit, String exitDescription, String exitTransition) {
    this.Exit(exit, exitDescription, exitTransition);
}

but every time I tell the IDE (Netbeans) to correct the compiler error, it generates this in my Exit class:
Exit(String exit1, String exit_description, String exit_transition_text) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

So my question is, why doesn't my constructor method work? Also, I had help from my professor and I believe he said that I don't want the generated code. Don't remember exactly though.
Comment: `public void Exit` isn't a constructor, it's a method
Comment: Please read the help/mcve document and supply the missing pieces.  You might also back up to the previous working version of the code and try moving forward just a couple of lines at a time.  We can't help too much without the minimal, complete, and verifiable example (mcve).
Answer: This is not a constructor:
public void Exit(String exit, String exitDescription, String exitTransition) {

constructors have no return type.
This is a constructor:
public Exit(String exit, String exitDescription, String exitTransition) {

Of course you know that even if this were a valid constructor the code in its body doesn't make much sense as it appears you're trying to have the constructor call itself recursively:
// void removed
public Exit(String exit, String exitDescription, String exitTransition) {
    this.Exit(exit, exitDescription, exitTransition); // this calls itself!
}

Comment: @noct27: You might not want to knock our talking as it's all in an attempt to improve this answer. You're asking for free advice, so please accept all you get in good faith and without being too critical. Note you will get better answers with better questions. To find out how to ask better questions please go through the [tour], the [help] and the [how to ask a good question](http://stackoverflow.com/help/how-to-ask) sections.
Comment: @noct27 thing is that constructor is not a method http://stackoverflow.com/questions/19061599/methods-vs-constructors-in-java
Comment: @Hovercraft I would do but I'm using my mobile which makes answering questions almost impossible. I'd have made this a community wiki answer too.
Comment: @noct27: I was just stating fact as you can't delete a question that has an up-voted answer. It's just one of the rules of the site. Also, note that a "community wiki" means that I don't get rep points for up-votes for this answer. This was per my choice.
Comment: You could also say something about the body of the constructor. I'm not sure what the OP is trying to do there.
Comment: Okay thanks that helped me so much, so in the scope of this method do I put anything there? Or keep it blank since I will be doing all that when I call the method inside my main class?
Comment: removing the void return statement made all the compiler errors disappear so, ill go read the constructor method chapter again tonight to get a better understanding
Comment: @noct27: yes, there's no such thing as a "constructor method". There are constructors and there are methods, and you don't want to confuse the two.
Comment: @PaulBoddington: this is community wiki answer, so no one gets rep for it (I felt that the question was too basic for me to get rep for this answer), and all can improve it. So please pitch in.
Comment: public Exit(String exit, String exitDescription, String exitTransition){

    }                       that is what I have in my Exit class, its a constructor and not a method because constructors are not methods, they're two different things. Am I correct?
Comment: Dont know what a community wiki answer is, will it help me get more answers? Dont want people talking to each other on my question like a chat page, rather get productive answers.
Comment: I understand, and will do, I fixed me compiler error so thank you guys for your input. Didnt mean to knock your talking, just couldnt tell if your "talking" was directed at me or not. I looked into my edit and saw my errors and will improve for next time, however I will be deleting this question because I resolved it.
Comment: @noct27: you may try to delete this question, but you won't succeed.
Comment: @HovercraftFullOfEels If it doesnt need to be deleted it's fine with me, just dont want to waste people space on the screen. Sorry for being courteous
Comment: but hopefully it can help people in the future, and maybe I can do something right for once in my life
Comment: @HovercraftFullOfEels I understand, well thank you for your help. You have helped a struggling computer science student.


Como transformar um texto que peguei de um site com web scraping em um arquivo txt?

Question: htmlPagina10 = pagina.locator('xpath=exemplo')
print(htmlPagina10.text_content())

estou usando python
eu usei essa primeira linha do código para localizar uma parte especifica de um texto da internet.
e a segunda linha para printar a parte especifica no terminal
e esta funcionando tudo certo, esta encontrando e printando no terminal
porem eu quero copiar o texto e colocar ele em um arquivo txt, como posso fazer isso?
Answer: Basta utilizar a função open para abrir um arquivo no modo escrita e escrever o texto nele:
htmlPagina10 = pagina.locator('xpath=exemplo')

with open('resultado.txt', 'w') as stream:
  stream.write(htmlPagina10.text_content())

Isso irá gerar o arquivo resultado.txt com o conteúdo que deseja.


How to interpret a switch from Em (Aeolian) to Bm?

Question: I'm self taught, so I know just a few things on scales and modes, some probably wrong.
So the other day I was composing a new song. I believe it starts in E minor, as I was playing over the Chords Em and D
Then, came a part with:
C, G, C, G (still matching the Em scale)
And it felt nice to me to end it with this progression:
C, Bm, A#, A.
After this bridge, it feels like I changed the scale, since I'm now playing over Bm, A and soloing over the Bm (B as root). This sounds right to me, but from a musical theory standpoint, I can't explain this progression.
My questions are:

With music theory terms.. what have I done ? did I change the song's Tonality? or Scale? or Mode? Or maybe I wasn't really playing Em in the first place ? Is this normal ? are there any rules on how you can do such a change?
How can I get back to the the Em scale? I want to close the Bm , A part and return to the Em, D but I can't find a way to do this transition. Do I need to make some Chord progression to do this? any hints on that ?
Answer: I would analyze it as follows:

    Em D

is indeed E minor. Since you go from D back to Em, it has a "modal" feel - Aeolian or Dorian. In a diatonic E minor scale, I'd expect to see a d# somewhere. (Not saying that you should, it sounds fine)

    C G

Still in e minor. As you repeat it more often, it might start to sound like G major (the relative major of E minor)

    C Bm

Without any information about the rhythm you're playing it can be difficult to draw a conclusion, but to me this sounds you're still in Em; in fact, C can be seen a a substitution chord for Em (third lower) and Bm as a substitution of D (also, a third lower).
(Not sure of it fits your song but if you have a longish pattern repeating Em D, you could occasionally substitute Em with C and D with Bm just for variety. If you don't overdo that, it may start to sound as an "announcement" of the C Bm progression in this bridge)

    A# A

This is where it becomes interesting. The progression of a major chord followed by a major chord a semi-tone below it often sounds as a VI-V progression in a (melodic) minor scale. The scale that would in this case be Dm; For this reason I would probably analyze it as:

    Bb A

Rather than A# A.
Now you proceed with:

    Bm A

Note that this is exactly like Em D, but a fourth lower (fifth higher). Now, I just argued that the Bb A progression suggested Dm. But the A could just as easily progress to D major. And interestingly, Bm is a substitution chord (third lower) of D.
At this point I will argue that the progression from A to Bm is actually an interrupted or deceptive cadence (http://en.wikipedia.org/wiki/Cadence_(music)#Interrupted_.28deceptive.29_cadence). That is, the A raises expectation to go to D major, but instead, it progresses to the relative minor of D major, which is to say Bm.
Going back to Em is simple - Tim already pointed out that you can simply use a B7. Since you're coming from A, and A B7 is in the melodic minor scale of E minor, the move back to E minor will sound very natural, and doesn't need any extra chords or preparation.
That said, you could spice it up a little to again use substitution chords, this time for Bm and A. These would be G and Fm respectively. So you could do

    Bm A | Bm Fm

And then restate your C G chords that got you there:

    G C

If you then let the C follow up by a B7, you get a alot of tension that make the  return to Em feel inevitable. (This C B is same thing as what I mentioned before about Bb A - the C B will sound as VI V progression, in this case in the scale of Em)

    G C | B7 B7 | Em
Comment: @RolandBouman - a plagal cadence would go from D to A, or may just be Bm to A. Did you mean an interrupted cadence? I mentioned a diminished in my answer - try Eo between A7 and Bm.
Comment: Yes, the scale change starts at the Bb chord. The new scale is Bm. The move from A to Bm, rather than the expected D, is called the actual plagal cadence.

The interesting thing is that only when you hit the A chord does the change to either D or Bm become possible. While you're still at the Bb chord, this change is not determined yet. Bb is called the pivot chord - the modulation revolves around that. All chords before it are in the old key, the chords after it are in the new key. You could use the Bb to move to yet another key. For example, if you follow Bb up with C7 you'd end up in F or Fm
Comment: I'll admit, that's the first time I've heard of Plagal Cadence :) So I did change the scale, right ?
Comment: Oh wait, scrap that remark about Fm. Fm doesn't work because it has an a flat, which is just too far off from what precedes it. But Bb C7 F works fine. What could also work is Bb C7 Dm. The C7 to Dm would again be a plagal cadence. It just means following up the dominant chord with the relative minor chord instead of the expected tonic major chord.
Comment: Yet another exciting progression from Bb could be to E7, and from there to Am. Bb to E7 works, because the Bb then sounds as the Napolitan 2nd chord in Am, and you start hearing that way once you introduce the E7 (which is the dominant of Am)
Comment: Another thought. The progression C Bm Bb A is actually a little unusual. It can work, but it can also sound a bit artificial. If your goal is to continue in Bm, perhaps a more straightforward would be if you'd move from G directly to A7, and then continue in Bm. So, Em D | Em D | C G | C G | A7 A7 | Bm. An even more direct way to go to Bm would be to avoid the plagal cadence from A7 to Bm, and to use F#7 to prepare the move to Bm. And to get to F#7 you could precede it by Em. Try it: Em D | Em D | C G | C G | Em #F7 | Bm. This works because Em #F7 Bm forms an authentic cadence, iv V7 i in Bm.
Comment: I totally get a 'pivoting' feeling while playing the Bb|A Chords. Like building up a surprise / uncertainty feel
Comment: @Tim, you're right. That's what I meant. Interruped, not plagal. Sorry for the confusion, and thanks for pointing it out.
Answer: Seems like you start in Em, as you said.The A#/Bb before the A is a tritone substitution for E, the dominant that normally leads to A.Sounds good, works well.It's a common change - Bm - E - A, the oft used ii-V-I.
If you feel that A fits better than Am in the first part, you are probably in E Dorian, rather than Emin. I know there isn't an A featured, but just try each to hear the one that would (if used) fit better.
After this, you could be in A or Bm. If we think in terms of A, then a root of B puts it into B Dorian, which is nearly a full minor.
Getting back to Em might entail using a B or B7 bar as this is the dominant of Em. Before the B bar, a diminished or half diminished (m7b5) bar will be useful to lead the way.The B after some Bm will sound rather like a 'tierce de picardie', although it won't be in its usual place at the end of the whole tune. You may, however, feel that you can make the very last chord an Emaj.This sounds effective and final.


jQuery Draggable plugin integration with Views 3

Question: I want draggable and sortable contents by admin. So, installed jQuery UI and put this code in my main.js:
<code>$(function() {
    $( ".panels-flexible-region" ).sortable({
      revert: true
    });
    $( "#makyaj .views-row" ).draggable({
      connectToSortable: ".panels-flexible-region",
      helper: "clone",
      revert: "invalid"
    });
    $( "ul, li" ).disableSelection();
  });
</code>
Yes, it works. But i want use this option only admin user. Whether View Sort Type: Jquery Draggable and qhat sets the admin users so they can see it.
Is it possible? Can i integration Views and jQuery UI Draggable?
Answer: I know this isn't exactly what you asked for, but have you considered using the draggable views module? It does what you aim to do without you having to code anything.
Answer: You can do something along these lines in a custom module...
<code>function mymodule_init() {
  global $user;

  if ($user->uid==1) { // super/admin user, add role based logic if needed or desired
    drupal_add_js('path/to/admin-only.js');
  }
}
</code>
...where 'path/to/admin-only.js' is a file containing JS you want added only for your admin/super user.  Look into drupal_add_js() for more information.


How to formal paragraph text via jquery?

Question: I'm trying to create a syntax highlighter that reviews code and adds bolding to certain keywords.  I attempted to replace a given keyword with  keyword , but the  tags were actually visible in the paragraph.  How can I actually format the text?  This is my code.
var textbox = $("#textbox")
var code = $("#code")

var patterns = {
    " ": ["local", "function"]
}

function format(text) {
    for (var pattern in patterns) {
        for (var keyword in pattern) {
            text = text.replace(patterns[pattern][keyword], pattern.replace(" ", patterns[pattern][keyword]))
        }
    }
    return text
}

textbox.change(function() {
    code.text(format(textbox.val()))
})

Answer: Your problem is you are using text() method which will treat any html entities as text also.
Use html() instead since you are including html tags
textbox.change(function() {
    code.html(format(textbox.val()))
})


Proving $S_1-S_2$ is monotone decreasing

Question: I have system number (1) as:
$S_1'=-bS_1I_1+(1-c)aI_1$
$I_1'=bS_1I_1-aI_1$
And on the other hand I have system number (2) as:
$S_2'=-bS_2I_2+aI_2$
$I_2'=bS_2I_2-aI_2$
All parameters $a,b,c>0$.
Both systems have the same initial conditions as in $S_1(0)=S_2(0)=s_0>0$ and $I_1(0)=I_2(0)=i_0>0$.
I want to prove that $S_1-S_2$ is decreasing for $s_0>\frac{a}{b}$.
What I proved so far:

I proved $S_1-S_2$ and $I_1-I_2$ are negative for all $t>0$.
Using the initial conditions then I have $S_1=  \frac{(1-c)a}{b}+(s_0- \frac{(1-c)a}{b}$$ )e^{-\int_{0}^{t} bI_1(t) \ dt}$.
Similarly, I obtained $S_2=  \frac{a}{b}+(s_0- \frac{a}{b}$$ )e^{-\int_{0}^{t} bI_2(t) \ dt}$.
From 2 and 3 we conclude that $S_1,S_2$ are monotone decreasing and that for $s_0>\frac{a}{b}$ we have $\frac{-ca}{b}<S_1-S_2<0$.
Initially we have $(S_1-S_2)'<0$ and because $S_1,S_2$ are $C^\infty$ then $(S_1-S_2)$ decreases initially and $$\lim_{t\rightarrow \infty}(S_1-S_2)'(t)=0.$$
I expressed $(S_1-S_2)'=F(t)(S_1-S_2)+G(t)$ where $G(t),F(t)$ are negative ($F(t)$ starts being negative from a certain point $t_0$ in case that $F(0)>0$) and descending toward finite limit.

Despite all that I can't seem to prove that $(S_1-S_2)(t)$ is decreasing for $t>0$. I checked this via simulations and indeed it is the case but I'm trying by contradiction and can't find something that can lead to a contradiction in anything. Help is appreciated!
Comment: The second system can be solved explicitly by noting that $I_2'=I_2(bS_2-a)=I_2(b(s_0+i_0-I_2)-a)$. This is very close to the logistic differential equation. I do not know whether it can help or not. https://en.wikipedia.org/wiki/Logistic_function#Logistic_differential_equation
Comment: It doesn't help because the first system cannot be solved explicitly so I doubt it very much. Also the answer given below is based on an assumption I did not write.
Answer: It looks like it is false in general. A particular counterexample is $b=1, a=30, c=0.5, s_0=31, i_0=1$ where the monotonicity reverses for $t>0.95$. Below I'll try to explain how I found that and what is behind that effect.
We will change the variables like in my answer to Brenda's previous post and work with the "implicit solution"
$$
S_\sigma(\xi)=-\sigma+(s+\sigma)e^{-\xi},
\\
I_\sigma(\xi)=i-\sigma\xi+(s+\sigma)(1-e^{-\xi}),
\\
t_\sigma(\xi)=\int_0^\xi\frac{d\eta}{i-\sigma\eta+(s+\sigma)(1-e^{-\eta})}\,,
$$
where the meaningful values of $\xi$ are those for which $I_\sigma>0$ on $[0,\xi]$.
The current conjecture is equivalent to the statement that for $s,\sigma>0$, we have
$$
-\frac{dS_{\sigma}}{dt_{\sigma}}\ge -\frac{dS_0}{dt_0}
$$
when $t_{\sigma}=t_0$.
The last condition (the agreement of time) is equivalent to the differential relation between the parameters $\xi_\sigma$ and $\xi_0$, which is
$$
\frac{d\xi_\sigma}{i-\sigma\xi_\sigma+(s+\sigma)(1-e^{-\xi_\sigma})}=
\frac{d\xi_0}{i+s(1-e^{-\xi_0})},.
$$
Introducing new variables $y=1-e^{-\xi_\sigma}$ and $x=1-e^{-\xi_0}$ and playing with the chain rule and elementary algebra a bit more, we arrive at the following equivalent reformulation of the conjecture:
If $y(0)=0$ and $y'=F(x,y)=\frac{i+\sigma\log(1-y)+(s+\sigma)y}{i+sx}\frac{1-y}{1-x}$ on $[0,1)$, then $\frac{s+\sigma}s y'=\frac{s+\sigma}sF(x,y)\ge 1$ on $[0,1)$.
Since $\psi(x)=-\log(1-y)-y\ge 0$, it is easy to see that $y$ lags behind $x$ all the time and as $x\to 1$, we have $y\to y_1$ where $y_1$ solves the equation $i+sy_1-\sigma\psi(y_1)=0$. Clearly, $y_1<1$.
We now will consider the "endgame" for $x$ close to $1$. Then $F(x,y)\approx \frac{(\sigma\psi'(y_1)-s)(1-y_1)}{i+s} \frac{y_1-y}{1-x}$. If the first fraction equals $\rho>1$, then in the endgame we have, roughly speaking, $y_1-y\approx (1-x)^\rho$ and $F(x,y)\to 0$ as $x\to 1$. It is fairly clear that we can achieve it by increasing $\sigma>0$ to some large value keeping other parameters fixed because $\psi'(y)/\psi(y)\to+\infty$ as $y\to 0$ and that what the above example (in which $s=i=1, \sigma=15$, so $y_1\approx 0.3686$ and $\rho\approx 2.45$) is based upon.
I do not know whether $\rho>1$ is a necessary condition for breaking the monotonicity though.
Comment: I don't understand anything you did in the last paragraph. Does this try to imply that we can't have t_delta=t_0 from a certain time? I don't see what is the contradiction here exactly.
Comment: @Brenda 1) Do you understand what was going on *before* the last paragraph? 2) Of course, not: for every time $t$, there are values of $\xi_0$ and $\xi_\sigma$ for which $t_0=t_\sigma=t$. The story is that the conjecture is equivalent to $\frac{s+\sigma}s F(x,y)>1$ all the way, which is incompatible with $F(x,y)\to 0$ as $x\to 1$. 3) Do you want do switch to the chat room?
Comment: Now I see the relation between that line and the original conjecture and now makes sense to have this analysis…. I guess what I don't understand are the sub-conclusions on the way like the (1-x)^p part but maybe I should try to simulate those to see it properly
Comment: I guess at some point I believed the claim to be false as it was impossible to prove it no matter what I tried. But this approach is so neat and elegant. Very nice!


not working with   and 's

Question: I have the following code:

Seus dados

Name Test Test

Email firstname.lastname@example.com

Address 44, Test Street
Test/TS

Phone (999) 999 999 999

I need that the span lines up to 30% of the li and at the same time that the last li (Phone) don't overlap the li of the Address.
I already have three boxes col-md-4 side by side that needs to be visible.
Thank you!
Comment: It's not clear what you are trying to do. `position:absolute` will overlay as it's now outside the document flow. do you have an image of what this is *supposed* to look like?
Comment: Per default, `span` is an **inline** element. Inline elements don't accept `width`. Apply `display: inline-block;` to be able to assign a `width`.
Answer: The problems are

Absolute positioning removes the element from the normal flow, so there may be overlaps.
span elements are inline by default, therefore the width property does not apply. Make them inline-block instead.

.Dados > ul > li > span {
  display: inline-block;
  vertical-align: top;
}
.Dados > ul > li > span:nth-child(1) {
  width: 30%;
}

.Dados > h4 { text-transform: uppercase; }
.Dados > ul { margin-left: 0; }
.Dados > ul > li > span {
  display: inline-block;
  vertical-align: top;
}
.Dados > ul > li > span:nth-child(1) { width: 30%; }

Seus dados

Name Test Test

Email email@example.com

Address 44, Test Street
Test/TS

Phone (999) 999 999 999

Comment: Thank you! I tried using your 1st post and it already worded fine!
Comment: @SergioCostaFaria Yes, the edit was just to fix a minor thing: if the first span had multiple lines, the bullet wouldn't be aligned with the first one. So I added `vertical-align: top` to the first span too.
Answer: Since you are already clearing floats on the li, you might as well float the spans too.

    .Dados h4 {
      text-transform: uppercase;
    }
    .Dados ul {
      margin-left: 0;
    }
    .Dados ul li {
      clear: both;
      list-style-type: none;
    }
    .Dados ul li span {
      float: left;
    }
    .Dados ul li span:nth-child(1) {
      width: 30%;
    }
    .Dados ul li span:nth-child(2) {
      width: 70%;
    }

Seus dados

Name  Test Test

Email  email@example.com

Address  44, Test Street
Test/TS

Phone  (999) 999 999 999

not working with   and 's


$A$ algebra of finite type over $\mathbb{Z}$, $\mathfrak{m}$ max ideal implies $A/\mathfrak{m}$ is a finite field?

Question: Suppose $A$ is an algebra of finite type over $\mathbb{Z}$ (i.e. a finitely generated ring). If $\mathfrak{m}$ is a maximal ideal of $A$, does it follow that $A/\mathfrak{m}$ is a finite field?
Comment: Is $A$ a unital algebra?
Answer: Yes, that's true. For the proof, it suffices to show that $K := A/{\mathfrak m}$ has positive characteristic, as then it is a finitely generated field extension of ${\mathbb F}_p$, and as such finite dimensional over ${\mathbb F}_p$ by Zariski's Lemma.
Suppose on the contrary that $\text{char}(K)=0$, so $K$ is a finitely generated - hence finite algebraic - field extension of ${\mathbb Q}$ which is moreover finitely generated as a ring. Adjoining to ${\mathbb Z}$ all coefficients of the minimal polynomials of a chosen set of generators of $K/{\mathbb Z}$ shows the existence of an $n\in{\mathbb Z}\setminus\{0\}$ such that $K$ is algebraic over ${\mathbb Z}[n^{-1}]$. This implies that $K/{\mathbb Z}[n^{-1}]$ is finite, so ${\mathbb Z}[n^{-1}]$ is a field - contradiction. $\Box$
While it (hopefully) works, I don't particularly like the argument because it's indirect.

Refined question: Is there a constructive proof of ${\mathfrak m}\cap{\mathbb Z}\neq\{0\}$ for ${\mathfrak m}\lhd{\mathbb Z}[X_1,\ldots,X_n]$ maximal?


How do you prevent short lambdas from being split between two lines?

Question: I've got a clang-format question regarding C++ lambdas.  I've noticed new behavior with short, but not on-line lambdas after upgrading to Clang-Format 15.0.1.  I call them "Two-line lambdas" below.  Examples:
One-line lambdas
// good/unchanged
auto shortLambda= []() { doSomething(); };

Two-line lambdas:
// unwanted/new behavior
const auto mediumLambda = [some, args, here](More arguments)
{ return doSomething(some, args, here, arguments); };

Multiline Lambdas:
// good/unchanged
const auto longLambda= [some, args, here](Are here)
{
   auto result =doSomething(some, args, here, arguments);
   return result;
};

Desired behavior of Two-line lambdas:
// desired
const auto mediumLambda = [some, args, here](More arguments)
{
   return doSomething(some, args, here, arguments);
};

Rational: "two line" if statements are not smashed together on two lines
// Good/unchanged
if (condition)
{
   doWhatever();
}

// Bad/unconfigured:
if (condition)
{ doWhatever(); }

I can get all lambdas to be multiline ones by setting AllowShortLambdasOnASingleLine : None - but I do want the ones that can fit on one line to fit on one line.
How can I avoid 'two line lambdas?
Relevant configurations:
# Basic
Language : Cpp
Standard : c++20
ColumnLimit : '110'

# Tabs
TabWidth : '3'
IndentWidth : '3'
UseTab : Never

# Braces/Parens (Allman style)
BreakBeforeBraces : Custom
BraceWrapping:
  AfterCaseLabel:  true
  AfterClass:      true
  AfterControlStatement: true
  AfterEnum:       true
  AfterFunction:   true
  AfterNamespace:  true
  AfterObjCDeclaration: true
  AfterStruct:     true
  AfterUnion:      true
  AfterExternBlock: true
  BeforeCatch:     true
  BeforeElse:      true
  BeforeLambdaBody: true
  IndentBraces:    false
  SplitEmptyFunction: true
  SplitEmptyRecord: true
  SplitEmptyNamespace: true
Cpp11BracedListStyle : true
SpaceBeforeParens : ControlStatements
SpacesInParentheses  : false
SpaceInEmptyParentheses : false

# Functions
AlignAfterOpenBracket : Align
AllowShortBlocksOnASingleLine : false
AllowShortFunctionsOnASingleLine : Inline
BinPackArguments : true
BinPackParameters  : true
AllowAllParametersOfDeclarationOnNextLine : true
IndentWrappedFunctionNames : false
AlwaysBreakAfterReturnType : None
AlwaysBreakAfterDefinitionReturnType : None

# Lambdas
AllowShortLambdasOnASingleLine : All

Edit: added semicolons to make valid C++.
Answer: I'm afraid that is not possible. If I were to guess, the tool first checks that you allow short lambdas, then notices that it won't fit in one line, so it applies BraceWrapping: BeforeLambdaBody and rests satisfied, because everything is within column limits now.
If you can sacrifice Allman's style in this case, BraceWrapping: BeforeLambdaBody set to false will result in
const auto mediumLambda = [some, args, here](More arguments) {
    return doSomething(some, args, here, arguments);
};

while keeping short lambdas on one line and breaking ending }; if not possible to keep it in one line.

It may or may not be a bug, but it would certainly be worth filling a bug ticket to clang to either change this behaviour or improve documentation, explaining what the tool does in this particular case.
Comment: Thank you, @yksisarvinen.  I was afraid that was the answer.  I cannot (I guess would rather not) sacrifice the Allman style, otherwise what you suggested does work.


Using Dapper with HanaDb

Question: I'm writing a new library so that our in-house projects can connect to various SAP Business One databases. For a while we've been using PetaPoco which can be configured to handle HanaDb quite nicely, but I've been looking at Dapper as a newer, potentially simpler ORM. The problem is that I don't know how to configure it to HanaDB.
In our code, it's possible to use the same SQL queries on both Microsoft SQL targets and HanaDB targets provided that we use double quotes to delimit all fields. This is possible because PetaPoco can be configured such that a parameter reference such as '@CardCode' in our query works on HANA, we can configure HANA's colon character in the provider.
Using PetaPoco it's also possible to add a custom mapping to deal with HANA's peculiar HanaDecimal type.
I'm wondering whether anybody knows whether it's possible to configure Dapper in a similar way i.e.

Add a data type mapping to handle data that comes into the c# world as a HanaDecimal
Internally convert @Parameter in the query to :Parameter so that we can always use the @ prefixed version in our queries.

I have seen some code suggesting that Dapper.Contrib can change the prefix, but I'm not using that - it also sounds as though the setting is across all connections in the process (not just HANA connections) and only allows use of the colon prefix, it doesn't hide the use of the colon prefix, so it may not be what I'm looking for.
It may be the case that I can only use Dapper on SQL only projects, but I'm hopeful that I can get this to work for me.
Any help is greatly appreciated.

Update: I tried adding an SQLMapper.TypeHandler, but it's not quite the solution I'm after. TypeHandle handles the situation where the Poco has a specific non-intrinsic type, such as a Role class, but with HanaDb, the actual DB connector reads Decimal Columns as a HanaDecimal type. The HanaDecimal type would actually need to map to a 'decimal' in the Poco.
I can map HanaDecimal to 'decimal' by using a SqlMapper.TypeHandler<decimal>, but theoretically I could specify my target property as decimal, or double, float or even int, long, uint, ulong etc. So I'd have to write a whole raft of mappers.
Does Dapper instead have a kind of mapper that get's triggered based on the incoming object type instead of the target type on the POCO? Or even better a mechanism that triggers on the incoming but also states the target type (which is what PetaPoco has).
For now, it seems that I'd have to write custom mappers for a whole raft of numeric types - buy wouldn't this slow down the whole thing?
Mark
Comment: With Dapper you write your own SQL, so it should handle it.
Comment: Re the parameter: with Dapper you would typically write the native SQL, so you'd use `:Parameter` - Dapper should handle that, since colon parameters are not uncommon; re the HanaDecimal: see `TypeHandler`
Answer: I ended up adding these classes (below) that are registered via SqlMapper.AddTypeHandler - it's the only way that I can think to do. If anybody has a better solution, then let me know - cheers.
public class HanaDecimalToDecimalTypeHandler : SqlMapper.TypeHandler<decimal>
{
    public override decimal Parse(object value)
    {
        return (value as HanaDecimal?) != null ? ((HanaDecimal)value).ToDecimal() : Convert.ToDecimal(value);
    }

    public override void SetValue(IDbDataParameter parameter, decimal value)
    {
        parameter.Value = value;
    }
}

public class HanaDecimalToDoubleTypeHandler : SqlMapper.TypeHandler<double>
{
    public override double Parse(object value)
    {
        return (value as HanaDecimal?) != null ? (double)((HanaDecimal)value).ToDecimal() : Convert.ToDouble(value);
    }

    public override void SetValue(IDbDataParameter parameter, double value)
    {
        parameter.Value = value;
    }
}

public class HanaDecimalToLongTypeHandler : SqlMapper.TypeHandler<long>
{
    public override long Parse(object value)
    {
        return (value as HanaDecimal?) != null ? (long)((HanaDecimal)value).ToDecimal() : Convert.ToInt64(value);
    }

    public override void SetValue(IDbDataParameter parameter, long value)
    {
        parameter.Value = value;
    }
}

public class HanaDecimalToIntTypeHandler : SqlMapper.TypeHandler<int>
{
    public override int Parse(object value)
    {
        return (value as HanaDecimal?) != null ? (int)((HanaDecimal)value).ToDecimal() : Convert.ToInt32(value);
    }

    public override void SetValue(IDbDataParameter parameter, int value)
    {
        parameter.Value = value;
    }
}

Using Dapper with HanaDb


$G$ is a connected graph. Show that if $A,B$ are bonds, and $e \in A \cap B$, there is a bond $C \subseteq A \cup B \setminus \{e\}$

Question: $G$ is a connected graph. Show that if $A,B$ are bonds, and $e \in A \cap B$, there is a bond $C \subseteq A \cup B \setminus \{e\}$
A bond is a set of edges $X$ so that $G \setminus X$ has two connectivity components.
Any hints and assistance would be much appreciated!
Answer: Let $G = (V,E)$ be a connected graph.
Every bond of $G$ is a cut.
A cut $F \subseteq E$ is a set of edges of $G$ such that there are vertex sets $V_1, V_2 \subseteq V$ with $F = E(V_1,V_2) := \{vw \in E:: v \in V_1 \wedge w \in V_2\}$.
The set of all cuts (including the empty cut) of a graph $G$ is the cut space $\mathcal C^*(G)$ of $G$.
The cut space $\mathcal C^*(G)$ is a vector space over $GF(2)$,
i.e., the field with only two elements $\{0,1\}$,
with the symmetric difference $\dotplus$ of sets as addition (in detail $A \dotplus B := (A\cup B)\setminus (A \cap B)$ for sets $A$ and $B$),
that is, two cuts $F_1,F_2 \in \mathcal C^*(G)$ can be added $F_1 \dotplus F_2 \in \mathcal C^*(G)$.
Back to your question: If $A,B \in \mathcal C^*(G)$ are bonds,
then $A\dotplus B \in \mathcal C^*(G)$ is a cut.
Note that $e \notin A \dotplus B$ because $e \in A\cap B$.
A bond is also a minimal non-empty cut.
Note that in a connected graph no cut is empty.
Since $A \dotplus B$ is a cut,
there must be a minimal cut contained in it,
i.e., there must be a bond $C \in \mathcal C^*(G)$
with $C \subseteq A \dotplus B \subseteq (A \cup B)\setminus \{e\}$.


Docker-client Java API : The server failed to respond with a valid HTTP response

Question: Managed to solve an issue which I posted about yesterday where the Java client library couldn't connect to my daemon but now I have a new problem which I cant find any info about online.
I ran the Boot2Docker v1.6 Windows installer on Win7 64 bit. I can run docker commands just fine. Then I pulled the latest Docker-client master branch (v2.7.22) from https://github.com/spotify/docker-client and ran it in Eclipse Java IDE. In DefaultDockerClient I changed DEFAULT_HOST and DEFAULT_PORT to the values which Docker seemed to be using https://docs.docker.com/installation/images/windows-boot2docker-cmd.png (the default values were giving me localhost:2375 connection refused errors).
I tried running the following commands:
final DockerClient docker = DefaultDockerClient.fromEnv().build();
List results = docker.searchImages("ubuntu");

My result is an Apache error going:
 Exception in thread "main" com.spotify.docker.client.DockerException: java.util.concurrent.ExecutionException: javax.ws.rs.ProcessingException: org.apache.http.client.ClientProtocolException
at com.spotify.docker.client.DefaultDockerClient.propagate(DefaultDockerClient.java:1109)
at com.spotify.docker.client.DefaultDockerClient.request(DefaultDockerClient.java:1028)
at com.spotify.docker.client.DefaultDockerClient.searchImages(DefaultDockerClient.java:653)
at com.spotify.docker.client.main.Test.main(Test.java:28)
Caused by: java.util.concurrent.ExecutionException: javax.ws.rs.ProcessingException: org.apache.http.client.ClientProtocolException
at jersey.repackaged.com.google.common.util.concurrent.AbstractFuture$Sync.getValue(AbstractFuture.java:306)
at jersey.repackaged.com.google.common.util.concurrent.AbstractFuture$Sync.get(AbstractFuture.java:293)
at jersey.repackaged.com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:116)
at com.spotify.docker.client.DefaultDockerClient.request(DefaultDockerClient.java:1026)
... 2 more
Caused by: javax.ws.rs.ProcessingException: org.apache.http.client.ClientProtocolException
at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:517)
at org.glassfish.jersey.apache.connector.ApacheConnector$1.run(ApacheConnector.java:527)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at jersey.repackaged.com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:293)
at jersey.repackaged.com.google.common.util.concurrent.AbstractListeningExecutorService.submit(AbstractListeningExecutorService.java:49)
at jersey.repackaged.com.google.common.util.concurrent.AbstractListeningExecutorService.submit(AbstractListeningExecutorService.java:45)
at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:523)
at org.glassfish.jersey.client.ClientRuntime$1.run(ClientRuntime.java:169)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:320)
at org.glassfish.jersey.client.ClientRuntime$2.run(ClientRuntime.java:201)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:469)
... 20 more
Caused by: org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:151)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:260)
at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:161)
at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:153)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:271)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:123)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:254)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
... 22 more

Does anyone know how I can read the HTTP message/where the logs are stored by the Apache library? I also tried it using the v2.7.21 client version but I had the same errors.
Any ideas how to solve or is anyone else on here also using the same library in combination with boot2docker Windows installer? I am looking for advice from people who are using this library please
Comment: I also want to add that yesterday I was getting "connection refused" errors due to the Docker daemon not being available outside of the Linux VM (which is now fixed due to new docker version) and after that I also got the same message before I edited the HOST:PORT in the library configuration. So I do believe that the client can connect to the daemon since it stopped giving me that error now.
Answer: I'm guessing that you do not have your DOCKER_CERT_PATH environment variable set, because I was able to reproduce your exception by running those two lines after unsetting my own DOCKER_CERT_PATH.
Also the "connection refused" errors would probably have been avoided if your DOCKER_HOST environment variables were set correctly.  Again, I can reproduce by unsetting my own DOCKER_HOST variable.
The values that you need to set for these environment variables are normally displayed at the end of the boot2docker init command, as described at https://docs.docker.com/installation/mac/.  You can also see them again by running boot2docker shellinit.
Answer: Its working after setting Environment variables DOCKER_CERT_PATH and DOCKER_HOST


como incluir arquivos javascript em arquivo um arquivo javascript?

Question: então, estou precisando incluir um arquivo javascript dentro de um arquivo javascript , mas eu não como fazer isso
ex:

incluir arquivo.js em arquivo2.js
Comment: Se é só incluir, não tem problema copiar todo o conteúdo de `arquivo.js` e colar no topo do conteúdo do `arquivo2.js`. Agora, se precisa utilizar uma função criada no primeiro arquivo, edite sua pergunta e descreva melhor o que precisa fazer.
Answer: Olá, não é possível fazer esse tipo de include no JS.
Porem você pode usar import e export para reutilizar código dentro de outro arquivo. Porém em uma funcionalidade do EcmaScript 6 ainda não está implementado em todos os browsers você precisa usar transpilers como Babel para funcionar
Ex.:
dado o arquivo function.js
function returnName(name) {
 console.log('Olá ' + name)
}
export default returnName

e arquivo index.js
import returnName from './function'

returnName('Salatiel)
// Olá, Salatiel

Veja a documentação do import e export
Answer: Para usar import e export você tem que está usando a lib do Babel, então use module.exports
module.exports é uma variável global no JS pode colocar suas funções, classes e até variáveis, para importar um módulo nesse modelo você tem que usar o require()
const minhaFunc = require('caminhoDoArquivo')


div by iframe over

Question: I want put a div by iframe over a video containing an active player
is it possible ?
Comment: not entirly shure what you mean. Is the video Flash, Quicktime, Windows Media Player, etc. And what do you mean by "div by iFrame"
Answer: If the video you are talking about is in flash, so long as you set wmode=transparent in the flash embed code, you can place HTML on top of the flash content using css z-index.
Comment: sadly wmode=transparent adversely affects firefox scroll-wheel :( .. it's always something~~
Answer: Actually you may want to use wmode="opaque"

div by iframe over