When did trumpet mutes come into use?

Question: My casual understanding is that mutes began to be invented and developed amongst jazz musicians looking to create unique sounds. Certainly I've encountered mutes primarily in jazz playing and also in contemporary classical music. I've never encountered a call for muting in pre-20th-century music.
But this is a casual understanding.
When did mutes first begin to appear in trumpet/cornet music?
Comment: Hm, https://en.wikipedia.org/wiki/Mute_(music)#Brass cites a claim for 1511, and apparently it's called for in Monteverdi's *Orfeo*...
Comment: Oo, and https://www.historicbrass.org/edocman/hbj-1990/HBSJ_1990_JL01_004_Keller.pdf looks useful. NB the Mersenne quote and illustration; clearly by 1635 there were objects created specifically as trumpet mutes (as opposed to just cramming something in the bell).
Comment: @AndyBonner "NB" ... the clearest possible indication of a graduate degree. :-) BTW, still looking forward to the possibility of your answer to the Stradivarius question.
Comment: Lol, I was using it much earlier, as the child of a couple of English majors. And yes, thanks for the reminder. (This one's got me wanting to refresh my knowledge of the similar origins of violin mute use. Somebody, I forget who—maybe Tartini?—talks about affixing a heavy key to the bridge. (Though there was definitely use long before Tartini))
Comment: @AndyBonner Yeah, sometimes I ask questions here less because I need the answer — like this one, I could look up the answer on my own — but because it seems like a good thing to have recorded on this site.
Comment: @AndyBonner your comments would make a perfect answer. Then you could earn even more points!
Comment: @RedSonja Thanks! I'm not sure I agree, though. In general, on SE, a response that does nothing more than offer a link is considered insufficient to be a proper answer (though various SE sites feel differently). I'd also love to follow the thread through to that 1511 primary source and judge its validity for myself, but don't have time to at the moment; Wikipedia cites the *Dictionary for the modern trumpet player*, and the relevant page is left out of Google books. Ideally I'd make an errand to look it up in person at a university library near me that has a copy, then see...
Comment: @RedSonja ... her citation for this 1511 mention and try to find *that*. I hold a healthy skepticism for all these claims of "X is the *first ever* instance of Y"; they're so easy to burst with just one find. Many of them get into gray areas of what counts as Y (did a 3-stringed version *count* as "the first violin"?), and many of them are just ignorant of an earlier instance.
Comment: @RedSonja I've been very fond of linking to my own dissertation lately, but see the discussion [starting on p 27](https://libres.uncg.edu/ir/uncg/f/Bonner_uncg_0154D_11176.pdf). In fact, I'd go so far as to say declaring "The first instance" of something is a sort of scholarly stunt, like yelling "FIRST POST!" More useful is to talk about significant emergence of trends, how a practice evolved from novel to established, and always to recognize that documented practice might have been preceded by significant undocumented practice.
Answer: This source says

The Toccata from Claudio Monteverdi's opera L'Orfeo (1607) is the
first appearance of the trumpet in an orchestral score and the
"Clarino con tre trombe sordine" called for indicates that the
trumpets were all muted. The Toccata is preceded by the instructions
"E si fa un tuono piú alto volendo sonar Ie Trombe con Ie Sordine", a
warning that the trumpets will be using mutes and that the pitch will
thus be a whole tone higher. The earliest mutes had the effect of
shortening the overall length of the trumpet by completely closing the
trumpet bell at the point of contact, with the sound going through a
hole in the center of the mute. These mutes raised the pitch by a half
or whole tone depending on the size of the bell. At some point,
probably around the time of Mozart's Idomineo (1790), mutes that
didn't change the pitch were invented or discovered. Since then the
ideal is a mute that doesn't disturb the orchestral fabric by being
too sharp or flat. Most modern mutes fulfill this ideal.

Wikipedia and other sources suggests the first Harmon-style mute showed up mid-19th century. There are a variety of tidbits in this article about the development of mutes and first uses by composers in the 18th and 19th centuries.

When did trumpet mutes come into use?


Find $\lim_{(x,y)\to (\alpha,0)}\left(1+\frac{x}{y}\right)^y$

Question: Find $$L=\lim_{(x,y)\to (\alpha,0)}\left(1+\frac{x}{y}\right)^y$$
My try:
I have chosen the Path $x=my+\alpha$
We get:
$$L=\lim_{y \to 0}\left(1+m+\frac{\alpha}{y}\right)^y$$
Which is of form $\infty^0$ and by L'Hopital's Rule i got $L=1$
Also by Path $x=0$ we get:
$$L=1$$
Now how can we conclude $L=1$ for any path we choose?
Answer: for $x> 0 \ \ y> 0 $ we get the following:
    $$ \left( 1+\dfrac{x}{y}\right) ^{y}=\exp\left( y\ln(1+\dfrac{x}{y})\right)=\exp\left( y\ln(x+y)-y\ln(y)\right)   $$
    we have the following inequality:
    $$\ln(x+y)\le x+y\Longrightarrow y\ln(x+y)\le y(x+y) $$
$$y\ln(y)\le y\ln(x+y)\Longrightarrow 0\leq y\ln(x+y)-y\ln(y)$$ thus
$$1\leq \exp\left( y\ln(x+y)-y\ln(y)\right)\leq \exp\left(  y(x+y)-y\ln(y)\right)  $$
and because  $\displaystyle \lim_{(x,y)\rightarrow(\alpha,0)} y(x+y)-y\ln(y)=0$ then we get the result that $\displaystyle \lim_{(x,y)\rightarrow(\alpha,0)}\exp\left( y\ln(x+y)-y\ln(y)\right)=\lim_{(x,y)\rightarrow(\alpha,0)} \left( 1+\dfrac{x}{y}\right) ^{y}=1 $
Answer: There is a problem with the expression $(1+\frac  xy)^{y}$ when  $1+\frac  xy$ is negative. So I will handle the case when the limit is taken through positive values of $y$ and $\alpha >0$.
$\lim_{y \to 0} (1+m+\frac {\alpha} y)^{y}=\lim_{y \to 0}(1+m)^{y}(1+\frac {\alpha /(1+m)} y)^{y} )=(1)(1)=1$. But this does not prove that the limit exists and equals $1$.
Observe that $(1+\frac t y)^{y}=e^{y\ln (1+\frac  t y)} \to e^{0}=1$ for each fixed $t $. Apply this to $t=\alpha -\epsilon$ and $\alpha +\epsilon$ and use the squeeze Theorem to conclude that the given limit exists and equals $1$.
Comment: @pigeon  Thank you for your comment.  There is a problem with the question itself since $t^{y}$ for $t<0$is not well defined. So I have edited my answer to consider only special case.
Comment: What if $t>0$ and $y\to 0^-$?


Getting a field value from a view

Question: I am new to Drupal8. In one of the preprocess functions in my customtheme.theme file, I need to get the value of a field from a view that I have already created. I searched the web and got:
 $view = $variables['view'];
    $view_result = $view->result;
    if (!empty($view_result)) {
      foreach ($view->result as $rid => $row) {
        foreach ($view->field as $fid => $field ) {
          $values[$rid][$fid] = $field->getValue($row);
        }
      }
    }
   $array[0] = $values[0]['nid'];

AND i got another one too :
$view = $variables['view'];
$values = [];
foreach ($view->result as $row_id => $row) {
  foreach ($view->field as $field_id => $field ) {
    $values[$row_id][$field_id] = $field->getValue($row);
  }
}

The first solution worked but I want an explanation of it please especially that I tried to print_r ($view_result) and that didn't work, so I managed to print its keys and got onyl one key which is 0. Then I got many weird keys when I did a foreach to print the keys of  $view_result[0].
I would be grateful if someone can explain to me the code and why did the getValue function take an argument ? I usually write it as getValue() only.
Answer: What you usually write as getValue() without arguments is a method of an entity FieldItemList.
$view->field returns field handler plugins configured in the FIELDS section of a View.
Views fields handler plugins are an abstraction layer for all kind of data not necessarily based on entity fields.
If based on entity fields then getValue($row) runs this code:
/core/modules/views/src/Plugin/views/field/EntityField.php:
 public function getValue(ResultRow $values, $field = NULL) {
    $entity = $this->getEntity($values);

    // Ensure the object is not NULL before attempting to translate it.
    if ($entity === NULL) {
      return NULL;
    }

    // Retrieve the translated object.
    $translated_entity = $this->getEntityFieldRenderer()->getEntityTranslation($entity, $values);

    // Some bundles might not have a specific field, in which case the entity
    // (potentially a fake one) doesn't have it either.
    /** @var \Drupal\Core\Field\FieldItemListInterface $field_item_list */
    $field_item_list = isset($translated_entity->{$this->definition['field_name']}) ? $translated_entity->{$this->definition['field_name']} : NULL;

    if (!isset($field_item_list)) {
      // There isn't anything we can do without a valid field.
      return NULL;
    }

    $field_item_definition = $field_item_list->getFieldDefinition();

    $values = [];
    foreach ($field_item_list as $field_item) {
      /** @var \Drupal\Core\Field\FieldItemInterface $field_item */
      if ($field) {
        $values[] = $field_item->$field;
      }
      // Find the value using the main property of the field. If no main
      // property is provided fall back to 'value'.
      elseif ($main_property_name = $field_item->mainPropertyName()) {
        $values[] = $field_item->{$main_property_name};
      }
      else {
        $values[] = $field_item->value;
      }
    }
    if ($field_item_definition->getFieldStorageDefinition()->getCardinality() == 1) {
      return reset($values);
    }
    else {
      return $values;
    }
  }

You can see how Views API connects with Entity API, but when programming Views API code you should stay at this abstraction layer if possible.
Comment: Thank you veryy much

Getting a field value from a view


Serialize form, where fields have multiple child fields

Question: I have one form which has 4 fields:

Full Name
Email
Text Area
Address

Full name and address have multiple fields.
I have 4 columns in the database: full name, e-mail, text area, and address.
Can anyone let me know how to achieve the result?
Here is the form layout:
Comment: You can either concatenate the subfields with javascript before you submit them, or you can change your web service to accept all of the different subfields, and process them there before storing in the database. Honestly your life will be easier if you just have the database match the UI.
Answer: If you are constrained to the 4 fields in the database you can concatenate the 2 fields with a known delimiter like
Assuming
fname = $('#fname').val();
lname = $('#lname').val();

Then
delimiter = "~";
fullname = fname  + delimiter + lname;

And the same for address
Then when you read the fields into the form for an edit you can use a split on the delimiter to break them up
name = fullname.split(delimiter);
fname = name[0];
lname = name[1];

However a much better solution is to add more fields to your database table to accommodate the individual fields


Determine change in values in a grouped dataframe

Question: Assume a dataset like this (which originally is read in from a .csv):
data = pd.DataFrame({'id': [1,2,3,1,2,3],
                     'time':['2017-01-01 12:00:00','2017-01-01 12:00:00','2017-01-01 12:00:00',
                          '2017-01-01 12:10:00','2017-01-01 12:10:00','2017-01-01 12:10:00'],
                     'value': [10,11,12,10,12,13]})

=>
    id  time                    value
0   1   2017-01-01 12:00:00     10
1   2   2017-01-01 12:00:00     11
2   3   2017-01-01 12:00:00     12
3   1   2017-01-01 12:10:00     10
4   2   2017-01-01 12:10:00     12
5   3   2017-01-01 12:10:00     13

Time is identical for all IDs in each observation period. The series goes on like that for many observations, i.e. every ten minutes.
I want the number of total changes in the value column by id between consecutive times. For example: For id=1 there is no change (result: 0). For id=2 there is one change (result: 1).
Inspired by this post, I have tried taking differences:
Determining when a column value changes in pandas dataframe
This is what I've come up so far (not working as expected):
data = data.set_index(['id', 'time']) # MultiIndex
grouped = data.groupby(level='id')
data['diff'] = grouped['value'].diff()
data.loc[data['diff'].notnull(), 'diff'] = 1
data.loc[data['diff'].isnull(), 'diff'] = 0
grouped['diff'].sum()

However, this will just be the sum of occurrences for each id.
Since my dataset is huge (and wont fit into memory), the solution should be as fast as possible. ( This is why I use a MultiIndex on id + time. I expect significant speedup because optimally the data need not be shuffled anymore.)
Moreover, I have come around dask dataframes which are very similar to pandas dfs. A solution making use of them would be fantastic.
Comment: If you have an item that changes from 10 to 11, and then from 11 to 10, the right output will be 2, but `len(set(x)) - 1` will record only 1. This is how you have described your problem statement, and that is how we have interpreted and answered it.
Comment: You could try asking a question in the numba tag and seeing if you'd get any response or speedup. Doubt pandas can do anymore here.
Comment: Important: Can one set of readings in one time slot have multiple readings associated with the same ID?
Comment: @COLDSPEED: no, these are observations. For each point in time there is at most one value for each id.
Comment: Well, in that case you have 3 good answers giving you the same thing. Please choose the most helpful solution and accept it.
Comment: Yes, thanks a lot. I did some measuring. Wen and COLDSPEED where very similar. @Vaishali 's first answer is way faster:
`1 loop, best of 3: 659 ms per loop`
`1 loop, best of 3: 219 ms per loop`

However, I wonder why nobody gave attention to my request for maximal speed. Does the MultiIndex not help with that? Because all your answers won't work with an MultiIndex. Also a solution in dask would be preferable. Especially in combination with MultiIndex this could speed up things.
Comment: The first may be faster but is also incorrect.
Comment: Mind to elaborate? For my case it returns the same output as the other solutions.
Comment: I see, that makes sense. Thanks a lot for the explanation. With my actual data   I've done some more timings. There is no significant difference in computing time between using an index or not using one. Also using dask.dataframe there is no speedup (because the apply func cant be reduced).
Comment: Thanks for taking the time to evaluate our answers. You mentioned apply, but my answer does not have apply. However if it is the same speed as apply, I guess that's all you've got.
Answer: Do you want something like this?
data.groupby('id').value.apply(lambda x: len(set(x)) - 1)

You get
id
1    0
2    1
3    1

Edit: As @COLDSPEED mentioned, if the requirement is to capture change back to a certain value, use
data.groupby('id').value.apply(lambda x: (x != x.shift()).sum() - 1)

Answer: I think you're looking for a groupby and comparison by shift;
data.groupby('id')['value'].agg(lambda x: (x != x.shift(-1)).sum() - 1)

id
1    0
2    1
3    1
Name: value, dtype: int64

Comment: Its ok, I personally feel that both are valid answers given within seconds. So as long as no one is copying, its cool:)
Comment: @Vaishali I think my answer is the same as yours. I'll just remove it. What do you think?
Answer: data.groupby('id').value.agg(lambda x : (x.diff()!=0).sum()).add(-1)
id
1    0
2    1
3    1
Name: value, dtype: int64

Another by using pct_change
data.groupby('id').value.apply(lambda x : (x.pct_change()!=0).sum()).add(-1)
Out[323]:
id
1    0
2    1
3    1
Name: value, dtype: int64

Comment: @cᴏʟᴅsᴘᴇᴇᴅ Can not figure it out ,haha ~ waiting for you update ~ :)
Comment: Ah I knew there was another method with diff. Was waiting for you to find it +1


Can you use the same Gemalto MFA fob for multiple AWS accounts?

Question: I control multiple AWS accounts. I'd like to use MFA for the root logins.
I have a Gemalto hardware key fob from Amazon (docs) registered for MFA for the root account on one of them.
I tried to add MFA to a second account using the same key fob, but I got the message "The token serial number was not found.".
Can anyone confirm or deny whether it is possible to reuse the same key fob for MFA for multiple AWS accounts?
I have not been able to find anything about this scenario in Amazon's documentation, and the error message is ambiguous. Cryptographically it seems to me like it should work fine, as it's a time-based token, rather than a OTP chain.
Answer: Your logic seems sensible, but AWS doesn't support this.

Q. Can I use my authentication device with multiple AWS accounts?

No. The authentication device or mobile phone number is bound to an individual AWS identity (IAM user or root account). If you have a TOTP-compatible application installed on your smartphone, you can create multiple virtual MFA devices on the same smartphone. Each one of the virtual MFA devices is bound to a single identity, just like a hardware device. If you dissociate (deactivate) the authentication device, you can then reuse it with a different AWS identity. The authentication device cannot be used by more than one identity simultaneously.

https://aws.amazon.com/iam/faqs/

One possible rationale for their policy can be found in this answer to "Is Sharing the Same TOTP Across Multiple Servers Any Less Secure?".
Comment: Thanks! Not sure why I didn't find that when I looked in the docs; it's right there in the main FAQ about 2FA :-)


What does "Parse error: syntax error, unexpected ')'" mean?

Question: Why am I getting the following error in PHP?
<?php

    require_once('validation_functions.php');
    $errors = array();

    //$username = trim($_POST["username"]);
    $username = trim("");

    if(!has_presence($username))
    {
        $errors['username'] = "Username can't be left blank";
    }
?>

<?php echo form_errors($errors); ?>

This is the following problem:

Parse error: syntax error, unexpected ')' in C:\wamp\www\sandbox\validation_functions.php on line 20

This is the file validation_functions.php detailed above
 <?php

function has_presence($value)
{
    //IF $value is SET AND value is NOT EXACTLY EQUAL TO "" RETURN TRUE
    return (isset($value) && $value !== ""); //RETURNS BOOLEAN
}

function has_max_length($value, $max)
{
    //IF $value is LESS THAN OR EQUAL TO $max Return TRUE
    return (strlen($value) <= $max)); //RETURNS BOOLEAN
}

function has_inclusion_in($value, $set)
{
    //IF $value is INCLUDED in $set RETURN TRUE
    return in_array($value, $set); //RETURNS BOOLEAN
}

function form_errors($errors = array())
{
    $output = "";

    if(!empty($errors))
    {
        $output = "
";
        $output .= "Please Fix The Following Errors:";
        $output .= "
";

        foreach($errors as $key => $error)
        {
            $output .= "
 {$error}
";
        }

        $output .= "
";
        $output .= "
";
    }

    return $output;
  }

 ?>

This is included in the code referenced above. It's a simple error but I can't seem to understand what's causing it.
Comment: You should post validation_functions.php, the error you are posting is in line 20, but you have only posted  18(+/-) lines
Comment: The error is at line 20 from `validation_functions.php`. You need to paste that
Comment: this error clearly tell there is some extra ")" at line 20 on validation_functions.php, please check it
Comment: PHP error reports you clearly that the file and the line number, `C:\wamp\www\sandbox\validation_functions.php`
Comment: I'm unaware of any extra ")" at line 20 after having checked sir
Answer: You have an extra bracket in the marked line
function has_max_length($value, $max)
{
    //IF $value is LESS THAN OR EQUAL TO $max Return TRUE
 >>>>>>>>>   return (strlen($value) <= $max)); //<<<< here is a extra bracket, remove the last one!

Should be like this:
return (strlen($value) <= $max)

Answer:
correct way: return (strlen($value) <= $max);

function has_max_length($value, $max)
{
//IF $value is LESS THAN OR EQUAL TO $max Return TRUE
return (strlen($value) <= $max); //RETURNS BOOLEAN

}


How to upload video into Odoo?

Question: I would like to upload video(s) from my local storage, manually, on Odoo website but it seems that there is no such option.
When I try to upload any media, I see that I can upload image, document (e.g. pdf file). There is no problem to upload any image or pdf file but on video section, it is written: Video code (URL or Embed) and Accepts Youtube, Vimeo, Dailymotion and Youku videos. Why? Why is this not possible? Do you have any solution?

I especially am asking this because I want to play video on my carousel and when I insert a vimeo or youtube video, on mobile, I have the Tap to Unmute issue.
Ayn idea, solution?
Answer: So, after I did some researches I have found the solution of how to upload a video on Odoo.
In order to add any media, you first need to edit a page of the website on front-end. When you click to Edit you will see the new blocks and all edit options on the right sidebar. Then, click to an empty area in the page and you will see that STYLE section on sidebar will become active. Click to the image icon ("File/Image" when you hover it) and Select a Media modal will open. Go to Document section --> Upload a document --> choose video from your local storage and when the upload finishes, it will add/appear a small video icon on the empty area where you had clicked before. Right click on it and and copy the link. Then, remove the extra part of the link and that is it.
e.g.
www.yourdomain.com/web/content/111111/?unique=2323c304345b19d696a5cf1cabb05cc9da49a5d90&download=true

final result:
www.yourdomain.com/web/content/111111/

How to upload video into Odoo?


How to use Case Statement

Question: Using C#.Net and MYSQL
I want to use a CASE Statement like SQL
Query
SELECT vehicleno,
       brandname,
       CASE
         WHEN inexpire < 0 THEN 'Expired'
         ELSE inexpire
       END AS inexpire
FROM   (SELECT Concat(plateno, vehicleno)   AS vehicleno,
               brandname,
               Datediff(inedate, Curdate()) AS inexpire
        FROM   tb_car
        WHERE  inedate < DATE_ADD(Curdate(), INTERVAL 30 DAY)
        GROUP  BY vehicleno) AS tab1

When I run the Query it is showing the output as
System.Byte[] instead of "Expired"
In the above query inexpire is column values
How can I solve this issue.....
Need Query Help
Comment: You seem to mix the different data types for inexpire, either you get a numeric value (you do check if the value is less than 0) or the string 'Expired'.
Comment: What is `inexpire` meant to return? Do you want it to return the string 'Expired' if it has expired and the number of days cast to a string if it hasn't? Or something else?
Answer: I think you would need to use the same datatype for both cases
e.g.
case when inexpire < 0 then 'Expired' else 'inexpired' end as inexpire

or
 case when inexpire < 0 then 1 else inexpire end as inexpire

Edit
Actually I just did a quick test on my machine this mixing of datatypes doesn't cause an error but the result just shows as Blob in MySQL Workbench
SELECT
cast( CASE  WHEN inexpire < 0 THEN 'Expired' ELSE inexpire END as char) as inexpire

stops this issue as suggested here. This should thus avoid the Byte[] issue
Comment: I'm actually surprised MySQL doesn't raise an error in this case. I think that Sybase, MS & IBM DB2/UDB all raise errors when the return type from a case differs (or at least there's no implicit conversion available). I'd be curious to know what the actual database type of `inexpired` is.
Comment: @Nathan - Maybe it does just cast the number to a string actually. I'm not in a position to test this at the moment.
Comment: MySQL's behaviour towards such expression can be configured. I think that by default it will issue a warning at most.
Comment: @Mhcl - I just did a quick test and it doesn't raise an error but shows up as `blob` in MySQL Workbench
Comment: inexpired is a table column values, no need to give in the single quotation, I tried your query when i use the else condition it is showing sytem.Byte error...., why it is coming, mysql why not taking the else statement
Answer: IF(inexpire < 0, 'Expired',inexpire) AS inexpire

How to use Case Statement


listview vb6 from sql: object required

Question: I am learning vb6 from youtube in a short time. but none of the videos that I watch defined well on object required to defined. it get error on line ListView1.ListItems.Clear I need to know the details on defined object in vb6, these are my codes.
Sub filllistview()
 strsql = "select * from pemilikkenderaan "
 Set rs = cn.Execute(strsql)
 ListView1.ListItems.Clear
 Do While Not rs.EOF
 Set Item = ListView1.ListItems.Add(, , rs!carid)
 Item.SubItems(1) = rs!username & ""
 Item.SubItems(2) = rs!cartype & ""
 Item.SubItems(3) = rs!carcolour & ""
 Item.SubItems(4) = rs!rfidno & ""
 rs.MoveNext
 Loop
 Set rs = Nothing
End Sub

Comment: Is this code in a form? Does the form have a control named ListView1 added to it?
Comment: ya from a form and it doesn't. and i just found out the solution this morning. I made several forms where it show and hide after clicking a button, while im following a tutorial that using only one form. So I've made a mistake where the code i wrote is in a wrong form, and it cause the form searching where is the list view that i've been mentioned. Btw, thank you so much for your respond.
Comment: Glad you found out the problem!  Good luck & have fun with the tutorials :)
Answer: 1) Add Components
2)Add References
check the link below for more:
list in vb6
Try this code:-
Private Sub filllistview()
Dim cn As New ADODB.Connection
cn.ConnectionString = ""
cn.CursorLocation = adUseClient
cn.Open

Dim strsql As String
strsql = "select * from pemilikkenderaan"
Dim rs As New ADODB.Recordset
rs.Open strsql, cn
ListView1.ListItems.Clear
Dim Item As Nodes

Do While Not rs.EOF
    Set Item = ListView1.ListItems.Add(, , rs!carid)
    Item.Add rs!carid, rs!username, rs!username
    Item.Add rs!carid, rs!cartype, rs!cartype
 Item.Add rs!carid, rs!carcolour, rs!carcolour
    Item.Add rs!carid, rs!rfidno, rs!rfidno
 rs.MoveNext
Loop
Set rs = Nothing
Set cn = Nothing

End Sub

Private Sub cmdCreateList_Click()
filllistview
End Sub

Comment: It is good that it solves your problem @AngelaHeely  .If you want more information, visit the page: http://esjay.org

listview vb6 from sql: object required


what is the meaning of probability distribution function?

Question: what is the meaning of probability distribution function? I am struggling to understand it can anyone help me please
Comment: Our highest-voted posts about [tag:pdf] are all directly relevant: see https://stats.stackexchange.com/questions/tagged/pdf?sort=votes.
Comment: @omesaad Perhaps start with https://en.wikipedia.org/wiki/Probability_distribution and https://en.wikipedia.org/wiki/Cumulative_distribution_function and https://en.wikipedia.org/wiki/Probability_density_function ... (some uses of your term may really refer to any of these)
Answer:
For a continuous case:

A cumulative probability distribution function p is a function which takes as argument a realization x of a random variable X and outputs the probability that X can be less or equal to this exact value, given that X is distributed according to p.
A probability density function is intuitively how likely a realization x will come from this local sample of X compared to other local samples of X.

For a discrete case:

A probability distribution function returns the probability of X == x, which is positive on all the support of the function, i.e., all possible x's. While in the continuous case the probability of any given x is zero.


FuelPHP can't setup database to work

Question: I'm using FuelPHP and I can't set up my database so it would work. I know that i'm using right information but i'm not sure if I put it in right place.
<?php

return array(
'default' => array(
    'connection'  => array(
        'dsn'        => 'mysql:firstname.lastname@example.com;dbname=modernt',
        'username'   => 'modernt',
        'password'   => 'pass',
    ),
),
);

This is my db.php in APP/config/db.php
Comment: Are you sure, you should use `modernt` host and not `localhost`?
Comment: I'm testing it not on local machine. I'm doing it on the server
Answer: Environment configurations are merged, and the environment wins.
So if you have ./app/config/db.php containing return array('a'); and you'll have ./app/config/development/db.php containing return array('b');, then after reading your config, you'll end up with "b".
So if you use environment based config (like DB does by default), only add configuration to the global file that is truely global, otherwise it gets overwritten in the merge.
Answer: Check this
'dsn' => 'mysql:host=moderntalking.lt;dbname=modernt',

Comment: Did you check the permissions?
Comment: i still get the same error :
Fatal error: Uncaught exception 'Fuel\Core\FuelException' with message 'Unable to create or write to the log file. Please check the permissions on /home/modernt/domains/moderntalking.lt/public_html/fuel/app/logs/.
Answer: // a MySQL driver configuration
'development' => array(
    'type'           => 'mysqli',
    'connection'     => array(
        'hostname'       => 'localhost',
        'port'           => '3306',
        'database'       => 'fuel_db',
        'username'       => 'your_username',
        'password'       => 'y0uR_p@ssW0rd',
        'persistent'     => false,
        'compress'       => false,
    ),
    'identifier'     => '`',
    'table_prefix'   => '',
    'charset'        => 'utf8',
    'enable_cache'   => true,
    'profiling'      => false,
    'readonly'       => false,
),

// a PDO driver configuration, using PostgreSQL
'production' => array(
    'type'           => 'pdo',
    'connection'     => array(
        'dsn'            => 'pgsql:host=localhost;dbname=fuel_db',
        'username'       => 'your_username',
        'password'       => 'y0uR_p@ssW0rd',
        'persistent'     => false,
        'compress'       => false,
    ),
    'identifier'     => '"',
    'table_prefix'   => '',
    'charset'        => 'utf8',
    'enable_cache'   => true,
    'profiling'      => false,
    'readonly'       => array('slave1', 'slave2', 'slave3'),
),

'slave1' => array(
    // configuration of the first production readonly slave db
),

'slave2' => array(
    // configuration of the second production readonly slave db
),

'slave3' => array(
    // configuration of the third production readonly slave db
),

Basic procedure of setup FuelPHP..may be its help you .Thank you
Comment: well i read that tutorial in framework page a lot of times, but it doesn't work.
just to be sure, where to put this piece of code? now it sits in App/config/development/db.php
Comment: @Casad link is http://fuelphp.com/docs/classes/database/introduction.html   . I flow this this and its work for that reason i share this with you .
Comment: well i saw that, and it's not working, that's why i'm asking what's wrong
Answer: First, check your environment configuration in app/bootstrap.php:
/**
* Your environment. Can be set to any of the following:
*
* Fuel::DEVELOPMENT
* Fuel::TEST
* Fuel::STAGING
* Fuel::PRODUCTION
*/
Fuel::$env = (isset($_SERVER['FUEL_ENV']) ? $_SERVER['FUEL_ENV'] : Fuel::DEVELOPMENT);

Then modify the db.php file accordingly (app/development/db.php, app/production/db.php, app/staging/db.php, app/test/db.php)

FuelPHP can't setup database to work


"syntax error, unexpected end of file" Upon enabling modules

Question: I'm getting a syntax error when enabling modules.  This is happening intermittently and it isn't specific to any module in particular, which is making it impossible for me to track down.  Here is the error I'm receiving today:

Parse error: syntax error, unexpected end of file in sites/all/modules/contrib/headerimage/headerimage.module on line 821

Line 821 is the very last line of the file, and the syntax looks fine to me.  When I get a similar error when enabling modules, it's always complaining about the last line.  There are never any missing brackets.  I've disabled any custom modules I wrote thinking that it could be my code causing this, but I've had no success.
I was wondering if anyone has run into this, if they have any suggestions, or possibly a method to troubleshoot this.
-- EDIT --
I was able to resolve the syntax errors for this particular module (headerimage).  I had to delete the very last line in two of the files and re-add them manually.  They were closing brackets "}".
I'm not convinced that this is the correct fix.  Maybe it's some kind of encoding issue?  Any thoughts?
Answer: I figured out what this was. It wasn't necessarily related to Drupal or PHP syntax, but the answer might save someone else some stress.
I had VMWare Fusion on my Mac running a Linux VM with Apache/MySQL/PHP server.  The webroot for Apache was a shared directory on my host machine which contained my Drupal install. I did this so I can have the benefit of a Linux web server while being able to edit my code locally on my host.
This works when serving up the site, but whenever I used Drush on the VM to install a module, there was always a hidden line appended to the module's files that Vi didn't pick up, which is why the syntax error was always on the last line. I'm assuming it had to do with the hgfs filesystem used for sharing between my host and the VM.
Once I removed the VM sharing and modified everything on the VM itself, all of my problems went away. Downloading modules with Drush no longer produces these syntax errors.
Here is a related thread on the Drush issue queue where people are having similar issues.
https://drupal.org/node/1948962
Thanks to those who gave their feedback.
--richard
Answer: This is a parse error which occurs when php is still looking for something and reaches the end of the file without finding it. It could be a quote or bracket which is unclosed, and php is still treating the file contents as a part of the quote.
Yes line 821 is the last line of the file. Php is just telling you it was unexpected.
Errors like this are not intermittent, but you might have to do some work to find how to reproduce it. Once you do that, you can start eliminating modules to try to find the source.
Good luck.
Answer: It could be as simple as removing the last closing PHP tag (?>), if one exists, at the end of the file(s). Generally no files should end with a closing PHP tag, although they should have a starting tag (<?php) at the very beginning.
Comment: Actually, contrary to many answers in stack overflow, the closing tag will not generate this error. The reason for omitting the closing tag in php scripts is to prevent the accidental output of unintended white space, which will generate 'Headers already sent' errors. [See the manual](http://php.net/manual/en/language.basic-syntax.phptags.php).
Comment: Yea, that's true. I stand corrected. Thanks for the update/refresh.
Comment: Thanks for the input. That was the first thing that I checked for since I remember reading that in Drupal's best practices.


TextBox.Keypress doesn't respond to return key

Question: I have a form with various text boxes.  One text box is used for entering a floating point number, so I am using TextBox.KeyPress to process each digit in turn, which only modifies the Text property.  The text is processed by a routine that is called when the OK button id pressed (before closing the form).  It is also called by the TextBox.Leave event.  However, if I change the contents of the text box then press Return to variable isn't updated.
I thought I could overcome this by the following:
    private void DestPointNoTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Return)
        {
            prvUpdateDestPointNo();
        }
    }

This is called whenever a key is pressed while the text box is in focus, as can be proved by setting a breakpoint within it.  However, it is not called when Return is pressed.
Can someone explain how I can ensure new text is processed when Return is pressed?
 If I change the contents of one then click the OK button the new
Comment: Can you please show us the routine you are using to get the values ?
Answer: If you are using Windows Form Application, then you can set the AcceptButton property of the Form to the OK button and the Click event of the OK button will be fired when you press Enter/Return key
Comment: What do you mean by `set the AcceptButton property to the OK button `.As far as i know there is no property named `AcceptButton` for `Button Control` although `TextBox Control` has a property named `AcceptsReturn`.And how you can call the `Click Event` of any Button with `Enter Key` unless it has keyboard focus ?
Comment: sorry, I mean the AcceptButton property on the Form.
Answer: I would use the Debugger to determine the value of e.KeyCode at runtime.
Why?
When I ran similar code (Winforms TextBox, KeyDown registered), the value of e.KeyCode was
e.KeyCode = LButton | MButton | Back

Another property of KeyEventArgs you can use is KeyValue -
private void DestPointNoTextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyValue == 13)
    {
        prvUpdateDestPointNo();
    }
}


"checked" do "ion-radio" não funciona

Question: <ion-list radio-group style="margin-bottom:10px;" [(ngModel)]="orcamento.tipo" name="tipo" #tipo="ngModel">

    <ion-item>
        <ion-label>Consumidor</ion-label>
        <ion-radio value="consumidor" checked="true"></ion-radio>

    </ion-item>

    <ion-item>
        <ion-label>Revenda</ion-label>
        <ion-radio value="revenda"></ion-radio>
    </ion-item>

</ion-list>

Queria que a primeira opção desses radio inputs viesse selecionada como padrão, mas no template ele fica assim:

Porque a opção não está vindo selecionada?
Comment: http://jsfiddle.net/yk62zsxv/55/
Comment: Só aproveitando o seu jsfiddle, quando eu instalei o ionic, nao veio com aquele arquivo app.js (que em todos os tutoriais se usa ele), e em nenhum arquivo a programação veio nesse "modelo": (angular.module('ionicApp', ['ionic']).controlle). Tem a ver com a versão do ionic?
Comment: Sim. Ele e utilizado para ter acesso aos componentes no ionic
Answer: Não precisa desse true, é só passar o "checked"
<ion-radio value="consumidor" checked></ion-radio>

Caso não de  certo, tente
<ion-radio value="orderBy1" [checked]="orderBy1">

Comment: Apenas com o checked também não foi :/
Também tentei com [checked]="consumidor" e não apareceu nada...
Answer: Perceba que dentro do seu ion-list possui um ngModel que é onde será armazenado o valor da opção selecionada, cada ion-radio possuí um value, para você inicializar o component com um selecionado, basta inicializar a variável "orcamento.tipo" com o value do ion-radio que você deseja que comece selecionado, exemplo:
-- Seu component.ts --
orcamento.tipo = 'consumidor';

Adicionando este código em seu constructor ou no seu onInit do component já deve vir selecionado, não precisando do checked no html, pois será feito o bind do valor do ngModel do radio selecionado.
UPDATE
-- Seu component.ts --
orcamento = { tipo: 'consumidor', ... seus outros atributos de orcamento };

O erro aconteceu pois seu orcamento é um objeto, veja onde você o inicializa e no campo tipo defina com o value do ion-radio desejado.
Na verdade quando você seleciona um ion-radio ele faz isso por trás, adiciona o value do ion-radio no ngModel, então se você inicializar o valor dele com um selecionado, ele vai buscar dentro do ion-list qual ion-radio tem o value informado e vai o selecionar.
Comment: Apareceu um erro: ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'tipo' of undefined
Comment: Corrigi a resposta.
Comment: Agora sim! Muito obrigado!!

“checked” do “ion-radio” não funciona


WSO2 ESB Callout Mediator axis2Configuration

Question: I have a question regarding the WSO2 ESB callout mediator using an individual Axis2 configuration file. I would like to have the individual Axis2 configuration to be deployed using a carbon application. Unfortunately the callout mediator doesn't seem to be able to read the Axis2 configuration from the registry. I'm getting an error that the file axis2_blocking_client_proxy.xml can't be resolved when I deploy the carbon application that contains the mediation with my callout mediator.

The deployment works when I Quote a relative file path that points to the configuration file. Does anybody know if there is a way to tweak carbon application files so that distinct resources will be written to a dedicated directory on the WSO2 ESB Server?
Best regards,
Heiko
Answer: AFAIU, your requirement is to deploy an axis2 configuration file using a CAR (carbon application) file. This is not a recommended approach. If you need to deploy a configuration file in to the ESB, you can deploy that during the server creation time. CAR files are used to deploy the actual implementation code rather than the static configuration files.


How can I speed up Pkg.add() in Julia?

Question: Take Cairo as an example, when I run Pkg.add("Cairo"), there's nothing displayed in the console.

Is there a way to let Pkg.add() display more information when it is working?
What steps does Pkg.add() carry out? Download, compile?
Is it possible to speed it up? I kept waiting for 15 minutes, nothing out! Maybe it's Julia's problem, or maybe it's system's problem, how can one tell?

Edit
Julia version: 0.3.9 (Installed using binary from julia-lang.org)
OS: Winsows 7 64bit.
CPU:  Core Duo 2.4GHz
RAM: 4G
Hard Disk: SSD

ping github.com passed, 0% loss.
Internet download speedtest: ~30 Mbps.

I don't know whether this is normal: it took me 11 seconds to get the version.
PS C:\Users\Nick> Measure-Command {julia --version}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 11
Milliseconds      : 257
Ticks             : 112574737
TotalDays         : 0.000130294834490741
TotalHours        : 0.00312707602777778
TotalMinutes      : 0.187624561666667
TotalSeconds      : 11.2574737
TotalMilliseconds : 11257.4737

And it took nearly 2 minutes to load the Gadfly package:
julia> @time require("Gadfly")
elapsed time: 112.131236102 seconds (442839856 bytes allocated, 0.39% gc time)

Does it runs faster on Linux/Mac than on Windows? It is usually not easy to build software on Windows; however, will it improve the performance if I build from source?
Julia is awesome, I really hope it works!
Comment: 15 minutes is too long. There is a download step so the first thing to check would be your internet connection (maybe try pinging github). Also, you should probably edit the question to include your Julia version and OS.
Comment: @ColinTBowers Thanks for your reminding. I've added more information.
Comment: Hi Nick, I'm on Ubuntu, so won't be much use here. Here is what I can tell you: Gadfly loads in about 5 seconds on my machine. `julia --version` runs pretty much instantaneously. Given the specs, Cairo should download and install in well under a minute. So there is definitely something funny with your install. I also know there are plenty of Windows users who are able to get Julia running just fine. Hopefully one of them will see this page and can offer some advice. If not, try posting a question to the julia-users google group. Good luck, it is a great language!
Comment: @ColinTBowers Thank you very much! I guess I should build from source when I got time.
Comment: Has this since been answered? Did you fix your problem?
Answer: As mentioned by Colin T. Bowers, your particular case is abnormally slow and indicates something wrong with your installation. But Pkg.add (along with other Pkg operations) is known to be slow on Julia 0.4. Luckily, this issue has been fixed.
Pkg operations have seen a substantial increase in performance in Julia v0.5, which is being released today (September 19, 2016). You can go to the downloads page to get v0.5. (It might be a few hours before they're up as of the time of this writing.)

How can I speed up Pkg.add() in Julia?


Distribution Selection based on Kolmogorov Smirnov Test

Question: I am trying to model the distribution of some non normal data, to do so i am fitting many different distributions(Student, Pareto...)  to the data. When computing the Kolmogorov Smirnov Statistic for each of the candidate distributions, Can I use the different p values to rank the candidates? Otherwise, how can I use the Kolmogorov Smirnov Test to select the best candidate?
I have found an article which proposes a similar procedure on Page 11 (Chapter 6), but I dont know about the reliability since it is discussed nowhere besides this article : https://www.iiap.res.in/astrostat/School10/LecFiles/Karandikar_Babu_ModelSelGOF_notes.pdf?fbclid=IwAR39zkhXRUD-j4JvCttBr6JOErxkp7h9Ct_Osz7BaXJkgF9wmWtFY4B2w14
Thanks.
Comment: Why do you feel you need to know the distribution?
Comment: What is your sample size? You are probably better off with visualization methods as a start. Try qqplots, ... search this site!
Comment: I have already tried different methods : qqplot, bic ,wasserstein distance, but I am curious as to how one could use the Kolmogorov Smirnov Test quantile to select the best model out of a large number of candidates, is it theoretically acceptable to compare the p values?  My sample size is 2500.
Answer: I wouldn't use the p-value to choose; I'd use the test statistic itself.
More specifically, I'd be quite unlikely to do something like this in the first place, and if I did I'd be quite unlikely to choose the Kolmogorov-Smirnov to do it wth, but if for some reason I did do it, I'd be looking at the actual measure of discrepancy rather than its p-value, since that at least says something about the fit.
Note that this would only make sense to use for comparison if the distributions were fully specified (or otherwise at least if number of parameters were the same for each distribution).
In the case where different models have different numbers of free parameters, I would not expect there to be a good way to compare the discrepancies (nor indeed the p-values) across models using the Kolmogorov-Smirnov distance.
Comment: Wouldnt the use of the quantile of the Kolmogorov Smirnov Distance(which we could bootstrap to get) make more sense since,otherwise, we can be vulnerable to outliers? And what other less known methods for distribution selection can I explore ? Thanks.
Comment: The statistic is looking at the difference in terms of a vertical difference in cdf. How much effect can an outlier have? The second question is probably better asked as a new question, but consider that (a) the best answer may usually be "don't select a distribution at all" and (b) such a question has already been answered on site a number of times already.


Claims Rule Language RegExReplace with multiple matches

Question: BACKGROUND: I am trying to setup single sign on between an on prem AD and AWS via ADFS.  I do not have access to our ADFS instance and I really dont know much at all about ADFS so I am left trying to guess at solutions to this.  Fortunately, I think I am close and just have one claims rule translation to resolve before I believe everything will work as it should.
ISSUE: The issue I am having is that I need to translate an AD group into an AWS role using Claims Rule Language (which I also dont have much experience with) but the the rule I have come up with isn't working properly.
What I've Tried: I've gotten the AD groups to fill the temp/variable type and get passed to the next step in the pipeline where the tokens are issued.  The format for the AD group I need to parse is: AWS#AWS_AccountName#AWS_RoleName#AWS_AccountNumber (i.e. AWS#Sandbox#SecurityAuditor#1234567890).
I need to use the AWS_RoleName and AWS_AccountNumber in this group name to generate the arn that is to be passed to AWS.  I tried to use RegExReplace to do this with this rule:
c:[Type=="http://temp/variable", Value=~"(?i)(^AWS)#([-_a-z0-9]+)#([-_a-z0-9]+)#([-_a-z0-9]+)"] => issue(Type="https://aws.amazon.com/SAML/Attributes/Role", Value=RegExReplace(c.Value, "(?i)(^AWS)#([-_a-z0-9]+)#([-_a-z0-9]+)#([-a-z0-9]+)", "arn:aws:iam:$4:saml-provider/ADFS,arn:aws:iam:$4:role/AWSReservedSSO$3))
The idea being that I would use $ to fill out the AWS rolename that is needed to gain access.  However I dont thing this is working because I just read that the RegExReplace replaces ALL RegEx matches in the source string with the string generated by the 3rd parameter.
Can anybody point out the flaws in this claim rule or a better rule to write to get the desired result?
Thank you in advance
Answer: Okay, so for some reason my $index construction wasnt working. When I replaced those with named variables in my regex, it started working properly.  So my updated claims rule looks like:
<code>c:[Type=="http://temp/variable",
Value=~"(?i)(^AWS)#([-_a-z0-9]+)#([-_a-z0-9]+)#([-_a-z0-9]+)"] =>
issue(Type="https://aws.amazon.com/SAML/Attributes/Role",
Value=RegExReplace(c.Value,
                   "(?i)(^AWS)#(?<accountname>[-_a-z0-9]+)#(?<role>[-_a-z0-9]+)#(?<accountnumber>[-a-z0-9]+)",
                   "arn:aws:iam:${accountnumber}:saml-provider/ADFS,arn:aws:iam:${accountnumber}:role/${role}))
</code>


C# | Como selecionar apenas algumas subpastas?

Question: Preciso buscar as informações de apenas algumas subpastas dentro de um diretório principal, fiz um código dessa forma mas estou com dificuldades para encontrar um jeito de informar apenas as subpastas que preciso.
Por exemplo tenho um pasta nesta estrutura:
Pasta
|
|_ _ _ subpasta1/arquivos.xml
|
|_ _ _ subpasta2/arquivos.xml
|
|_ _ _ subpasta3/arquivos.xml
Precisaria pegar os dados apenas da subpasta1 e subpasta3, o código que tenho só consigo ler a Pasta inteira:
using System.IO;
using System;
using System.Linq;

namespace LerDiretorios
{
    class Program
    {
        static void Main(string[] args)
        {
            var directoryPath = @"C:\Pasta\";
            var searchPattern = "*.xml";
            var monthsAgo = -2;
            string[] filesFound;
            var startTime = DateTime.Now;

            try
            {
                filesFound = Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);

                filesFound
                    .Select(f => new FileInfo(f))
                    .Where(f => f.CreationTime >= f.CreationTime.AddMonths(monthsAgo))
                    .ToList();
            }
            catch (Exception ex)
            {
                Console.Write($"ERRO: {ex.Message}");
                goto End;
            }

            if (filesFound.Length == 0)
            {
                Console.WriteLine("Nenhum arquivo encontrado.");
                goto End;
            }

            foreach (string filePath in filesFound)
            {
                FileInfo fInfo = new FileInfo(filePath);
                Console.WriteLine(
                    $"{fInfo.Directory}, Arquivo: {Path.GetFileName(fInfo.Name)}, " +
                    $"Criado em: {fInfo.CreationTime.ToString()}\n");
            }

            //Conta os registros lidos
            Console.WriteLine($"Quantidade de registros lidos: {filesFound.Length}");

            //Mostra hora de início do procedimento
            Console.WriteLine($"Hora Inicio: {startTime.TimeOfDay}");

            //Mostra hora de fim do procedimento
            var finishTime = DateTime.Now;
            Console.WriteLine(
                $"Hora Fim: {finishTime.TimeOfDay} \n" +
                $"Tempo de Execução: {finishTime.TimeOfDay - startTime.TimeOfDay}");

        End:;
        }
    }
}

Comment: @VirgilioNovic são quase 60 subpastas, simplifiquei um pouco no exemplo, mas a lógica penso que seria a mesma para resolver. Vou tentar o for pra ver como fica.
Comment: Tem tantas formas mas nada direto tem que passar o Path nesse caso separados já visto que você sabe qual deseja ler. Crie um array com os nomes da pastas e faça um for. Pergunto é várias pastas?
Comment: Como você faria se não fosse programação?
Answer: Observação: seu código pode ser refatorado e aperfeiçoado, porque pode por exemplo criar a lista de FileInfo diretamente pela class DirectoryInfo
Se deseja especificar somente alguns diretórios para listar os seus arquivos dependendo do tipo utilize um argumento de array informando quais pastas precisa pesquisar, também vale lembrar que já existe um maneira de retornar FileInfo de forma explicita, segue o exemplo abaixo:
Esse método primeiro retornar um array de FileInfo:
private static FileInfo[] GetFiles(string[] paths, string search = "*.xml")
{
    FileInfo[] items = null;
    foreach (string path in paths)
    {
        if (Directory.Exists(path))
        {
            items = (items == null)
                ? (new DirectoryInfo(path)).GetFiles(search)
                : items.Concat((new DirectoryInfo(path)).GetFiles(search)).ToArray();
        }
    }
    return items;
}

E esse outro método imprime as informações do arquivo:
private static void PrintFileInfo(FileInfo[] fileInfos)
{
    if (fileInfos != null)
    {
        foreach (FileInfo fileInfo in fileInfos)
        {
            Console.WriteLine(
             $"{fileInfo.DirectoryName} Arquivo: {fileInfo.Name}, " +
             $"Criado em: {fileInfo.CreationTime.ToString("dd/MM/yyyy HH:mm:ss", null)}\n");
        }
    }
    else
    {
        Console.WriteLine("Nenhum dado para impressão");
    }
}

sempre tente dividir de uma maneira lógica que cada coisa faz, um pega os arquivos o outro mostra os arquivos e assim por diante, o reaproveitamento fica mais claro.

Como utilizar?
// Busca os arquivos
FileInfo[] items = GetFiles(new string[] { @"C:\", @"D:\" }, "*.txt");

//Mostra os arquivos com as suas informações
PrintFileInfo(items);

Referencias:

FileInfo Class
DirectoryInfo Class


Is there a way to create a non-stop spinning square using html and css?

Question: I want to create a non-stop spinning square using html and css. I currently have:
@-webkit-keyframes spinnow {
    100% {
        transform: rotate(360deg);
        -webkit-transform: rotate(360deg);
    }
}
@-moz-keyframes spinnow {
    100% {
        transform: rotate(360deg);
        -moz-transform: rotate(360deg);
    }
}
@-ms-keyframes spinnow {
    100% {
        transform: rotate(360deg);
        -ms-transform: rotate(360deg);
    }
}

What I have currently got will make the square spin, but it will always stop after one full rotation, then start shortly afterwards. How do I make it continuously spin without stopping?
N.B. I'm using @-webkit-keyframes, @-moz-keyframes and @-ms-keyframes.
Thanks very much,
Lucas
Comment: What HTML and CSS code do you have so far?
Comment: I just added it in as an edit. Thank you for reminding me to add that.
Answer: It has nothing to do with the definition of the animation, but with its usage:
.foo {
    animation: 5s spinnow infinite linear;
}

The infinite keyword is what you need. You can also put an integer there, to have a finite number of rotation cycles.
Edit by OP: For future visitors, the linear keyword is to make the animation not speed up and then slow down using the swing animation, but rather use a linear, smooth approach, so that the speed is distributed and does not make the square appear to stop. This keyword was the important one for me - I had the infinite keyword already.
http://jsfiddle.net/GXPS8/
Comment: Right now it's not spinning on chromium, works in firefox
Just a minor problem in the order of parameters
http://jsfiddle.net/ZD7yN/ this one works
Comment: Can you please rewrite your jsfiddle code? When I clicked the link, all I saw was a stationary square. Sorry for bothering you.
Answer: My guess is that the existing code goes through rotation of 360 degrees, then 0 degrees, then rotates back to 360 degrees again.
The stop you perceive may be due to the animation rendering the same rotation twice (360 degrees = 0 degrees).
EDIT: not pure HTML+CSS as OP is trying to do, but it may address the fluidity issue.
Calculating the amount of rotation to do via a formula similar to this should do the trick:
var rotation=0;
...
function _RotateStep(){
    rotation=(rotation+1)%360;
    //apply rotation to element (via method of choice)
    setTimeout("_RotateStep()",250); //or time between rotation steps of your choice
}

In Pure CSS, you may be able to get away with setting it to rotate to 359 degrees continuously, eliminating the duplicate rotation being rendered.
Comment: nah, javascript's ok. Thanks!


How to multiply a vector and matrix when the matrix includes a translation?

Question: What is the proper way to right multiply an $N$ x $N$ matrix $H$ by an $N$ x $1$ vector $\mathbf{v}$, if $H$ includes a translation vector?
For example, say
$$H=R-\mathbf{tn}^T$$
where $R$ is a conventional rotation matrix, $\mathbf{t}$ is a translation vector and $\mathbf{n}^T$ is the transpose of the normal vector to a plane.  And I want to figure out $\mathbf{v'}$:
$$\mathbf{v'}=H\mathbf{v}$$
The rotation part of the equation is easy (say $N=2$ and $\mathbf{v}=(x,y)$):
$$R\mathbf{v}=\begin{bmatrix}x_r\\y_r\end{bmatrix} =\begin{bmatrix}\cos{\theta} & -\sin{\theta}\\\sin{\theta} & \cos{\theta}\end{bmatrix} \begin{bmatrix}x\\y\end{bmatrix}$$
$$\begin{matrix}x_r=x\cos{\theta}-y\sin{\theta} \\y_r=x\sin{\theta}+y\cos{\theta}\end{matrix}$$
But now I'm not sure what to do with the translation part.
$$\mathbf{tn}^T\mathbf{v}=?$$
Help is appreciated.  The matrix $H$ in this question is based on the homography matrix.
Comment: $\mathbf{tn}^T$ should itself be a matrix, being the product of a vector with a transposed vector (in that order). So you can go on with the same kind of multiplication.
Comment: Yes. the (i,j) elements of matrix $\mathbf{tn}^T$ is $t_i n_j$
Answer: $$\mathbf{v'}=H\mathbf{v}=(R-\mathbf{tn}^T)\mathbf{v}=R\mathbf{v}-\mathbf{t}(\mathbf{n\cdot v})$$
where $\mathbf{n\cdot v}$ is a scalar.


Move primary tabs to the shortcuts bar

Question: I am using drupal7 and the admin menu overlay (in seven). And I'm always apalled by the primary tabs appearing in view mode. They are messing up the layout for the editors / admins, and they're usually not in style with either the site design or the overlay design.
I was just wondering .. is there a pretty way to move the primary tabs ('edit' et al) to the admin overlay shortcuts bar - 'if the overlay is visible and you are in view mode'
Perhaps there are two answers:

remove the primary tabs from the content, if the overlay is visible and you are in view mode
add the primary tabs to the shortcuts bar,    if you are in view mode

Any hints ?
*-pike
Comment: Huh ? If by "extraordinarily narrow situation that is not generally applicable" you mean all users of Drupal 7, then yes. The overlay admin, the seven theme, the primary tabs, are all standard in 7. Did I phrase the question wrong ?
Comment: This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet
Answer: The easiest way would be to use the http://drupal.org/project/admin_menu module.
It has an option to move the tabs into the admin menu bar.
Set it by going to the admin menu settings page (admin/config/administration/admin_menu) and checking the "Move local tasks into menu" option.
For users gien access to the admin menu, you should remove access to the drupal toolbar module, or they will have 2 toolbars.
You could even disable to toolbar module and just use admin menu.
If you want to keep using the toolbar module instead of the admin menu module, you can remove the tabs from the page.tpl.php file in your theme and then print them elsewhere.
I don't know off the top of my head how you would go about doing that though.
Comment: excellent, brilliant, exactly what i meant.

Move primary tabs to the shortcuts bar


Is morphisms in category equivalent to binary relation?

Question:
Composition of relations is associative

https://ncatlab.org/nlab/show/relation#binary_relations
https://en.wikipedia.org/wiki/Binary_relation
https://en.wikipedia.org/wiki/Composition_of_relations#Properties
On the other hand, in a category
https://ncatlab.org/nlab/show/category#OneCollectionOfMorphisms

for every pair of morphisms f and g, where t(f)=s(g), a morphism g∘f, called their composite (also written gf or sometimes f;g— see diagrammatic order);

If composition of morphism (and associativity) is required to form a cateogory, are morphisms in category equivalent to binary relation?
Or, is there anything else than binary relation that is composable which can also be a morphism of cateogry?
Thanks.
Answer: It is not quite the case that every category can be represented by a relation, but every (small) category can be represented by a categorified relation, known as a profunctor.
Consider a category with object-set $C_0$. A reflexive transitive endo-relation $R : C_0 \times C_0 \to 2$ on $C_0$ describes whether two objects $X, Y \in C_0$ are connected by a morphism, i.e. $R(X, Y) \implies \exists f : X \to Y$. However, note that such categories are necessary thin/posetal: we may have at most one morphism between any two objects. These relations turn out to be monads in the 2-category $\mathbf{Rel}$ of relations.
To represent categories, we may instead move to profunctors, which are categorified relations (i.e. we replace the two-element set $2$ with the category of sets $\mathbf{Set}$). An endo-profunctor on a small discrete category $C_0$ (i.e. a set), which is a monad in the bicategory $\mathbf{Prof}$ of profunctors, is exactly a category with object-set $C_0$. (Monads in $\mathbf{Prof}$ are sometimes called "promonads".)
Comment: @KevinArlin: I agree that the question could be interpreted as "Is every category a subcategory of $\mathbf{Rel}$?", but I took "are morphisms in category equivalent to binary relation" to refer to a representation result. (If it had been "equivalent to binary relations", I probably would have read it the other way, so this could be a grammatical issue.) The question under the other interpretation was answered by PrudiiArca, so hopefully we covered all the bases between us :)
Comment: This has been accepted, but I have trouble reading the problem as "can every category be represented as a binary relation" rather than "can the morphisms in every category by represented (individually) as binary relations"...
Answer: It is not perfectly clear to me what you are asking for.
Given a category being composable defines a relation on the class/set of morphisms, but I don't think this is your question.
A category need not consist of sets and relations. For example you can draw a finite category like $\bullet \rightarrow \bullet$, where the indicated morphisms is the only non-identity. There is no real choice for composition here. Another example would be the category $BM$ associated to a monoid $M$, which consists of one object and an endomorphism for every monoid element. The composition is defined by the monoid multiplication. To make this work one does not really need to know, what this one object is made of, so depending on how you model it, the morphisms need not be relations.
Answer: I suspect that you are asking if a morphisms in a category must be a function.
The answer is no
You may regard a group as a one object category, where morphisms are the elements of a group and composition is the group multiplication. The same is true for a monoid. So morphisms in a category need not be (structure preserving)  function between sets (with structures).
Anyhow one could notice that in such cases an element can actually be identified with a function: a multiplication for that element. So in some sense we fall back in the previous case.
At the same time there are cases where this is not the case: for instance take index categories, which are basically graphs with compositional arrows and identity arrows at any node. By the way they are also very useful: any commutative diagram in a category C is a functor from an index category  J into C.
Comment: Thanks, but the question is "Is morphisms in category equivalent to binary relation?" not  "Is morphisms in category equivalent to function?" Function is a special case of binary relation. So, your guess is not correct. Please discuss on relation not function, thanks.
Comment: @Leucippus, well I tried to do my best in order to answer the question, which is not clear at all. Moreover the content of my answer is very similar if not identical to that of PrudiiArca (we posted at the same identical time), which has not be deleted. Please explain this policy to me.
Comment: Your question is not clear, also in terms of grammar. Hence my confusion. Anyhow, as also @PrudiiArca mentioned, taking index categories yields morphisms which are not binary relations.


InvalidOperationalException base.Dispose(disposing)

Question: I creating diagnostic application for PLCs. I have one form and a few Controls, which was inherited of UserControl. This Controls I switch. One view is Dashboard, Graph, and so on. When the graph is running, exception is occured. Exception is showed on line "base.Dispose(disposing)" in Form1.Designer.cs. Do you have any idea, how I can fix it? Thanks for any ideas.

This is code of Form1.Designer.cs. Error is show on line base.Dispose(disposing). Basicaly I don't know what this part of code do. That I can't repair it. Can somebody tell me, how it works? When is this part called? I don't find any use of method Dispose() in my program, only override methodes in each Control (inherited from UserControl). Thanks
namespace WindowsFormsApplication1
{
    partial class Form1
    {
        ///
        /// Required designer variable.
        ///
        private System.ComponentModel.IContainer components = null;
    ///
    /// Clean up any resources being used.
    ///
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        /*Updated 8.4.2013*/
        //try
        //{
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        //}
        //catch { }
    }

    #region Windows Form Designer generated code

    ///
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    ///
    private void InitializeComponent()
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
        this.statusStrip1 = new System.Windows.Forms.StatusStrip();
        this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
        this.btn_ChangeLanguage = new System.Windows.Forms.Button();
        this.pictureBox1 = new System.Windows.Forms.PictureBox();
        this.Zobraz_Palubka = new System.Windows.Forms.Button();
        this.Zobraz_Verzi = new System.Windows.Forms.Button();
        this.Zobraz_error = new System.Windows.Forms.Button();
        this.Zobraz_Nastaveni = new System.Windows.Forms.Button();
        this.Zobraz_TestIO = new System.Windows.Forms.Button();
        this.Zobraz_monitor = new System.Windows.Forms.Button();
        this.statusStrip1.SuspendLayout();
        ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
        this.SuspendLayout();
        //
        // statusStrip1
        //
        this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
        this.toolStripStatusLabel1});
        resources.ApplyResources(this.statusStrip1, "statusStrip1");
        this.statusStrip1.Name = "statusStrip1";
        //
        // toolStripStatusLabel1
        //
        this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
        resources.ApplyResources(this.toolStripStatusLabel1, "toolStripStatusLabel1");
        //
        // btn_ChangeLanguage
        //
        this.btn_ChangeLanguage.Image = global::WindowsFormsApplication1.Properties.Resources.flag_cze_mini;
        resources.ApplyResources(this.btn_ChangeLanguage, "btn_ChangeLanguage");
        this.btn_ChangeLanguage.Name = "btn_ChangeLanguage";
        this.btn_ChangeLanguage.UseVisualStyleBackColor = true;
        this.btn_ChangeLanguage.Click += new System.EventHandler(this.btn_ChangeLanguage_Click);
        this.btn_ChangeLanguage.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
        this.btn_ChangeLanguage.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
        //
        // pictureBox1
        //
        this.pictureBox1.BackColor = System.Drawing.Color.Transparent;
        this.pictureBox1.Image = global::WindowsFormsApplication1.Properties.Resources.trojuhelnik;
        resources.ApplyResources(this.pictureBox1, "pictureBox1");
        this.pictureBox1.Name = "pictureBox1";
        this.pictureBox1.TabStop = false;
        //
        // Zobraz_Palubka
        //
        this.Zobraz_Palubka.Image = global::WindowsFormsApplication1.Properties.Resources.tachometr_mini;
        resources.ApplyResources(this.Zobraz_Palubka, "Zobraz_Palubka");
        this.Zobraz_Palubka.Name = "Zobraz_Palubka";
        this.Zobraz_Palubka.UseVisualStyleBackColor = true;
        this.Zobraz_Palubka.Click += new System.EventHandler(this.Zobraz_Click);
        this.Zobraz_Palubka.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
        this.Zobraz_Palubka.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
        //
        // Zobraz_Verzi
        //
        this.Zobraz_Verzi.Image = global::WindowsFormsApplication1.Properties.Resources.info_mini;
        resources.ApplyResources(this.Zobraz_Verzi, "Zobraz_Verzi");
        this.Zobraz_Verzi.Name = "Zobraz_Verzi";
        this.Zobraz_Verzi.UseVisualStyleBackColor = true;
        this.Zobraz_Verzi.Click += new System.EventHandler(this.Zobraz_Click);
        this.Zobraz_Verzi.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
        this.Zobraz_Verzi.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
        //
        // Zobraz_error
        //
        this.Zobraz_error.Image = global::WindowsFormsApplication1.Properties.Resources.error1_mini;
        resources.ApplyResources(this.Zobraz_error, "Zobraz_error");
        this.Zobraz_error.Name = "Zobraz_error";
        this.Zobraz_error.UseVisualStyleBackColor = true;
        this.Zobraz_error.Click += new System.EventHandler(this.Zobraz_Click);
        this.Zobraz_error.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
        this.Zobraz_error.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
        //
        // Zobraz_Nastaveni
        //
        this.Zobraz_Nastaveni.Image = global::WindowsFormsApplication1.Properties.Resources.settings_mini;
        resources.ApplyResources(this.Zobraz_Nastaveni, "Zobraz_Nastaveni");
        this.Zobraz_Nastaveni.Name = "Zobraz_Nastaveni";
        this.Zobraz_Nastaveni.UseVisualStyleBackColor = true;
        this.Zobraz_Nastaveni.Click += new System.EventHandler(this.Zobraz_Click);
        this.Zobraz_Nastaveni.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
        this.Zobraz_Nastaveni.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
        //
        // Zobraz_TestIO
        //
        this.Zobraz_TestIO.Image = global::WindowsFormsApplication1.Properties.Resources.testIO_mini;
        resources.ApplyResources(this.Zobraz_TestIO, "Zobraz_TestIO");
        this.Zobraz_TestIO.Name = "Zobraz_TestIO";
        this.Zobraz_TestIO.UseVisualStyleBackColor = true;
        this.Zobraz_TestIO.Click += new System.EventHandler(this.Zobraz_Click);
        this.Zobraz_TestIO.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
        this.Zobraz_TestIO.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
        //
        // Zobraz_monitor
        //
        this.Zobraz_monitor.Image = global::WindowsFormsApplication1.Properties.Resources.line_graph_icon_mini;
        resources.ApplyResources(this.Zobraz_monitor, "Zobraz_monitor");
        this.Zobraz_monitor.Name = "Zobraz_monitor";
        this.Zobraz_monitor.UseVisualStyleBackColor = true;
        this.Zobraz_monitor.Click += new System.EventHandler(this.Zobraz_Click);
        this.Zobraz_monitor.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
        this.Zobraz_monitor.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
        //
        // Form1
        //
        resources.ApplyResources(this, "$this");
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.Controls.Add(this.btn_ChangeLanguage);
        this.Controls.Add(this.pictureBox1);
        this.Controls.Add(this.Zobraz_Palubka);
        this.Controls.Add(this.Zobraz_Verzi);
        this.Controls.Add(this.Zobraz_error);
        this.Controls.Add(this.statusStrip1);
        this.Controls.Add(this.Zobraz_Nastaveni);
        this.Controls.Add(this.Zobraz_TestIO);
        this.Controls.Add(this.Zobraz_monitor);
        this.Name = "Form1";
        this.statusStrip1.ResumeLayout(false);
        this.statusStrip1.PerformLayout();
        ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.Button Zobraz_monitor;
    private System.Windows.Forms.Button Zobraz_Nastaveni;
    private System.Windows.Forms.StatusStrip statusStrip1;
    private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
    private System.Windows.Forms.Button Zobraz_TestIO;
    private System.Windows.Forms.Button Zobraz_error;
    private System.Windows.Forms.Button Zobraz_Verzi;
    private System.Windows.Forms.Button Zobraz_Palubka;
    private System.Windows.Forms.PictureBox pictureBox1;
    private System.Windows.Forms.Button btn_ChangeLanguage;
}

}

Here is exception detail:
System.InvalidOperationException was unhandled by user code
  Message=Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Control.get_Handle()
       at System.Windows.Forms.Form.UpdateMenuHandles(MainMenu menu, Boolean forceRedraw)
       at System.Windows.Forms.Form.UpdateMenuHandles()
       at System.Windows.Forms.Form.MenuChanged(Int32 change, Menu menu)
       at System.Windows.Forms.Form.Dispose(Boolean disposing)
       at WindowsFormsApplication1.Form1.Dispose(Boolean disposing) in c:__Projects__\C#\RailJay Diagnostic SW\20130408\Motor\Motor\Form1.Designer.cs:line 23
       at System.ComponentModel.Component.Dispose()
       at System.Windows.Forms.ApplicationContext.Dispose(Boolean disposing)
       at System.Windows.Forms.Application.ThreadContext.DisposeThreadWindows()
  InnerException:
Answer: It appears that you're calling Dispose from a thread other than the GUI thread. You can't do that.
Comment: but if I look for in whole project, that I can't find any instance or calling of Dispose method. So that is very incomprehensible for me...
Answer: You need to be more specific - perhaps adding some code to what you are trying to do, where?
[EDIT]
As Jim mentioned, you are referencing a form from a seperate thread;

Here is exception detail:
System.InvalidOperationException was unhandled by user code
  Message=Cross-thread operation not valid: Control 'Form1' accessed
  from a thread other than the thread it was created on

This means that you are trying to dispose Form1 from a thread that it was not created on.
Have you got sperate threads running in the application, if so, this is the first place to look.
Are you closing the Form1 anywhere within code?
Comment: I just realize, that i use threading for change language. Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en"); I try to comment it and will see. Thanks for advices.


Error check for int value not working

Question: I have a function that is meant to test whether or not a field in a .csv contains a valid id (ProfileID in this case). I want to check for non-numeric entries and display an error message if this is true. However, I don't understand why the function I have setup fails to catch the error. The import process still produces an error page with the message: "Conversion failed when converting the nvarchar value '9b' to data type int" (9B is the invalid value I have in my test .csv file).
This is the code:
    bool RetVal = true;

    //PROFILEID
    string ProfileID = GetValue(row, (int)ProfileColumns.ProfileId);
    try
    {
        ProfileID = ProfileID.ToLower();
        int profIDCount = 0;

        int pnumber;
        bool presult = Int32.TryParse(ProfileID, out pnumber);

        if (presult == false)
        {
            ErrorLabel.Text += "Error Line " + LineCount + ": on " + ProfileID + " Invalid ProfileID
";
            RetVal = false;
        }

        else
        {
            string profIDSqlStr = string.Format("SELECT COUNT(*) AS 'ProfileID' FROM ProductProfile WHERE ProfileID=@ProfileID");
            using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
            {
                SqlCommand cmd = new SqlCommand(profIDSqlStr, cn);
                cmd.Parameters.AddWithValue("@ProfileID", ProfileID);
                cn.Open();

                using (IDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {

                        profIDCount = Convert.ToInt32(reader["ProfileID"].ToString());
                    }
                    if (profIDCount <= 0)
                    {
                        ErrorLabel.Text += "Error Line " + LineCount + ": on " + ProfileID + " Invalid  Product Profile
";
                        RetVal = false;

                    }
                }
                cn.Close();
            }
        }
    }
    catch
    {
        ErrorLabel.Text += "Error Line " + LineCount + ": on " + ProfileID + " Error looking up product profile
";
        RetVal = false;
    }

Answer: The reason is this line:
 cmd.Parameters.AddWithValue("@ProfileID", ProfileID);

Your ProfileID is of type string , so your C# code would add it as a string , (Surrounded by single quotes) that is why you are getting the error. You need to pass parsed value (int) to your parameter.
Declare your int variable pnumber outside of the try block and initialize it with a default value.  (no need, since scope is same)
Just pass pnumber as your parameter value.
cmd.Parameters.AddWithValue("@ProfileID", pnumber);

Answer: Use the correct type, so not string when it's an int column.
Replace
cmd.Parameters.AddWithValue("@ProfileID", ProfileID);

with
cmd.Parameters.AddWithValue("@ProfileID", pnumber);

pnumber was successfully  initialized in Int32.TryParse.

Error check for int value not working