How to generate directed acyclic graph with long shortest path between two nodes in python

Question: I want to compare several routing algorithms in terms of time needed to find the shortest path between two nodes in directed acyclic graph (DAG).
I wrote code for the algorithms, but I am having problem to generate DAG for which it is computationally complex to find the shortest path. For example, when I generated 100-node DAG by following this approach, the graph was very connected and for any combination of source and destination nodes I got three-hop long route in the "best" case.
Any idea how to overcome this problem?
Comment: Do you want a path that is "long" or one that is difficult to find?  You can make a simple circular graph (e.g., each node with one edge pointing to the next, and the last pointing to the first) with paths as long as you like.
Comment: Perhaps this approach helps: generating the DAG from a random matrix ([link](http://mathematica.stackexchange.com/a/613)).
Answer: Let your graph be a union of a path and a "half complete graph". A "half complete graph" (sorry for the silly name) is a graph, where you connect each node to all other nodes with higher id (eg. 1 -> 2, 1 -> 3, 2 -> 3). This guarantees a big number of edges (due to the "half complete graph") and a long shortest path because of the path. You can connect some of the nodes in the path to nodes in the "half complete graph".
Example
Graph with 14 nodes:
1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10
11 - 12
11 - 13
11 - 14
12 - 13
12 - 14
13 - 14
2 - 13
4 - 14
You can continue adding edges from nodes 1-9 to nodes 11-14

Find a path between 1 and 10.
Comment: I need an idea for algorithm that will generate DAG. If I keep adding edges on my own (but randomly) as you suggested, at the end I could get short route as optimal solution again.
Comment: @user2683229 You should always constrain yourself to the method above. You should not add edges totally randomly, instead you should follow the steps described above (ie. create a path and a the half complete graph). Node 1 and 10 in the above example will not be reachable through any of the other points, only 2-3-4-5-6-7-8-9. This will guarantee the length.


How to extract structured information from a text string?

Question: I have a text string containing unstructured data and I would like to analyze it in order to extract structured information. In particular, this text string specifies when a service is operational (the days and the hours). This text string may be written in different ways:

a list containing one or more day names;
hours may be written next to the names of the days to which they refer;
the string may contain one or more range of days (each range of days could have a certain range of hours);
the name of the days may not be present, and in this case it could be replaced by "every day" or the words "workdays" or by "holidays";
etc..

What approach could I use to be able to extract structured information from such a text string? Are there specific algorithms to achieve this purpose? Should I use a classifier (artificial neural networks, random forests, etc.)?
Comment: Did you consider to use [Regular expressions](http://en.wikipedia.org/wiki/Regular_expression) ?
Answer:
What approach could I use to be able to extract structured information from such a text string?

The task corresponds to named-entity recognition + relation extraction. Two main choices:

Unsupervised, which in your case  most likely mean defining regular expressions and a bunch of heuristic ( e.g., hours directly succeeds days to reach that refer to )
Supervised

You can mix both choices, e.g. perform the named-entity recognition supervisedly, and  relation extraction unsupervisedly.
From the examples you gave, I'd go unsupervisedly at first.


Problem with Hyper-V guest services install on Windows 7

Question: We are trying to setup Windows 7 clients under Hyper-V for testing; however, guest services are not installing.  Are there new guest services available, or is there a way to force the install on Windows 7?
Answer: Are you running one of the supported hosts? "The guest operating systems are supported for Hyper-V in Windows Server 2008 R2, Hyper-V in Windows Server 2008 with Service Pack 2, and Hyper-V version 1 (KB950050, "Hyper-V Update for Windows Server 2008 x64 Edition")."
See: http://technet.microsoft.com/en-us/library/cc794868(WS.10).aspx
Various Pages state that the integration components are already installed in Windows 7.
e.g.: http://blogs.msdn.com/virtual_pc_guy/archive/2009/01/12/windows-7-on-hyper-v.aspx
Comment: I'll vote for "already installed" - my Win7 virtual shows up in SCVMM as VM Additions Detected, though there's nothing to remove.
Comment: Yes, I believe Windows 7 already has the integration components installed.
Comment: Wow, that was a brain dead moment.  You are correct. :)


How can I add a field in Entityform / hook_form_alter

Question: I'm trying to add a field to the form in hook_form_alter. What's the proper way of adding fields in this hook in case of entityform?
I tried to add it this way:
<code>$form['leadname'] = array(
    '#type' => 'hidden',
    '#value' => 'abc'
);
</code>
but I have the impression that this is not the way it should be done...
Answer: That is the way it should be done.
For example using
<code>MODULE_form_ENTITYFORM_MACHINE_NAME_entityform_edit_form_alter(&$form, &$form_state) {}
</code>
Answer: You have to use the following API's

field_create_field : Creates a field.
field_create_instance : Creates an instance of a field, binding it to a bundle.
field_delete_field : Marks a field and its instances and data for deletion.
field_delete_instance : Marks a field instance and its data for deletion.

Reference

Programmatically create a field in Drupal 7
Comment: This is not what the they asked.


Finding all n×n permutation matrices

Question: If I have a doubly stochastic matrix, how can I find the set of all basic feasible solutions?
Here's Wikipedia on doubly stochastic matrices.
Comment: According to the link: "The principal fact about doubly stochastic matrices is the Birkhoff–von Neumann theorem. This states that the set $B_n$  of doubly stochastic matrices of order $n$ is the convex hull of the set of permutation matrices (of order $n$), and furthermore that the vertices (extreme points) of $B_n$  are precisely the permutation matrices."   Since the basic feasible solutions (BFS) are the extreme points, is your question about how to find the set of all permutation matrices?
Comment: Yes, is there an algorithm to do so?
Comment: Would you edit your title and question (and tags) to that effect?
Answer: Don Knuth's Volume 4, Fascicle 2, of The Art of Computer Programming has a long section on generating all permutations, including algorithms for doing so.  I found a draft here online.  (Update: The link still works, but it is now to a zipped file.  However, Knuth has since published Volume 4A: Combinatorial Algorithms, Part 1, which includes this material on generating permutations as Section 184.108.40.206. )
Then, going from a permutation to a permutation matrix is fairly straightforward.  For example, suppose you have the permutation 1342 of the numbers 1, 2, 3, and 4.  That can be represented in two-line form as
$$\begin{matrix}1&2&3&4\\1&4&2&3\end{matrix}$$
because the permutation sends 1 to the first position, 2 to the fourth position, etc.
Then the permutation matrix is the matrix with 1's in entries (1,1), (2,4), (3,2), (4,3), and 0's elsewhere; i.e.,
$$\begin{pmatrix}1&0&0&0\\0&0&0&1\\0&1&0&0\\0&0&1&0\end{pmatrix}$$
Comment: @J.M.: Would you mind editing the title so that it better reflects what the OP really wanted?  I had the rep to do that until they ended the public beta earlier today. :)
Comment: Nice! This neatly solves a problem I had a few months ago. Actually, if it were not for you, I'd not have known Knuth is writing new volumes of TAOCP. Thanks a bunch!
Comment: I aim to please. Better?

Finding all n×n permutation matrices


Problemas com tipagem no angular

Question: Eu criei um novo projeto no angular depois de algum tempo e com o projeto limpo eu tentei criar uma variável mas percebi que a tipagem está diferente pois nos meus antigos projetos não dava erro. Não entendo muito bem angular, ainda.
O que eu costumava fazer era: variavel: string;
Mas agora, neste novo projeto está dando erro em "variavel".
A tipagem está diferente agora? Não sei o que se passa.
Answer: O que se passa é que nas versões mais recentes do Angular, a checagem de tipos ficou ainda mais estrita.

https://angular.io/guide/strict-mode
https://blog.angular.io/angular-cli-strict-mode-c94ba5965f63

O resultado disso é que você precisa ser mais explícito na hora de declarar suas variáveis.
O código abaixo, por exemplo, vai dar erro.
export class MyComponent {
  title: string;
}

O motivo do erro é que eu estou dizendo que o tipo de title é string, mas eu não estou inicializando, logo, seu valor é undefined.
Para ajeitar isto temos algumas opções:
Opção 1: Inicialize-a. É a opção que eu recomendo para a maioria dos casos.
title: string = '';

// Ou apenas...
title = '';

Opção 2: Marque-a como opcional, assim dizemos que ela pode ser undefined.
title?: string

Opção 3: Mude o tipo para string | undefined, é mais ou menos como a opção anterior, mas mais explícita.
title: string | undefined;

Opção 4: Marque-a com o Non-null assertion operator. Com isto estamos garantindo para o compilador que a variável nunca será null e nem undefined, só que eu só recomendo usar isso em situações específicas porque vc fica responsável por garantir que o valor será sempre válido.
title!: string;

Problemas com tipagem no angular


generic lambdas in c++14

Question: I'm trying to compile the following code in VS2019:
auto moveToEnd = []<typename T>(std::vector<T>& into, std::vector<T>& from)
{
    into.insert(std::end(into), std::make_move_iterator(std::begin(from))
        , std::make_move_iterator(std::end(from)));
};

However, I get an error:

'<' skipping unexpected token/s before lambda body

Note: I'm using a C++14 compiler.
Comment: https://isocpp.org/wiki/faq/cpp14-language#generic-lambdas
Answer: Those ain't the regular generic lambdas. Specifying the template parameter list for a lambda is a C++20 feature. The C++14 "generic lambdas" merely let you use auto in lambda parameters.
Comment: @NissimLevy a generic lambda, where type of parameter is `auto`, or a template function ,provided your lambda expression have no capture
Comment: so what can i use instead in c++14? just a regular template function instead of lambda?

generic lambdas in c++14


MVC user format output

Question: I have a C# MVC Project, and allow for users to select the way in which their data can be outputted (i.e. speed in kmh/mph, time in CST, ESt, etc., Distance in KMs, Miles, Meters, Hecters, etc.).  Rather than running back to the db each time to retrieve the settings, on logon i stuff it into the encrypted cookies user data portion.  I am also using the service-repository pattern where my services are implemented in the BLL and models defined in the BOL. I am also returning the data as JsonResults (using NewtonSoft Library). What is the best strategy (where and how) to convert the data to the user specified type without passing this unit preference information into the Business Logic Layers? I was initially thinking about using customAttributes and writing my own CustomJsonResult actionResult, that would use reflection and generate the Json string, but this would require my own object traversal algorithm.  My primary concern is that i want to make my app stateless.
Answer: I think that this conversion could be performed in the mapping layer which converts your business objects into view models that are passed to the view. So the controller would query the business layer to retrieve a model then will query the user preference which was stored into a cookie and would pass those two entities to the mapping layer which will perform the necessary conversions and formatting based on the user locale and return a view model ready to be transmitted to the strongly typed view which would simply output the information.
Another possibility is to use custom HTML helpers inside your view which would take the model value and based on the user preferences stored into the cookie output perform the conversion and output the formatted string.
Comment: Hey Darin, thanks for the insight, however I am passing my Data back to differing ActionResults i.e JsonResult(), CSVResult(), etc. Thus, i need that data in the correct format before i send it to these default methods. You are correct I could do this with static helper functions IF i was rendering to html views. But I am not :s
Comment: @Amit, then my first suggestion for performing the conversion in the mapping layer stays valid.

MVC user format output


resolution of vii 7th chord 3rd inversion

Question:
The image above (from Korean composer Byung Dong Paik's Theory of Harmonics, page 130) shows progressions diminished and half-diminished 7th chords 3rd inversion
But there seems to be another solution, but no more examples and explanations.
the progression at the bottom of the image, perfect 4th is come out in succession., but can I change the progression to A-D-F-B(vii24) -> G-E-G-C(I64) -> G-D-G-B(V) ?
or
can I change the progression to A-D-F-B(vii24) -> G-D-G-B(V) -> C-E-G-C(I) ?
Answer: The problem with the two progressions is that in the vii chords, the F (the chordal seventh) is expected to resolve down by step to E or Eb.
So the two progressions are "allowable", but awkward.
Comment: @guss2222 It seems we're often online around the same time.
Comment: the F (the chordal seventh) is expected to resolve down by step to E or Eb. <--you mean, are you talking about examples of images? And the fact that the process I made is awkward means that the example of an image is the most appropriate?
Comment: @guss2222 Correct. In your progressions, the F proceeds upwards to G; in the book's examples, the F moves downward, which is more typical. The upward movement is not forbidden, however.
Comment: i understand thank you. and It sounds silly, but my questions almost always seem to be answered by you.


For a django model, how can I get the django admin URL to add another, or list objects, etc.?

Question: As much as I love the django documentation, the section on bookmarklets in the admin is strangely vague.
My question is this:  If I'm in a view and I have a django model (or, in some cases, an actual object), how can I get to the relevant admin pages for that model (or object)?  If I have the object coconut_transportation.swallow.objects.all()[34], how can I jump right to the admin page to edit that particular swallow?
Likewise, how can I get the URL for the admin page to add another swallow?
Answer: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls
obj = coconut_transportation.swallow.objects.all()[34]

# list url
url = reverse("admin:coconut_transportation_swallow_changelist")

# change url
url = reverse("admin:coconut_transportation_swallow_change", args=[obj.id])

# add url
url = reverse("admin:coconut_transportation_swallow_add")

Comment: The changelist for a particular model instance is not the "list of objects"
Answer: You can retrieve this from the actual object instance, this worked for me:
from django.core import urlresolvers
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(object.__class__)
object_admin_url = django.core.urlresolvers.reverse("admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(object.pk,))

See this: http://djangosnippets.org/snippets/1916/
Comment: I like this, since it works for any object - nice :-)
Answer: You can actually retrieve the info without making a query to ContentTypes
Just add this to your model class:
def get_admin_url(self):
    return urlresolvers.reverse("admin:%s_%s_change" %
        (self._meta.app_label, self._meta.model_name), args=(self.pk,))

Comment: module_name VS model_name atually depends on Django version. See: https://code.djangoproject.com/ticket/19689
Comment: It's self._meta.model_name (not module_name). Other than that, great solution, thanks!


How do I check in a piece of of data is in a specific column of a dataset (python)?

Question: I have a two dimensional array, and want to check if a specific number is in a certain column.
For example, if I have something like
list = [[1, 2], [1, 3]]
I want it to tell me if there is a 3 in the first part of the list.
I tried to do
if 3 in list['Number"]:
where one of the columns in the dataset is the Number, but it just says "syntax error"
Comment: Why do you try to get list['Number']?
Comment: Welcome to stack overflow. Please [edit] your question to include a [mcve] with a sample of your input data and a reproducible amount of code. In this example, there is no "number" in the data provided, you mix single and double quotes, and your variable name `list` shadows the built-in `list` type
Comment: It may be `3 in list['Number'].values`. If you post a working example, we can try it out.
Answer:
row=0 means you want to search in the first row
target=3 is the target that you want search for
column=0 means you want to search in the first column (i make it as comment because you want to search in the whole first row)

i suggest you to check this it will help you to know more about what is row and column in array
arr = [[1, 2], [1, 3]]
row = 0
target = 3
# column = 0

if any(row[column] == target for row in arr):
    print(f"{target} found in column {column}")
else:
    print(f"{target} not found in column {column}")


pie chart shiny application using selectinput

Question: when i execute my code i have only the the siderbarPanel in my application,and when i choose the state nothing to show .
the probleme that i don't have any error in my code to correct in
My data :
total.death=c(48, 24, 12, 22)
total.recovred=c(12, 22, 78, 21)
total.cases=c(553, 226, 742, 370)
State=c ('USA', 'Belgium', 'France','Russia')
df2 = data.frame(State,total.cases,total.recovered,total.death)

My code:
library(shiny)
library(plotly)
library(RColorBrewer)
ui=fluidPage(

  selectInput("select", label = h3("Select box"),
              choices = df2$State,
              selected = 1),

  hr(),
  fluidRow(column(3, verbatimTextOutput("value"))),
  mainPanel(
    textOutput("text1"),

    plotOutput("mypie")

  ))

s=function(input, output) {

  output$text1 <- renderText({
    txt = as.character(input$select)
    paste("text is", txt)

  })
  output$mypie <- renderPlot(

    {labels=c("unrecovered","recovered","death")
    S=filter(df2,df2[1]==as.character(input$select) )
    S=c(S[2],S[3],S[4])

    plot_ly(labels = ~labels,
            values = ~S, type = 'pie',
            marker = list(colors = brewer.pal(7,"Spectral")))

    })

}

shinyApp(ui=ui,server = s)

Comment: I edit it, thank you
Answer: Try using plotlyOutput and renderPlotly. See below for working version. Minor modifications made to spelling, case-sensitive names, etc.
Edit: This includes S = unlist(S[-1]) for plotting as mentioned in comments.
total.death=c(48, 24, 12, 22)
total.recovered=c(12, 22, 78, 21)
total.cases=c(553, 226, 742, 370)
State=c ('USA', 'Belgium', 'France','Russia')
df2 = data.frame(State,total.cases,total.recovered,total.death)

library(shiny)
library(plotly)
library(RColorBrewer)

ui=fluidPage(
  selectInput("select", label = h3("Select box"),
              choices = df2$State,
              selected = 1),

  hr(),
  fluidRow(column(3, verbatimTextOutput("value"))),
  mainPanel(
    textOutput("text1"),
    plotlyOutput("mypie")
  )
)

s=function(input, output) {

  output$text1 <- renderText({
    txt = as.character(input$select)
    paste("text is", txt)
  })

  output$mypie <- renderPlotly({
    labels=c("unrecovered","recovered","death")
    S=filter(df2, df2$State==as.character(input$select))

    S = unlist(S[-1])

    plot_ly(labels = ~labels,
            values = ~S, type = 'pie',
            marker = list(colors = brewer.pal(7,"Spectral")))
  })

}

shinyApp(ui=ui,server = s)

Comment: i tried with plotlyOutput but in vain,plz see the code i edit it
Comment: now it show me the the pie chart, but in Rviewer,not in my applicartion shiny
Comment: i just add S = unlist(S[-1])
Comment: output$mypie <- renderPlot(

    {labels=c("unrecovered","recovered","death")
    S=filter(df2,df2[1]==as.character(input$select) )
    S=unlist(S[-1])

    plot_ly(labels = ~labels,
            values = ~S, type = 'pie',
            marker = list(colors = brewer.pal(7,"Spectral")))

    })
Comment: i delet S=c(S[1],S[2],S[3]) but i have same problem
Comment: you still have `renderPlot` _not_ `renderPlotly` (notice the "ly") - also make sure you use `plotlyOutput` _not_ `plotOutput`


Understanding behaviors

Question: I created a custom theme (a sub-theme of Radix base theme).
I am loading a custom Javascript file (radix_sub.script.js) using the module libraries.yaml file like below:
style:
  version: VERSION
  css:
    theme:
      assets/css/radix_sub.style.css: {}
  js:
    '//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js': { type: external }
    '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js': { type: external }
    assets/js/radix_sub.script.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once
    - core/drupalSettings

In that file, I want to register some JavaScript events (Bootstrap modal).
(function ($, Drupal) {

  Drupal.behaviors.portfolio = {

    attach: function (context) {

      console.log('CONTEXT', context);

      $('#portfolioModal', context).once('bootstrap-modal-shown', console.log('*** REGISTER SHOWN.BS.MODAL')).each(function () {
        $(this).on('shown.bs.modal', function () {
          console.log('SHOWN BS MODAL EVENT TRIGGERED');
        });
      });

      $('#portfolioModal', context).once('bootstrap-modal-hidden', console.log('*** REGISTER HIDDEN.BS.MODAL')).each(function () {
        $(this).on('hidden.bs.modal', function () {
          console.log('HIDDEN BS MODAL EVENT TRIGGERED');
        });
      });
    }
  }
}(jQuery, Drupal));

It works. I see both SHOWN BS MODAL EVENT TRIGGERED and HIDDEN BS MODAL EVENT TRIGGERED logs when I show/hide the modal.
First, am I doing that the correct way?
This is what my developer console looks like when I load my page.

This happens only when I am logged in (as admin). When I am anon, I see the REGISTER logs only once but here my code seems to be executed 11 times.
Is this normal behavior? And/or why is it doing that?
Comment: `Is this normal behavior?` prob not, can you replicate on fresh D8 install with Bartik theme?
Comment: It ended up being "normal behavior" considering where I placed my `console.log()`s. jQuery `once()` is called on page load and on any AJAX load. All the scripts that can be seen in the screenshot (`plainTextEditor.js`, `image.js`, `theme.js`, etc.) are loaded on the page via AJAX, hence the 10 subsequent logs after the initial page load. The code **within** the `jQuery.each()` callbacks is executed only once.
Answer: The answer lies here:
$('#portfolioModal', context).once('bootstrap-modal-shown', console.log('*** REGISTER SHOWN.BS.MODAL'))

The code that comes after the call to $.once() will only be executed once. However, $.once() can and will be executed multiple times. That's why you are seeing your calls to the console being called multiple times. If you change this:
$('#portfolioModal', context).once('bootstrap-modal-shown', console.log('*** REGISTER SHOWN.BS.MODAL')).each(function () {
  // Do some stuff.
});

To this:
$('#portfolioModal', context).once('bootstrap-modal-shown').each(function () {
  console.log('*** REGISTER SHOWN.BS.MODAL');
  // Do some stuff.
});

You will see that your call to the console is only shown a single time.
Note that you also will not use $.on() here, as the Drupal behaviors API replaces any necessity of it. Each time Drupal.behaviors are executed, a context argument is passed to it. This will be either the full DOM, or any HTML being newly inserted into the DOM. So where in normal jQuery you might do this:
$(".some_selector").on(someCallbackFunction);

In Drupal, you would do this:
Drupal.behaviors.someArbitraryKey = {
  attach: function(context) {
    $(context).find(".some_selector").once("some-arbitrary-key").each(someCallbackFunction);
  }
};

This is the Drupal way of achieving the same goals as using $.on() in normal jQuery, while tying in with the Drupal APIs.
---- Edit ----
Original answer below, which turned out to not answer the question. Left for posterity's sake, and because it actually adds on well to the end of the above answer.
Drupal behaviors are called on page load. It is also called upon AJAX load. You need to wrap code in $.once() if it should only be executed a single time:
function someElementListener(context) {
  // Call to $.once():
  $(context).find(".some_selector").once("arbitrary-key").each(function () {
    // Code here will only be executed a single time on
    // each .some_selector element found
    $(this).click(function() {alert("clicked");});
  });
}

Drupal.behaviors.someModule = {
  attach: function (context) {
    someElementListener(context);
  }
};

If you wrap your code in $.once(), your console calls will only be logged a single time.
Comment: he's already using `.once()`...
Comment: I think that's what I am doing already and now I am thinking the problem only comes from where I placed my `console.log()` (in the `once()` function) which is called every time, including on AJAX calls as you mentioned. What's inside the `each()` callback though isn't called more than once.
Comment: Actually you are doing that. sorry I missed it, but I also see the answer to your question. I'll update my original answer.
Comment: Yes, thank you, that cleared up my doubts and I can confirm it works as expected!

Understanding behaviors


GString pointer memory leak

Question: I am trying to free GString * using g_string_free, pointer was allocated using g_string_sized_new. But valgrind gives memory leak for same.
Example Code:
Ports * function(bs_t *bs)
{
    GString *string = g_string_sized_new(PATH_MAX);
    char template[] = "/tmp/grokXXXXXX";
    Ports *rc =NULL;

    if (condition) {
        rc = (Ports *) malloc (sizeof(Ports));
        if (rc == NULL) {
            g_string_free(string, TRUE);
            return NULL;
        }
    }

    if (condition_2) {
        if (!port_file(string->str, &rc->ports[0], &rc->port_valid,
            NUM_RC_PORTS))
        {
            g_free(rc);
            rc=NULL;
        }
    }
    g_string_free(string, TRUE);
    return rc;
}

Comment: What's the valgrind error message?
Answer: You are mixing calls to plain malloc with wrapped g_free,

 rc = (Ports *) malloc (sizeof(Ports));
    .
    .
    .
 g_free(rc);

Use plain or wrapped memory allocators consistently.
Comment: Your answer is not wrong (memory allocators and deallocators should always be used pairwise consistently), but since GLib 2.45.5, `g_malloc()` is equivalent to `malloc()` and `g_free()` is equivalent to `free()`, so that's probably not the problem here.

GString pointer memory leak


What hotfixes should be applied to a ColdFusion 8 Server

Question: I've recently inherited a server running ColdFusion 8 and believe it may not have been patched for security updates (as per http://www.adobe.com/support/security/#coldfusion) for quite some time.
The Coldfusion installation is 8.0.1 (8,0,1,195765), but I don't see any other information to see which patches have been installed from the 13 shown on the Adobe security page.
Is there a way I can tell which patches have been installed? If not, can I tell which we're included in 8.0.1 so I don't have to include these?
Additionally, it looks like some updates contain other older ones - can I get away with only installing the latest update (listed to fix APSB11-14) or do I need some others as well?
Answer: As Shane said "It'd be less effort to just re-apply all the patches." - true, and false. You will get all kinds of weird problems if you don't return your installation to an un-patched state first. The crappy thing about it is "there is no good and/or easy way to determine what patches are installed"
you will need to look at each patch, hotfix & cumulative update, read it's installation instructions & look for the files it tells you to replace & do a checksum on them to determine if they have been patched or not.
One or more of the cumulative updates has you update the CFIDE files as well, hopefully, the last admin kept the backup.
Adobe's advice on hotfixes is "if you are experiencing this problem ... then apply this patch" if not - don't, all security patches should be installed.
Good luck, I've been down this road myself & it really sucks trying to figure out what is/needs to be installed...
Is this a live/production machine? You may be further ahead reinstalling & patching from there
-sean
Answer: ColdFusion security updates usually take the form of "plop these newer files on top of the old versions" - to check, you'd probably need to do size or hash comparisons of the new/old versions of the files.
It'd be less effort to just re-apply all the patches.
Some of the updates will touch overlapping files, but only if that file needed to be updated multiple times - if a file's touched multiple times, then only apply the newer update, but they aren't necessarily aggregate.


Disproving continuity using epsilon delta

Question: Suppose I wanted to show that $\ln(x)$ is not uniformly continuous on $\mathbb{R}_{>0}$.
I know if I negate the definition of uniform continuity, that I have to find an $\varepsilon$  such that
$ \forall \delta > 0 \quad \exists x  $ :
$$ |x-y|<\delta \implies |f(x)-f(y)|\geq \varepsilon $$
Am I correct in saying I can choose epsilon without any restrictions? And for $x,y$ I have to make sure, that their absolute difference remains smaller than delta, for any $\delta$ chosen, now matter how small?
Would it then be correct to state that $\varepsilon:=\frac{\ln(2)}{2}$ and $x:= \delta $ and $y:= \frac{\delta}{2}$ work, but I couldn't for example choose $x:= e $ and $y:= 1$ ?
Comment: $\forall\,\delta>0, x_\delta := \delta/2, y_\delta := \delta$. $$|f(x)-f(y)| = |\ln(x) - \ln(y)| = |\ln(x/y)| = \ln2 = 2\varepsilon > \varepsilon$$
Answer: The definition of being uniformly continuous on $I\subseteq \mathbb{R}$ is
$$\forall \varepsilon > 0 \; \exists \delta > 0 \quad \forall x,y \in {I}, \; |x-y|<\delta \Rightarrow |f(x)-f(y)|<\varepsilon$$
So its negation is (remembering that "not $\forall$ = $\exists$") is
$$\exists \varepsilon > 0 \; \forall \delta > 0 \quad \exists x,y \in {I}, \; |x-y|<\delta \text { and } |f(x)-f(y)|>\varepsilon$$
So yes, you would be correct. Of course there are some $x$ and $y$ such that $|f(x)-f(y)|$ is still going to be less than $\varepsilon$, but you just need a pair for which it's not, and whose distance is less than $\delta$, to provide the counterexample.
Comment: Well, you can usually see where things go wrong by trying to prove that $f$ $\textit{is}$ uniformly continuous, like, in your example you would try to derive some inequality for $h$ from
$$ln(x+h)-ln(x) < \varepsilon$$
Comment: So as a kind of "strategy", you'd often try to construct some x and y so that they cancel out? As in, I try to construct something that makes $|f(x)-f(y)|$ greater than a certain value but still has the property of $|x-y|< \delta $ for all deltas and then choose epsilon accordingly?


How to delete multiple entries from a List without going out of range?

Question: I have a list of integers that contains a number of values (say, 200).
List<int> ExampleList;

And another list on integers that holds the indexes that need to be deleted from ExampleList. However, this list is not sorted.
List<int> RemoveFromExampleList;

If it were sorted, I would have run a reverse loop and deleted all the values like this:
for (int i = (RemoveFromExampleList.Count-1); i >=0; i--)
{
    ExampleList.RemoveAt(RemoveFromExampleList[i]);
}

Do I have to sort RemoveFromExampleList, or is there another way to prune the unnecessary values from ExampleList?
If I do have to sort, whats the easiest way to sort? Is there any inbuilt C# library/method to sort?
Answer: If RemoveFromExampleList is a list of indexes, you would have to sort it and work in descending order to delete based on those indexes. Doing it any other way would cause you to delete values you don't mean to delete.
Comment: Exactly. And Sorting is as easy as `RemoveFromExampleList.Sort();`. If you add a `.Reverse()` afterwards, you can `foreach` through the list.
Comment: thanks...this works! I feel silly for not knowing that List.Sort() exists...lol.
Answer: Here is the one liner.
ExampleList.RemoveAll(x => RemoveFromExampleList.Contains(ExampleList.IndexOf(x)));

Answer: You could replace the values you are going to remove with a sentinel value, i.e., one that you know doesn't occur in the list, and then remove all occurrences of that value.
Answer: Your option is to sort, yes. Sort the removal list in descending order and then remove by index that way.
// perform an orderby projection, remove
foreach (int index in RemoveFromExampleList.OrderByDescending(i => i)
    ExampleList.RemoveAt(index);

Or
// actually sort the list, then remove
RemoveFromExampleList.Sort((a,b) => b.CompareTo(a));
foreach (int index in RemoveFromExampleList)
    ExampleList.RemoveAt(index);

(Assumes there are no duplicates, use .Distinct() on the list/projection if otherwise.)
Answer: If you really had some aversion to sorting the list, you could make the list a list of nullable ints:
List<int?> ints;

Then you could nullify the values in the "delete list", and use the RemoveAll method to delete the null values.
But this is obviously a bit of a hack.
Answer: You could do it with LINQ / Lambda like so:
//EXAMPLE TO REMOVE ITEMS COMING FROM ANOTHER LIST
            List masterList = new List();
            masterList.Add(1);
            masterList.Add(1);
            masterList.Add(2);
            masterList.Add(3);
        List<int> itemsToRemove = new List<int>();
        itemsToRemove.Add(1);
        itemsToRemove.Add(2);
        itemsToRemove.Add(3);

        List<int> cleanList = new List<int>();
        foreach (int value in itemsToRemove)
        {
            masterList = masterList.Where(x => x != value).ToList();
        }


Scatter plots in ggplot2 with non linear trend line

Question: I'm trying to create a scatter plot using ggplot.  The x value goes roughly from 0-20, and the y value goes from 0-~50. The data is raw so it's not nice and neat and I need to plot a curved line through the majority of the data.
The code I'm trying to use is
ggplot(temperature, Number.of.Fish,aes(x=Temperature,y=Number.of.Fish))+geom_smooth

But I keep getting an error message: error in inherits (mapping, "uneval"), could not find function "Number.of.Fish"
Comment: This sort of question is best asked on the [ggplot2 mailing list](https://groups.google.com/forum/#!forum/ggplot2)
Comment: This question appears to be off-topic because it is only about software. If a *reproducible* example were provided it likely would be welcome on SO.
Answer: The correct code should be
ggplot(temperature,aes(x=Temperature,y=Number.of.Fish)) + geom_smooth()

You made two mistakes. First, the parenthesis () after geom_smooth and secondly, extra variable Number.of.Fish after the data frame temperature. Also, please always include a reproducible example when asking a question. This is what I did for you.
x <- 0:20
temperature <- data.frame(Temperature=x,Number.of.Fish = rnorm(mean=x, sd=2, n=21))
ggplot(temperature,aes(x=Temperature,y=Number.of.Fish)) + geom_smooth()

Comment: lengths of x and y have to be same. If for one x you have multiple y, you may replicate same value of x. for example `x <- c(1,1,1)` and `y <- c(20,32,45)` so both vectors have same lengths.
Comment: Thanks that really helps, but does it matter if x and y axis are unequal (number of fish 1:50, temperature 0:20.67)?


covariance matrix of residuals from a fitted model to decorrelate residuals

Question: I fit a geeglm model with clustered data and now I would like to decorrelate the residuals of the model in order to run model diagnostics.
I read that if I can obtain the covariance matrix of the residuals I can use the Cholesky decomposition to transform the residuals and thus decorrelate them.
How can I obtain this covariance matrix of residuals?
Furthermore, I understand that doing this involves a decent understanding of linear algebra in R. Can someone point me in the right direction on this topic?
Comment: If you want residuals from a correlated data analysis, fit a mixed model instead of a GEE.
Answer: The standard residual diagnostics of a linear model do not apply to GEE for several reasons. In this case, a strong rationale is needed to know what you actually need to do in this case.
With a standard linear model, you might plot residuals against fitted on the chance of catching either a) a mean model misspecification (real trend different from model) or b) heteroscedasticity (non-constant mean-variance relation). "Funnel shaped residuals" would indicate B and trending residuals indicate A. The point of a GEE is to use the linear model as a rule of thumb, so for instance if the trend is in fact curvilinear, the linear parameter estimates provide the "expected slope" of the response over a range of the predictor.
The GEE estimates the model parameters using a generalized least squares approach in addition to a sandwich variance estimator. More precisely, the estimating equation is given by:
$$ U(\beta) = D^T V^{-1} (Y - g^{-1}(X^T \beta)$$
Where $V$ is the working covariance matrix, and $D = \frac{\partial}{\partial \beta} g^{-1}(X^T \beta)$. The value of $\beta$ that provides a root to the above equation is the GEE estimate. The $A$ (bread) matrix is given by $A = \frac{\partial^2}{\partial^2 \beta} g^{-1}(X^T \beta)$ and the $B$ (meat) matrix $B = U(\beta)U(\beta)^T$. The sandwich variance estimate is $A^{-1}BA^{-1}$. This is also called the heteroscedasticity consistent variance estimate or "HC". Basically point B from the residual diagnostic exercise is completely deprecated with a robust enough sample (small sample performance of the sandwich is quite good, a number of 40 is often quoted). It turns out that model misspecification can conceptually be considered a form of heteroscedasticity. In each case, a misstep in the GEE specification should lead the standard errors to being exploded to accommodate the problem. In that regard, getting the model "right" only matters insofar as you can get the "optimal GEE" in which case $A=B$ and the covariance estimate is $A^{-1}$.
To inspect these issues, I suggest you fit the generalized least squares model, and obtain the Pearsonized residuals. With those you can perform a standard inspection of funnel and trend in the plot of Pearson residuals versus mean. But "optimality" is rarely a concern in its own right.
The advantage of a GEE is that you do not need assumptions related to residual diagnostics to apply to claim that the model is interpretable or valid.
Answer: Imitate the work of the VAR function of the vars package:
<code>set.seed(1)
mydataframe <- data.frame(rnorm(20),rnorm(20),rnorm(20))
names(mydataframe) <- c("x","y","z")
library(vars)
summary(VAR(mydataframe, p=1, type="none", ic="SC"))

VAR Estimation Results:
=========================
Endogenous variables: x, y, z
Deterministic variables: none
Sample size: 19
Log Likelihood: -67.515
Roots of the characteristic polynomial:
0.1872 0.1872 0.1821
Call:VAR(y = mydataframe, p = 1, type = "none", ic = "SC")

Estimation results for equation x:
==================================
x = x.l1 + y.l1 + z.l1

     Estimate Std. Error t value Pr(>|t|)
x.l1  -0.1373     0.2643  -0.520    0.610
y.l1  -0.1338     0.2810  -0.476    0.640
z.l1   0.1156     0.2996   0.386    0.705

Residual standard error: 0.9884 on 16 degrees of freedom
Multiple R-Squared: 0.03397,    Adjusted R-squared: -0.1472
F-statistic: 0.1876 on 3 and 16 DF,  p-value: 0.9033

Estimation results for equation y:
==================================
y = x.l1 + y.l1 + z.l1

     Estimate Std. Error t value Pr(>|t|)
x.l1   0.4457     0.2156   2.068   0.0552 .
y.l1   0.2092     0.2292   0.913   0.3749
z.l1  -0.2307     0.2444  -0.944   0.3591
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.8062 on 16 degrees of freedom
Multiple R-Squared: 0.2343, Adjusted R-squared: 0.09073
F-statistic: 1.632 on 3 and 16 DF,  p-value: 0.2215

Estimation results for equation z:
==================================
z = x.l1 + y.l1 + z.l1

     Estimate Std. Error t value Pr(>|t|)
x.l1 -0.15566    0.23065  -0.675    0.509
y.l1 -0.24029    0.24524  -0.980    0.342
z.l1 -0.01854    0.26147  -0.071    0.944

Residual standard error: 0.8626 on 16 degrees of freedom
Multiple R-Squared: 0.07097,    Adjusted R-squared: -0.1032
F-statistic: 0.4074 on 3 and 16 DF,  p-value: 0.7498

**Covariance matrix of residuals:**
         x        y       z
x  0.91256 -0.07276  0.2039
y -0.07276  0.64134 -0.1309
z  0.20389 -0.13087  0.7087

Correlation matrix of residuals:
         x        y       z
x  1.00000 -0.09511  0.2535
y -0.09511  1.00000 -0.1941
z  0.25353 -0.19411  1.0000
</code>
Comment: Could you explain in either English or mathematical notation what this code is supposed to be doing and how you interpret it?


Make number format?

Question: Make format of number:
For example:
if number = 204433
output = 204K
if number = 84243
output = 84'243
if number = 8000
output = 8000
if number = 400
output = 400
How to formatted number to that's format?
Comment: Well, use If's to do that. Maybe you want to put that in a function.
Answer: The number_format command can do what you are looking for.

string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )

You wrote:

if number = 84243
  output = 84'243

Example:
$in = 84243;
$out = number_format ( $in, 0, ".", "'");
// $out = "84'243"

Comment: That's not the whole requirement though.
Answer: I think you can try this
if(strlen($number) > 5) {
   echo substr($number,0,2).'K';
} elseif(strlen($number)) {
   echo numberformat($number,2,'.',"'"); // for example
} else {
   echo $number;
}

Make number format?


Finding the Client ID for a RadGrid inside a RadLightBoxItem tag in a RadLightBox

Question: I'm trying to fetch the ClientID for a RadGrid control from client side using JavaScript so that I'll be able to bind data to this from the client side.
The RadGrid is present within the RadLightBox and needs to be populated on a button click event. The markup for LightBox looks something like this.
<telerik:RadLightBox ID="RadLightBox1" runat="server">
    <Items>
        <telerik:RadLightBoxItem runat="server">
            <ItemTemplate>
                <telerik:RadGrid runat="server" ID="lightbox_radgrid" AutoGenerateColumns="false">
                    <MasterTableView>
                        <Columns>
                            <%-- Columns not shown here --%>
                        </Columns>
                    </MasterTableView>
                    <ClientSettings>
                        <ClientEvents OnCommand="window_radgrid_OnCommand" />
                    </ClientSettings>
                    <GroupingSettings CaseSensitive="false" ShowUnGroupButton="true" />
                </telerik:RadGrid>
            </ItemTemplate>
        </telerik:RadLightBoxItem>
    </Items>
</telerik:RadLightBox>

This is the partial Javascript Code that I have written. I am able to find upto the RadLIghtBoxItem element but unable to fetch the RadGrid and it's clientID. This method is to be executed on success of a call to a web service to return the data.
function onSucessCallThis(result, userContext, methodName) {
            var radWindow = $find('<%= lightbox.ClientID %>');
            var LightBoxItems = radWindow.get_items();
            console.log(LightBoxItems);
            console.log(LightBoxItems.get_count());
            var item = LightBoxItems.getItem(0);
            console.log(item); //Able to fetch LightBoxItem
            var radGrid = item.FindControl("lightbox_radgrid"); //Doesn't work
        }

I'm not sure if this is the right way to have a radGrid inside a radLightBox. There isn't many examples of this online.
Answer: I think it will be easier for you to use a RadWindow's ContentTemplate. Something like:
        <telerik:RadWindow ID="RadWindow1" runat="server" Modal="true">
            <ContentTemplate>
                <telerik:RadGrid ID="RadGrid1" runat="server"></telerik:RadGrid>
            </ContentTemplate>
        </telerik:RadWindow>

If you want to keep using a lightbox, review the Get Client-side Reference to a Control Object article. The gist is that you can easily loop through the DOM, for example:
        <telerik:RadLightBox ID="RadLightBox1" runat="server">
            <Items>
                <telerik:RadLightBoxItem runat="server">
                    <ItemTemplate>
                        <telerik:RadGrid CssClass="gridInLightbox" runat="server" ID="lightbox_radgrid" AutoGenerateColumns="false">

                        </telerik:RadGrid>
                    </ItemTemplate>
                </telerik:RadLightBoxItem>
            </Items>
        </telerik:RadLightBox>


c# WYSIWYG editor using webbrowser and richtextbox

Question: Im trying to hammer togehter a WYSIWYG-edit in c# following some examples from here and other place.
Im using a webbrowser for the design state of the editor, but i need to be able to switch to "html-view" so I used a rich textbox, and my tought was to just grab the content from the webbrowser and set it to the rtb, and the other way around.
It works fine until i try to put back the value from the rtb into the webbrowser, then i get a
"This document has changed, do you want to save the changes"-alert and after that the webbrowser wont accept new content.
Any idea what to do? Or any other way to handle the solution im after?
the code:
namespace EmailAdmin
{
    public partial class Form1 : Form
    {

    // global variables
    private IHTMLDocument2 doc;
    private int WYSIWYGviewState = 0;

    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // initiate web browser to design mode
        webBrowserWYSIWYG.DocumentText = "";
        doc = webBrowserWYSIWYG.Document.DomDocument as IHTMLDocument2;
        doc.designMode = "On";
    }

    private void linkSwitchWYSIWYGview_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        // determins viewstate
        // is design view
        if (WYSIWYGviewState == 0)
        {
            // set html view
            WYSIWYGviewState = 1;
            rtbWYSIWYG.Visible = true;

            // populates the texteditor with html
            rtbWYSIWYG.Text = webBrowserWYSIWYG.DocumentText;

            // change label text
            linkSwitchWYSIWYGview.Text = "View Design";

        }
        // is html view
        else if (WYSIWYGviewState == 1)
        {
            // set design view
            WYSIWYGviewState = 0;
            rtbWYSIWYG.Visible = false;

            // populates the designer with html
            webBrowserWYSIWYG.DocumentText = rtbWYSIWYG.Text;

            // change label text
            linkSwitchWYSIWYGview.Text = "View HTML";
        }
    }
}
}

Answer: It's a good thing for you that I've spent far too much time recently looking at how the WebBrowser control and related things work :-)
To do what you want, instead of
webBrowserWYSIWYG.DocumentText = rtbWYSIWYG.Text;

do
webBrowserWYSIWYG.Document.Write(rtbWYSIWYG.Text);

I hope that helps. It works for me.
Edit: Try this:
webBrowserWYSIWYG.Document.OpenNew(true);
webBrowserWYSIWYG.Document.Write(rtbWYSIWYG.Text);

Comment: @David Johnstone: Thanks, it worked! Still having the issue with that .Document.Write(); only adds, not replace, so if you start by writing "!" and switch back and forth between views, the document will grow with 1 "!" every switch. Any thoughts?
Comment: I solved it and was about to write about the: webBrowserWYSIWYG.Document.OpenNew(true); when I saw that you had updated the reply, thanks again David


move element to top when click each buttons

Question: I have list and each list has "move top" button.
when click "move top" button, div element shoul be move to top(in DOM).
But I am getting little trouble to make it.
Also when using keyboard tabbing to the button and press enter key, the focus has to be keep to the button, after press the keyboard enter.
This is what I tried so far here
Please help.

$('.btnTop').on('click', function() {
  $(this).parent().prepend(this).focus();
});
.box {
  border: 1px solid #000;
  margin: 0 0 20px 0;
}

    aa <button class="btnTop">Top</button>

    bb <button class="btnTop">Top</button>

    cc <button class="btnTop">Top</button>

Answer: You are prepending the wrong item. You need to prepend the parent div of the button, not the button itself. Also, you need to prepend to the .wrap div, which is the button's parent parent rather than to the button's parent which is just the div wrapping the button.
Lastly, you need to focus() on this (which is the button you clicked) to get the tab button working. At the moment you are not focusing on the button you clicked on.
See working example below:

$('.btnTop').on('click', function() {
  let this_div = $(this).parent();
  this_div.parent().prepend(this_div);
  $(this).focus();
});
.box {
  border: 1px solid #000;
  margin: 0 0 20px 0;
}

    aa <button class="btnTop">Top</button>

    bb <button class="btnTop">Top</button>

    cc <button class="btnTop">Top</button>


Matrix derivative of $\operatorname{tr}\theta^TX^TX{\theta}$

Question: This is a part of the derivation of the normal equation and I am struggling with this part.
I don't get how $\operatorname{tr}\theta^TX^TX{\theta}$ can become $2X^TX\theta$....
I know that the derivative of $\operatorname{tr}(ABA^TC)$ respect to $A$ is equal to $CAB + C^TAB^T$ and the lecturer seems that he wants me to use this to derive it, but I don't get how I should use it.
The picture is the part of the lecture note that I'm struggling with.
Comment: Have a look at https://math.stackexchange.com/help/notation and re-fromat your question accordingly.
Comment: Thanks for ur advice!
Comment: In your formula simply set $C=I_m, A=\theta^T, B=X^T X$. Use the fact that $B=B^T$. Make sure your formula is correct, however.
Answer: Let's rewrite it using the trace/Frobenius product notation (colon), i.e.
\begin{align}
F & = \theta^TX^TX\theta\\
\implies Tr(F)&= Tr((X\theta)^TX\theta) = X \theta:X\theta\\
\implies dF & = d(X \theta):X\theta + X\theta:d(X \theta) \\
 & = 2X\theta:d(X \theta)\\
 & = 2X\theta: (d(X) \theta + X d\theta)\\
 & = 2X\theta: X d\theta\\
 & = 2X^TX\theta: d\theta\\
\implies \frac{dF}{d\theta} &=2X^TX\theta
\end{align}
=========================================
NB: I used the following properties of the trace function:
$$Tr(A^TB) = A:B$$
$$Tr(AB) = Tr(BA)$$
$$A:BC=AC^T:B=B^TA:C$$
Answer: \begin{align}
& \frac d {d\theta} \operatorname{tr}(\theta^TX^TX\theta) \\[12pt]
= {} & \frac d {dA}\operatorname{tr}(ABA^TC) \\[4pt]
& \text{with $\theta^T$ in the role of } A, \\
& \text{$X^TX$ in the role of } B, \\
& \text{and } I \text{ in the role of } C \\[12pt]
= {} & CAB + C^TAB^T \quad \text{(This was given.)} \\[10pt]
= {} & \theta^T X^TX + \theta^T X^TX.{}
\end{align}
Here, $B$ and $C$ must be square matrices, and their sizes differ if $A$ is not a square matrix.


Limit point of a complex sequence

Question: maybe someone can give me some advice on how to show that?
Problem: Show that $y ∈ C$ is a limit point of $(y_{n})_{n∈N}$ (complex sequence) exactly when, for any $ε$ > 0, there are infinitely many sequence members in the $ε$-neighbourhood$$U_{ε}(y) := {x ∈ C | |x - y| < ε}$$ of y.
Thoughts on that: Then, for each $n$, there ist an $x$ different from $y$, which lies in the $\frac1n$ - neighbourhood of $y$. I have to choose such a one as $x_{n}$. Then the sequence of $x_{n}$ is a subsequence converging to $y$ subsequence of $y_{n}$. Am I on the right way?
Comment: Yes, you are on the right way.
Answer: A subsequence of $(y_n)$ is a sequence $(x_n) = (y_{\varphi(n)})$ where $\varphi : \mathbb N \to \mathbb N$ is strictly increasing. You have to adapt your argument a little bit to make sure this is the case of the sequence you are building.
Then, you also have to prove the converse statement : if $y$ is a limit point of $(y_n)$ then for any $\varepsilon >0,\ldots$

Limit point of a complex sequence


how to remove these errors ora-31640 and ora-39001,ora-39000 and ora-27041

Question:
i have only dump file so i cant recreate the another dump file.
how to solver these error?
Answer: In the image that you posted your current directory is C:\Users\Vattamwar, which is where it appears that the dump file is located. However, as shown in the ORA-31640 message, the IMPDP utility expects the dumpfile to be located in the directory D:\app\oracle\admin\xe\dpdump. I suggest that you move your dump file dream.dmp to the directory D:\app\oracle\admin\xe\dpdump.


Is it worthwhile to change your golf swing?

Question: Tiger Woods has made headlines for changing his golf swing multiple times in his professional career. As a pro, Woods has changed his golf swing three times under Butch Harmon, Hank Haney, and most recently Sean Foley.
Woods's pro statistics before each swing change:

June 1997, pro swing change No. 1. Tour events prior to change: 17.
  Wins: 5. Winning percentage: 29.4 percent. (Majors: 1. Wins: 1.
  Winning percentage: 100 percent.) World rank at time of swing change:
  2.
March 2004, swing change No. 2. Tour events since prior change: 132.
  Wins: 35. Winning percentage: 26.5 percent. (Majors: 27. Wins: 7.
  Winning percentage: 25.9 percent.) World rank at time of change: 1.
August 2010, swing change No. 3. Tour events since prior change: 91.
  Won: 31. Winning percentage: 34.1 percent. (Majors: 23. Wins: 6.
  Winning percentage: 26.1 percent.) World rank at time of change: 1.

Woods's experience of changing his swing is an exception. Other golfers, such as Padraig Harrington and Sir Nick Faldo, have not had an equitable level of success after changing their golf swing. In Faldo's case, it took several years for his swing change to click.
Is it worthwhile to change your golf swing? What are the reasons for changing your golf swing? What factors play into the "growing pains" associated with changing your golf swing?
Comment: meta discussion: http://meta.sports.stackexchange.com/questions/317/should-we-look-to-relax-too-subjective-to-generate-more-and-more-interesting-q
Comment: Are you asking if it is worth it for pros or if it is worth it for the average golfer or both?
Comment: @mikeazo take it as is. i would assume that it would immensely frustrate the average golfer, but assume no indication of either.
Answer: The purpose of modifying one's golf swing is to enhance specific playmaking qualities (i.e distance vs. accuracy) or to avoid stresses on certain parts of the body. It is no difference from a quarterback or pitcher changing their throwing motion.
We'll use Tiger Woods as an example.
Woods has always ranked among the top drivers on the PGA Tour. From 1997-2002, he placed in the Top 5 annually with an average drive around 295 yards. After Woods changed his swing the first time 2004, he increased his average drive by 10-20 yards.
When he settled into his swing, however, Woods' drives became more erratic. This is why he sought another swing change in 2010 -- to improve driving accuracy, which had dropped from a peak of 71 percent in the early 2000s to the 50s in the mid-to-late 2000s. Driving distance can be a great advantage, but it doesn't mean much if you frequently have to hit out of the rough.
And because Woods, who derives so much of his power from his lower body, has suffered a couple of knee and ankle injuries, some tweaks have probably been made to help prolong his playing career. (It isn't unusual for pros over the age of 50 continue to compete on the PGA Tour despite qualifying for the Champions Tour.)
Not every professional golfer works with a swing coach. Bubba Watson, 2012 Masters champion, prides himself on not having someone constantly analyzing his swing.
More often than not, swing coaches analyze a golfer's motion and make sure he's not deviating from what made him successful. For professionals, it may be honing in on something very specific -- tilting the club head, getting full torque out of the swing -- whereas for an amateur, its making sure they're performing proper fundamentals at the basic level.
Comment: Good answer. I would also attribute Woods's accuracy issues to switching from steel to graphite shafts...even though his accuracy did deteriorate before the switch. 60% in a season is good for him.


$n$ balls into $n+1$ urns (with one special urn)

Question: Assume that there are $n$ balls numbered from $1,2,\ldots,n$ and $n+1$ urns, numbered  as $0,1,\ldots,n$
Throw each ball randomly into one of $n$ urns: urn 1, urn 2, . . . , urn $n$. That is, any urn except urn $0$. (A ball goes to a certain urn with probability $1/n$) Check each urn and if there are more than one ball in an urn, choose one randomly and keep that in that urn and remove the other balls and put them into urn $0$.
What is the probability that there are $k$ balls in urn 0?
Comment: This is a great question that deserves an upvote. With that in mind...what have you tried?
Comment: Well, I tried first finding the probability of having $m$ empty urns- which is to do with Stirling numbers of the second kind. There is no ball to remove from those. The question then what is the probability of having $s$ urns that have more than 1 ball given that there are $n-m$ nonempty urns. That is the hard part and where I got stuck.
Comment: But if you know the number of empty urns, don't you already know $k$?
Comment: When you say "choose one randomly", do you mean one ball or one urn?  (My guess is probably the former.)
Answer: Hints/Guiding questions:

How many balls are not in urn $0$?
How many of the urns $1$ up to $n$ had balls in them before moving balls to urn $0$?
What is the probability of such a configuration occurring?
Answer: The number of balls in urn $0$ at the end is simply the number of urns numbered $1$ through $n$ that received no ball during the ball-tossing stage. Let $K$ be a set of $k$ of the urns numbered $1$ through $n$; a distribution of the balls that leaves exactly the urns in $K$ empty is a partition of the $n$ balls into $n-k$ parts. There are $n\brace{n-k}$ such unordered partitions, but the urns are numbered, so there are actually $(n-k)!{n\brace{n-k}}$ distributions leaving exactly the urns in $K$ empty. (Here $n\brace{n-k}$ is a Stirling number of the second kind.) Thus, there are
$$\binom{n}k(n-k)!{n\brace{n-k}}=\binom{n}k\sum_{i=0}^{n-k}(-1)^{n-k-i}\binom{n-k}ii^n$$
distributions that result in $k$ balls in urn $0$. Since there are $n^n$ equiprobable distributions, the probability $p_k$ of ending up with $k$ balls in urn $0$ is
$$p_k=\frac1{n^n}\binom{n}k(n-k)!{n\brace{n-k}}=\binom{n}k\sum_{i=0}^{n-k}(-1)^{n-k-i}\binom{n-k}i\left(\frac{i}n\right)^n\;.$$
Answer: Denote by $q_r(j)$ the probability that after $r\geq0$ throws exactly $j\geq0$ urns are occupied. Then $p_0(j)=\delta_{0j}$ and
$$q_r(j)={j\over n} q_{r-1}(j)+{n-(j-1)\over n}q_{r-1}(j-1)\qquad(r\geq1)\ .$$
Let $f_r(j):=n^r q_r(j)$; then
$$f_r(j)=j f_{r-1}(j)+\bigl(n-(j-1)\bigr)f_{r-1}(j-1)\ .$$
Note that $r$ does not appear in the coefficients of this recursion. It is then easy to see that in fact
$$f_r(j)=c_{r,j}\prod_{i=0}^{j-1} (n-i)$$
for  constants $c_{r,j}$ that satisfy the recursion
$$c_{r,j}=j c_{r-1,j} + c_{r-1,j-1}\ .$$
Now this is the recursion formula for the Stirling numbers of the second kind, denoted by $S(r,j)$ in Stanley's Enumerative combinatorics, vol. I. One easily checks that in fact $c_{r,j}=S(r,j)$. Therefore we obtain
$$q_r(j)={1\over n^r} S(r,j)\prod_{i=0}^{j-1}(n-i)\ .$$
At the end the number of balls in ${\rm urn}_0$ is equal to the number of unoccupied urns among ${\rm urn}_1,\ldots,{\rm urn}_n$. The probability $p(k)$ that this number is $k$ is then given by
$$p(k)=q_n(n-k)={n!\ S(n,n-k)\over k!\ n^n}\ .$$
Answer: The problem you need to solve is not how many urns have more than one ball - if you have 12 urns, 11 balls, and 7 urns have balls in them, you're going to be putting 4 balls into urn 0 no matter what the count of the balls in each urn is.
You simply need to calculate sum of the probability that, for each thrown ball, whether it falls into an urn that already has a ball in it. The first ball is obviously probability $0$, and subsequent balls are $\frac{k}{n}$, where $k$ is the number of urns with balls in them. For the second ball, $k=1$ and for the third ball, $k=1+1-\frac{1}{n}$.
The wording of the question makes it seem much more complicated than it is. This is pretty much the birthday problem with an arbitrary number of months and people in the room - if two people share a birth month, one of them leaves the room (and gets put into an urn - yikes).


Is every sigma algebra generated by some subclass.

Question: Let $\Omega$ a non empty set and consider and $\cal{A}$ a sigma algebra in  $\Omega$. Is there always a set $\cal{C}\subset\mathscr{P}(\Omega)$, $\cal{C}$ strictly contained in  $\cal{A}$  such that
$\cal{A}$ is generated by $\cal{C}?$
For example, is the Lebesgue measure generated by some $\cal{C}?$
Obs.
https://mathoverflow.net/questions/87838/is-every-sigma-algebra-the-borel-algebra-of-a-topology
I have already seen the discussion in the above link, but I'm not asking noting special about the class  $\cal{C}$.
Also in the above case the answer is quite sophisticated. I'm wondering if in the question I ask the answer is more simple.
Comment: You had better put some condition on $\mathcal C$, otherwise just take $\mathcal A = \mathcal C$.
Comment: Thanks for the warning. When I ask the question I have the condition ${\cal C}$ strictly contained in ${\cal A}$ in mind
Answer: If you take $\mathcal{C}=\mathcal A$, then you'll have a set that generates $\mathcal A$. If you want a smaller set, take $\mathcal{C}=\mathcal{A}\setminus\{\emptyset\}$.


Set ntfs permissions so that a file can be read, but no browsing of the directory

Question: OK folks, I don't think this is possible, but:
Got a client who needs to allow domain users to read files in a directory.
The catch is, he does NOT want them to BROWSE the directory.
basically, they know a filename and a location, so they can open it directly. ( assume they will be pasting the entire path\filename into the file / open  dialog.
Is there any way to do this?
Additionally, they should not be able to see directory structure although this might be OK.
My feeling is to put all these files behind an application front-end, give permissions to the (web) app, and remove all direct domain user access to the files.  Utilize app security.
Other method suggestions are welcome.
I do not have full details of the application arch, but since it is all file based, I feel that a front-end needs to be written to handle this.  ( Note that I'm an application guy, not an admin.  I only play an admin on tv.....  I do know enough admin stuff to be extraordinarily dangerous, so no need to be TOO simplistic  )
Comment: Lots of good answers here.  Thank you all so far.  I've been busy over the weekend and will be looking into the answers given more over the next couple of days.
Comment: Something more to add to this.  As currently requested by the client, he wants EVERYONE to have read permission for all files.  He just does not want them to be able to browse and see ALL the file names.
Comment: Yes, this is bad as if the "filename" gets out to other customers, they have access.  I'm marking the ABE answer correct as that will allow me to create groups for each of his clients, adding permissions as needed for the group/files, and add users to the group.  Even if they guess a filename, they still won't be able to open it.  As a bonus with ABE, they won't even be able to see the other file names.  Not very scaleable, but this will do very nicely for now.
Answer: The problem with your setup (assuming I understand it correctly as "have all files in a single directory") is that a clever client can guess the filenames of other people, and gain access to their data, so it doesn't matter that they can't browse, it only matters that they can pick up any file by name, and that means other client's files.
In other words, obscurity does not imply security, only that it is out of sight, out of mind.  Someone with a little imagination will come along and see right through that.
I'd re-think the approach, and possibly isolate each client to a subdirectory that only they have permissions to.  You would then be able to isolate the client to that location only by sharing the client's specific directory level upwards...and they could browse all they want, because there is nothing else to see.  When they connect/log in, they only get access rights to "their directory"...it won't matter that there are other directories because they don't get access to them (lacking the correct privileges).
Comment: I wholeheartedly concur.
Comment: I disagree. My assumption is that the OP will have the appropriate NTFS permission set on the contents of the directory so users will not be able to access files that they don't have explicit NTFS permissions on. I don't see this as security by obscurity. This scenario is exactly why ABE was created. The pointy haired boss' desire to hide the contents probably has nothing to do with security and everything to do with confidentiallity. Of course I'm assuming that the OP means that he needs to grant specific users access to specific files and not grant Domain Users access to all files.
Comment: The problem is that it's not entirely clear why it is being done.  You could set ACLs on a per-file basis, but that still doesn't stop the directory browse situation, only the data access.  If it's a function of "hide our other clients from the client making the connection" then you're better served by segregating the data.  Otherwise, it's plain goofy at best and smart clients will see it for what it is.  If it's a function of "give data to the correct client" then it still doesn't make sense to lump data into a giant bucket, just give every client their directory and control it that way.
Comment: I'm going to make the client have subdirs for each customer, with random folder naming, and still have an AD Group for each client.  Even if they guess, they won't get into the files.
Comment: One of the items that I didn't mention, because I have not yet dragged the reason out of the client, is that apparently he has a bunch of "data" files.  He wants to give out filenames, but not let them browse for files which they have not paid for.  It sounds like a case of a terrible architecture, but I don't yet know the full story.  I'll add more comments as I know more.
Answer: This should be fairly easy. Enable ABE (access based enumeration) on the share and make sure that you set the NTFS permissions correctly on the files and folders within the share.
http://technet.microsoft.com/en-us/library/dd772681(WS.10).aspx
Alternately, the Bypass traverse checking user right grants the Everyone group (by default) the ability to taverse folders that they don't have NTFS permissions on in order to get to files that they do have NTFS permissions on. Here's what to do:

Grant the Everyone group Change and Read permissions on the Share.
Set the appropriate NTFS permissions on the folders and files within the share.

A user may then access the files directly via
<code>\\servername\sharename\foldername\filename
</code>
As long as you have the Share and NTFS permissions set correctly the users will be able to access the appropriate files without being able to browse the contents of the share.
Comment: bump +1 for direct answer, even if I disagree with it ;-)
Comment: Thanks much. We may not agree but I respect your position just the same.
Answer: Sharing a specific directory (and no higher) in Windows is as simple as right-clicking the folder you want, clicking "Share", and adding users.
When they want to access it, they will use the UNC path \\server.domain.local\name_of_shared_folder
That's it!*
*Please make sure DNS is set up correctly. Double-check the firewall too.
Comment: This does not actually answer the question.
Comment: Yeah, definitely not. Did you bother to read the entire question?
Comment: I guess I missed something. Should I retire this answer?
Comment: Actually, I could create a share at the appropriate depth, and then restrict the browse ability in ntfs.  This is a solution that I had not even thought of, so it's actually not that far off base Joel.  Please do leave it.  It's forcing me to think out of the box somewhat.  With this answer, I don't have to fool with traversing rights, and not allowing users to see branches of a tree.


How would I go about predicting the survival probability or regress the survival date/time of an entity in a dataset?

Question: I have a longitudinal dataset comprising of physicians and their time independent covariates (age group, physician type, etc) and time dependent covariates (number of patients, hours worked, etc). I have several entries for each physician where the time-dependent covariates change from month to month (I have monthly intervals). This data is formatted in count process format.
I want to predict the risk/survival of a physician leaving. I am unsure how to do this because:
COXPH can handle the time-dependent covariates and does model the effect of the variables on the hazard but can't predict the survival out of the observation window.
Classical machine learning can predict/regress a physician leaving but may not model the time aspect very well (treats each sample as an independent sample, no relation to group of samples for a physician)
I am wondering if these approaches are correct?

Would it be possible to extract the hazard from the coxph (or predict partial hazard) and keep this hazard constant until the survival probability reaches 0?

Could I train a classical model such as xgboost or random forest to predict if a physician is going to leave before x months and include rolling averages on the time-dependent covariates to relate the different observation within a physicians group of observations?
EDIT: The input to this classical ML model would be my all my features (time-independent + time-dependent) and the output is physician did not leave/left ([0,1]). This Binary output is generated from doing term_date-study_start_date < num_days. This num of days could be 6 months. Meaning if at some point a person leaves we categorize this persons last 6 months as 1 (left) and this is what we are trying to predict. I am proposing to compute rolling averages for each of the time varying covariates and adding these averages as a new feature in the dataset.

Another approach is to do the same as 2 but instead regress the term date. I can convert the term_date into days since beginning of study and regress this. I can then use this model to predict when they will leave and threshold on this. I think this would be a great feat but it may be difficult to do.

Essentially I would like to be able to predict either when a physician will leave (survival curve is ok here or a regressed value) or if they leave before a certain time interval for physicians that include time varying covariates. The above are some approaches I have thought about but I am not 100% sure if they are the correct way. How can I accomplish this?
Comment: Please edit your question to say more about approach 2. Are you talking about a tree/boosted survival model based on time-fixed covariates, or a binary-outcome model after some period of time? If the latter, are you proposing to use the rolling-average time-varying covariates in building the model somehow, or just in generating predictions from it? Please edit the question to provide that information, as comments are easily overlooked and can get deleted.
Comment: Hi @EdM I have edited the question and added more detail. Thank you
Answer: As Therneau and Grambsch put it (page 272):

Survival curves based on a time-dependent covariate must be used with extreme caution.

My answer here covers many of the general problems in working with models based on time-varying covariates and making predictions from them. The warnings about potentially violating causality and modeling a covariate that changes suddenly and represents the "last straw" in a decision to leave seem particularly applicable here.
With respect to your questions:

Would it be possible to extract the hazard from the coxph (or predict partial hazard) and keep this hazard constant [beyond the observed survival window] until the survival probability is 0?

In a Cox model the hazard is identically 0 except at event times observed in the original data. So, no. You could consider extrapolation to later times with a parametric survival model, but predictions beyond the range of observations is always risky.

Could I train a classical model such as xgboost or random forest to predict if a physician is going to leave before x months ...

Old fogies like me don't think of xgboost or random forests as "classical" models, but this could be done with standard binomial regressions, too. The trick would be how to incorporate the time-varying covariates properly into a model that works with a fixed time window. I'm not sure how to do that.
You could, however, put a short time window together with a survival model incorporating time-varying covariates, as you seem to be interested in relatively short-term decisions to leave. That would move away from the individual-specific time origin, implicit in the survival modeling of your first question, and go to a panel-data approach with a fixed study start date as time = 0 for all individuals then employed, as in your second question. You then include things like prior length of service at study start as covariates in a survival model restricted to a reasonably short period (say, for just a few years) after the common study start date. That would avoid the difficulties of trying to extrapolate to long individual survival times that led in part to your question.
My answer here outlines such an approach, based on a thesis that modeled customer churn in the insurance industry (pretty similar in concept to your situation). The modeling in that thesis allowed for time-varying covariates. What you would be modeling is something different from the individual-survival analysis often done in clinical studies but might be more directly applicable to your business needs.

Another approach is to do the same as 2 but instead regress the term date.

The problem with this approach is that you omit the cases whose "term date" hasn't been reached. That introduces bias. Survival analysis is needed to help avoid that bias in regressions of times-to-events when some events, even if inevitable, haven't occurred during the study.
A final warning: using pre-Covid data on clinician turnover to model behavior either during the current pandemic or in a hoped-for thereafter seems to be pretty risky. Proceed "with extreme caution" on that account, too.


Distribution of text by word count in Spark Java

Question: I am new to Spark, sorry if this question seem to easy for you. I'm trying to come up with the Spark-like solution, but can't figure out the way to do it.
My DataSet looks like following:
<code>+----------------------+
|input                 |
+----------------------+
|debt ceiling          |
|declaration of tax    |
|decryption            |
|sweats                |
|ladder                |
|definite integral     |
</code>
I need to calculate distribution of Rows by length, e.g:
1st option:

500 rows contain 1 and more words
120 rows contain 2 and more words
70 rows contain 2 and more words

2nd option:

300 rows contain 1 word
250 rows contain 2 words
220 rows contain 3 words
270 rows contain 4 and more words

Is there a possible solution using Java Spark functions?
All I can think of, is writing some kind of UDF, that would have a broadcasted counter, but I'm likely missing something, since there should be a better way to do this in spark.
Comment: Hi. Welcome to Stackoverflow. This has a makings of a good question. Can you incdue some of the code you have tried so far, and explain where you are stuck?
Answer: Welcome to SO!
Here is a solution in Scala you can easily adapt to Java.
<code>val df = spark.createDataset(Seq(
  "debt ceiling", "declaration of tax", "decryption", "sweats"
)).toDF("input")

df.select(size(split('input, "\\s+")).as("words"))
  .groupBy('words)
  .count
  .orderBy('words)
  .show
</code>
This produces
<code>+-----+-----+
|words|count|
+-----+-----+
|    1|    2|
|    2|    1|
|    3|    1|
+-----+-----+
</code>


Net Screen manager setup

Question: I'm having an issue with our NSMExpress box.  I'm trying to manage all our devices, range from ns5gt to ssg320m, and some of those devices have addresses assigned by dhcp from the ISP (like pppoe or dsl).  The addresses are actually static but we have the register the MAC address in order to get this address.  I can actually add the device in NSM except the IP that's on the untrust side isn't imported in as it's dynamic.  Because of this I cannot change many options that pertian to the untrust interface as there is no IP.
I've talked to JTAC on this and they didn't know if there was a way to do this or not but then they stated that Tim Hortons does this so I'm confused on how to get this working.  Maybe i'm just missing something as I imagine that other people must be doing this as well.  Any assistance is appreciated!
Furthermore when I import a device this is the message I get:
Warnings:
Interface ethernet0/0 is a pppoe/dhcp/pppoa client and its ip is NOT IMPORTED because it may be dynamic.
Answer: First I would escalate your case to get an answer on your possible solution.
Second, it would be nice to know your version of NSM and the schema you are using. If these are older versions then this may be a limiting factor. A lot of times things like this slide in under a new release or schema update, but there is no guarantee. While a new version of both can expose some nice new functionality this should be well considered before making an upgrade depending on your environment. Basically the more complicated features you are using on NSM and on the device side could alter the experience for better or worse if there are many devices and if this NSM instance is a very important and heavily used production deployment.
Comment: Thank you for the reply.  I've actually been through the whole JTAC and they say there is no solution which I can't believe since other people must have the same situation as I do.

The version of NSM that we are running is 2009.1r1 and schema is 124.  I see that 2010.1 is out now but doesn't appear to address the issue either.  I have updated it along the way according to JTAC but again no fix.
I'll try the 2010 release to see what happens.
Comment: Codezy, keep escalating on it and don't close the case until you get an answer as to whether this is supported or not. This should get you an answer to this either way.

Net Screen manager setup


Determine which of these sets is a lattice

Question: I'm currently reading Dugundji's Topology's book. Exercise 4 in chapter 2 says (omitting a part that is irrelevant to the question)

A partially order set is a lattice if each pair of its elements has a least upper bound and a greatest lower bound. Is $(P(X),\subseteq)$ a lattice? In $P(A\times A),\subseteq)$, is the set of all transitive relations a lattice? Determine also if the set of all partial orders, preorders, and well orders are each lattices.

This is what I got. $P(X)$ is clearly a lattice cause the supremum of $A$ and $B$ is clearly $A\cup B$ and the infimum is $A\cap B$. The set of all transitive relations is a lattice cause given two relations $R$, $S$, the relation $T=\bigcap\{Q:R\cup S\subseteq Q \text{ and Q is a transitive relation}\}$ is a transitive relation that is also the supremum of $A$ and $B$ (note also that this intersection is non-empty cause $A\times A$ is transitive). The same trick works for preorders. I'm struggling with partial orders and well orders, the problem is that $A\times A$ is not in general a partial order (let alone a well order) so I cannot prove that the intersection is nonempty. For the infimum one can always take the intersection $R\cap S$.
Comment: I just realized that, edited.
Answer: Hint for partial orders and well orders: Consider concretely $A=\{1,2\}$ and the orders $<$ and $>$. Do they have a common upper bound at all (let alone a least upper bound)?


C++ what does the error of "Initial value of reference to a non-const must be an lvalue" mean in this case?

Question: I am a complete beginner to C++ and was assigned to write a function that returns the factors of a number. Below, I have included the function I also created called print_vector that will print all of the elements of a vector to the Console.
In my assignment, in order to check if the factorize function is working, we have to use the test_factorize function provided, which I have also included. However, the issue I've run in to is that the given test_factorize does not work due to the error "Initial value of reference to a non-const must be an lvalue." I'm unsure what this means and why the test_factorize runs into an issue because the output of factorize is a vector and the input of print_vector is also a vector, so I don't see why the contents of test_factorize result in an error, though I suspect it might be something within the `factorize' function I defined that causes this error.
#include <iostream>
#include <vector>

using namespace std;

void print_vector(std::vector<int>& v) {
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
    cout << endl;
}

std::vector<int> factorize(int n) {
    std::vector<int> answer;
    for (int i = 1;i < n + 1; ++i) {
        if (n % i == 0) {
            answer.push_back(i);
        }
    }
    return answer;
}

void test_factorize() {
print_vector(factorize(2));
print_vector(factorize(72));
print_vector(factorize(196));
}

Comment: hi! This is one of the cases where `using namespace std;` is not a good idea; instead, `using std::cout;` would be much less confusing, potentially. (You'll have to use `cout << std::endl;` instead of just `cout << endl;`, that's the only change). `using` the whole `std::` namespace imports *a lot* of symbols. For example, there might be a `factorize` already in `std`! That's why people [will tell you](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) not to do `using namespace std;`.
Comment: Also, you seem to be learning an old version of C++. Since '11, your `for(int i = 0; i < v.size(); i++) cout << v[i];` could be replaced with the much cleaner `for(int val : v) cout << val;`.
Comment: Thank you for the suggestion about namespace, I will definitely change that. As for the older version, I guess I am, I've only ever seen the old style syntax in my lectures.
Answer: The error is from this line:
void print_vector(std::vector<int>& v) {

Since you didn't include the const keyword in the argument-type, you are (implicitly) indicating that print_vector has the right to modify the contents of v.
However, you are calling print_vector() with a temporary object (the vector returned by factorize()) as an argument, and C++ doesn't allow you to pass a temporary object by non-const reference, presumably on the theory that making changes to a temporary object is pointless (because the temporary is going to be destroyed as soon as the function call returns, so any changes made to it would have no effect) and therefore must a programmer error.
In any case, the fix is easy, just change your function declaration to this:
void print_vector(const std::vector<int>& v) {

... and that will allow you to pass a reference-to-a-temporary-vector to it.


Make mic sound stronger

Question: I don't know if it's because I plugged my mic directly into my keyboard but i wanted to ask...
I bought a yamaha dgx 660 keyboard  Yamaha DGX-660 Digital Piano -... https://www.amazon.com/dp/B01DCA1CJM?ref=ppx_pop_mob_ap_share to learn to play the piano. I liked it and noticed it had an input for a mic and that got me thinking about singing. So i bought a shure sm58 lc mic Shure SM58-LC Cardioid Dynamic... https://www.amazon.com/dp/B000CZ0R42?ref=ppx_pop_mob_ap_share and needed an xlr3f to 1/4" converter to convert the cable so that I could plug it into my keyboard:  Hosa PXF-110 XLR3F to 1/4" TS... https://www.amazon.com/dp/B000068NYN?ref=ppx_pop_mob_ap_share.
This setup allowed me to attach my mic to my keyboard and have the sound come out of the keyboard speakers. Cool it works, however my experience is I can barely hear my voice. Its only until my mouth is very very close to the mic that the sound gets better. I have checked settings and volume control and all are fine. So my question.
On a typical setup where do people plug mics into. Is there some interface or simply an app that would get my voice louder rather than putting my mouth so close to the mic. I spent a lot of money on the mic it was around a hundred bucks and the keyboard is real nice too. What is the typical setup for plugging a mic for singing?  Can someone please explain a better setup that is not too expensive that would get my voice to sound better in terms of not having to be directly in front of mic?
Comment: Yes. It's the right microphone for the job, but it needs to be pointed straight at you, and quite close (depending on how loudly you sing).
Comment: That's the nature of a dynamic vocal mic; you hold it close to your mouth, and it captures your singing but not any other sounds. If you used a condenser mic like in recording studios, you could have it further away from you, but it would also pick up the sound from the speakers, and you'd get audio feedback (unless you used headphones instead of the speakers).
Comment: @YourUncleBob so this is quite normal setup?
Comment: @JonH- I had to delete my answer when I found out the Audio Master I described had been modified to accomplish the desired results. My sincere apologies.
Answer: I haven't read the manual for the Yamaha, but since the mic input is 1/4" it is most likely that you have an impedance mismatch that is lowering the signal from your microphone.
Microphones that use the three pin XLR connector are often built differently than microphones that go directly to 1/4". Using an adapter or XLR - 1/4" cable on a microphone designed to go XLR to XLR will result in a lower level.
To get a better sound and to be able to move the microphone away from your mouth and still get good signal will require you to pre-amp  the microphone.  There are many solutions for pre-amping a microphone and an internet search will give you a number of options in different prices. A small mini-mixer or dedicated microphone preamp is probably your best solution.
You can also find a microphone transformer, which will match your XLR mic to the 1/4" input. In my experience just using the transformer to match the impedance does not give you good control of the mic sound quality and level, but it is usually the cheaper option.
I can't give you any specific product recommendations, but here are some examples of the product types that I am referencing:
Microphone preamp
Matching Transformer
Mini Mixer
Here is some more information on the transformer:
https://www.shure.com/en-US/support/find-an-answer/transformers-when-to-use-and-how-does-it-work
Comment: So the cable I bought, would I be replacing that with a "Matching Transformer" from what you linked above ?  That means I'd go from the mic end that has the 3 plugs into this new transformer and then into my keyboard and this would get me better sound ?
Comment: Looks like the cable I bought was wrong, looks like based on your info I need two new things, one is the shure A85F transformer found here: https://www.amazon.com/Shure-A85F-Transformer-Female-4-Inch/dp/B0006NMUHW/ref=sr_1_3?keywords=A85F&qid=1561653432&s=gateway&sr=8-3 and another now is to replace my cable with male female as shown here: https://www.amazon.com/dp/B01JNLUA5G/ref=psdc_11973421_t1_B000VJJQUU  This new cable will plug into my mic directly and then the transformer needs to plug into this cable and then the transformer to my keyboard, correct?
Comment: yes, the XLR to XLR cable is the correct one for that type of mic and will let you use it in other situations. The matching transformer will help with the sound quality going into the keyboard, but for best sound and control you should look into getting a preamp for the mic, either stand alone or in a mixer. Some preamps and mixers are available in the $40.00 range, putting them close to the cost of the transformer.
Comment: Can you help me understand that some more and show me a decent one on say amazon or on shures site?
Comment: https://music.stackexchange.com/questions/81502/purpose-of-xlr-mono-jack-cable
Comment: Unfortunately the subject is  bigger than the comments section. You'll have to look up microphone impedance.  Here is an example of a cheap preamp: https://www.amazon.com/Behringer-MIC100-BEHRINGER-TUBE-ULTRAGAIN/dp/B000CZ0RME  Mic Cables - https://music.stackexchange.com/questions/81502/purpose-of-xlr-mono-jack-cable .    A mini-mixer can have a mic preamp built in and also allow mixing in other signals.

Make mic sound stronger


Como capturar as cores de um Label que está atrás de outro label?

Question: Eu tenho dois JLabels sobrepostos um ao outro.
JLabel label = new JLabel();
label.setBounds(15, 15, 300, 300);
label.setOpaque(true);
label.setBackground(Color.red);

JLabel label1 = new JLabel();
label1.setBounds(60, 60, 300, 300);
label1.setOpaque(true);
label1.setBackground(new Color(0,0,0,125));

O "label" está abaixo do "label1" e ambos estão inseridos em um GlassPane:
layeredPane.add(label, 0, 0);
layeredPane.add(label1, 1, 0);

o GlassPane está perfeito dentro do frame
frame.setGlassPane(layeredPane);
layeredPane.setVisible(true);
frame.setVisible(true);

Apenas para o "label" (o que está abaixo do "label1") eu criei um evento no mouse e quando eu passar o mouse sobre este label eu quero que ele retorne o valor RGB da sua cor.
ml = new MouseMotionAdapter() {public void mouseMoved(MouseEvent evt) {

      Point point = evt.getLocationOnScreen();

      Color color = robot.getPixelColor((int)point.getX(),(int)point.getY());
      System.out.println(color);
      }

};

Como eu não quero que ele traga nenhum retorno do label1, eu inclui:
 label1.removeMouseMotionListener(ml);
 label.addMouseMotionListener(ml);

O código funciona normalmente no que se refere a área dos labels. Mas o mouse ainda retorna o RGB das cores do label1 sobre o label, quando de fato eu quero  que o mouse retorne apenas o valor RGB para a cor do "label" que está abaixo do "label1".
segue o código completo
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;

public class Main extends JFrame {

public static void main(String[] args) throws AWTException
{
    JFrame frame;
    Robot robot;
    JLayeredPane layeredPane;
    MouseMotionListener ml;

    robot = new Robot();
    frame = new JFrame("Pc");
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    layeredPane = new JLayeredPane();
    layeredPane.setPreferredSize(new Dimension(300, 310));
    layeredPane.setBorder(BorderFactory.createTitledBorder(
                                "Move the Mouse to Move Duke"));
    JLabel label = new JLabel();
    label.setBounds(15, 15, 300, 300);
    label.setOpaque(true);
    label.setBackground(Color.red);

    JLabel label1 = new JLabel();
    label1.setBounds(60, 60, 300, 300);
    label1.setOpaque(true);
    label1.setBackground(new Color(0,0,0,125));

    layeredPane.add(label, 0, 0);
    layeredPane.add(label1, 1, 0);

    frame.setSize(660, 400);

    frame.getContentPane().setBackground(Color.YELLOW);
    frame.setGlassPane(layeredPane);
    layeredPane.setVisible(true);
    frame.setVisible(true);

       ml = new MouseMotionAdapter() {

      public void mouseMoved(MouseEvent evt) {

                Point point = evt.getLocationOnScreen();

                Color color = robot.getPixelColor((int)point.getX(),(int)point.getY());
                System.out.println(color);
            }
  };
            label1.removeMouseMotionListener(ml);
            label.addMouseMotionListener(ml);
    }
}

Comment: De onde vem esse `robot`?
Comment: Do frame   `public void Frame1() throws AWTException
    {
        robot = new Robot();...}`
Comment: Tem como adicionar um trecho executável desse JFrame com o problema?
Comment: veja se atende!
Answer: Isso ocorre porque o que você está resgatando são as coordenadas da tela quando o mouse se move, e não as coordenadas do componente desejado. Por isso é retornado a cor do label que está sobreposto e não do label que está por baixo quando as coordenadas de ambos coincidem.
Pegue as coordenadas do componente ao invés de pegar da tela toda, senão o que vai ser levado em consideração é a cor sobreposta:
ml = new MouseMotionAdapter() {

    @Override
    public void mouseMoved(MouseEvent evt) {

        JComponent comp = (JComponent) evt.getSource();
        Point point = comp.getLocationOnScreen();

        Color color = robot.getPixelColor((int) point.getX(), (int) point.getY());
        System.out.println(color);
    }
};

label.addMouseMotionListener(ml);

A saída será:

Repare que a cor(em RGB) é sempre 255,0,0, ou seja, é a cor vermelha do JLabel que foi sobreposto.
Uma observação: A linha label1.removeMouseMotionListener(ml); é desnecessária no código, uma vez que o listener jamais é aplicado ao componente, então não há necessidade de remover.
Comment: Diego, você é o cara!!! Era isso que estava tentando resolver! Como eu sou noob neste site como eu te agradeço! :)
Comment: @vinuales disponha! :) Você pode marcar a resposta como aceita, clicando no `V`, assim, ela servirá de referencia para outros com problema semelhante,


Como manter as proporções de uma imagem dentro de uma div de tamanho fixo em CSS?

Question: Estou com dificuldade de criar uma imagem que fique dentro de uma div, mantendo suas proporções. Porém a div tem um tamanho padrão, não podendo ultrapassar esse tamanho limite.
Abaixo deixo uma imagem que ilustra qual é minha intenção:

Abaixo está o código em css que eu fiz, a imagem continua nos seus padrões, porém não é limitada na div, muitas vezes ultrapassando o tamanha desejado que caiba na tela:
<code>  #div{
      padding-top: 20px;
      padding-bottom: 20px;
      width: 50%;
      height: auto ;
    }
  #imagem{
      width: auto;
      height: auto;
      top: 5%;
      left: 26%;
    }
</code>
Possivelmente o código esteja sem muito sentido pois estou programando web a  pouco tempo.
Answer: Boa tarde. Você deve deixar a imagem responsiva, para que ela possa se adaptar ao container (elemento pai), a div em questão. Use a propriedade max-width: 100%; na imagem. O max-width evitará que a imagem ultrapasse o tamanho máximo do elemento pai. Lembre-se de utilizar agum tipo de posicionamento na div pai (float por exemplo), se ela estiver como static (valor padrão), os elementos internos não ficaram restritos a ela.
Exemplo:
<code>#imagem {
   max-width: 100%;
   float: left;
}

#div {
   float: left;
   width: 50%; /* 50% do tamanho do elemento pai */
}
</code>
Se precisar da margem utilize padding na div pai.
Comment: Muito obrigado, me ajudou muito.


Calculate the correct area to be cropped fabricjs

Question: I want to crop image using fabricJs but I'm stuck on the calculus of the correct area to be cropped.
When I click on the crop button, it doesn't crop the image to the correct area.
The calculation is wrong.
Here's my crop code:
<code>function centerXY (w, h) {
    return {
        x: canvas.width / 2 - w / 2,
        y: canvas.height / 2 - h / 2
    }
}
// zoneWidth: width of area where I want to cropped
// zoneHeight: height of area where I want to cropped
 $('#crop').click(function () {
    var zoom = canvas.getZoom()
    const imgTop = canvasImage.top
    const imgLeft = canvasImage.left
    const {x, y} = centerXY(zoneWidth, zoneHeight)
    let top = zoneHeight - imgTop - y
    let left = zoneWidth - imgLeft - x
    zoneWidth /= zoom
    zoneHeight /= zoom

    canvasImage.clipTo = ctx => {
      ctx.rect(left, top, zoneWidth, zoneHeight)
    };
    canvas.renderAll()
  })
</code>
This calculation is based on this post: Crop Functionality using FabricJs
Here's the demo.
Note: You can use the input type range to zoom out and see where the image is cropped.
Comment: Also, the reference you used is out of date - current version of fabric.js deprecate method `clipTo`.
Comment: Is there any particular reason for having the zone crop to be HTML element, instead  of drawing a rectangle in canvas?
Answer: I solved my problem.
Here's the solution:
<code> $('#crop').click(function () {
    var zoom = canvas.getZoom()
    let top = zoneY // Top position of area
    let left = zoneX// Left position of area
    zoneWidth /= zoom
    zoneHeight /= zoom

    canvas.clipPath = shapeRect; // fabric.Rect()
    canvas.renderAll()
  })
</code>
Instead of cropping the image, I cropped the canvas itself.
And Using the position of the area to crop
Here the final demo: https://jsfiddle.net/58nvte7h/43/