Tricky Rails migration and modeling involving a self-join ":users" table and a ":bands" table: simultaneous one-to-many and many-to-many relationships

Question: My :users table is successfully self-joined with all the necessary confusing (to this newbie) code and tables necessary to do that.  :users's two groups are :teachers and :students.
I need to make the group :teachers join one-to-many with the :bands table (a band may have only one teacher) while at the same time joining :students many-to-many with the :bands table (a band may have many students and vice versa).
What's tripping me up is :students and :teachers are both :users.  Therefore, if for a moment I pretend that there's only one kind of user and go for a one-to-many (teacher) relationship, then the Band model belongs_to :user and the User model has_many :bands
But if I go for the many-to-many (student) relationship instead, the Band model has_many :users, through :user_bands join table and the User model has_many :bands, through :user_bands join table. (UserBands model has belongs_to :user and belongs_to :band in this case)
But I need both relationships at the same time.  I haven't actually tried putting has_many :bands in the User model while simultaneously having has_many :users (through join table) and belongs_to :users in the Bands model because, unless Rails is more magic than I give it credit for, it won't differentiate that teachers get the single-to-many while the students get the many-to-many.
I have not attempted my best guess (below) because I'm admittedly skittish: my database already has a sprawling number of many-to-many relations that are intact and functioning properly.  The one time I attempted to make a complicated alteration to it earlier in the process, it thoroughly messed things up so badly that rolling back and undoing model alterations didn't get me back to where I'd started somehow, so I had to go back to rebuilding everything from scratch after pulling out enough hair for a tonsure.  I do have github this time, so I should be able to revert the project if it blows up like before, but git is its own fussy minefield.
So if some folks could take a look at my guess first, I'd deeply appreciate it.  Does it look right?  Do I need to make changes before updating the database schema?:

In User model, add has_many :bands.
In Band model, add has_many :students, through :user_bands ; add belongs_to :teacher
In the create_bands migration, add t.belongs_to :teacher
In UserBands model, add belongs_to :teacher and add t.belongs_to :teacher in the create_user_bands migration.
Answer: The needed associations are not self-joining. Self-joins are primarily used to build tree like hierarchies from a single table - see the guides for a good example.
You just need  multiple associations between two tables - the key thing here to remember is that you must use unique names for each association. If you declare multiple associations with the same name the later just overwrites the former without error.
Teachers
class AddTeacherIdToBands < ActiveRecord::Migration[5.2]
  def change
    add_reference :bands, :teacher, foreign_key: { to_table: :users }
  end
end

class User < ApplicationRecord
  has_many :bands_as_teacher,
    class_name: 'Band',
    foreign_key: 'teacher_id'
end

class Band < ApplicationRecord
  belongs_to :teacher,
    class_name: 'User'
end

We name the association bands_as_teacher to avoid conflict and confusion. This requires us to explicitly set the class_name and foreign_key options as they cannot be deduced from the name.
This is kind of where you tripped up and overcomplicated your solution. If the association is one to many you don't need to involve a join table.
Students
To create the association between a band and its members you need a m2m association through a join table:
class CreateBandMemberships < ActiveRecord::Migration[5.2]
  def change
    create_table :band_memberships do |t|
      t.references :band, foreign_key: true
      t.references :user, foreign_key: true
      t.timestamps
    end
  end
end

class Band < ApplicationRecord
  # ...
  has_many :band_memberships
  has_many :users, through: :band_memberships
end

class BandMembership < ApplicationRecord
  belongs_to :band
  belongs_to :user
end

class User < ApplicationRecord
  # ...
  has_many :band_memberships
  has_many :bands, through: :band_memberships
end

You can improve the naming by providing the source option which tells Rails which association to use on the model its joining through.
class Band < ApplicationRecord
  # ...
  has_many :band_memberships
  has_many :members, through: :band_memberships, source: :user
end

class User < ApplicationRecord
  # ...
  has_many :band_memberships
  has_many :bands_as_member, through: :band_memberships, source: :band
end

Comment: Max, this is fantastic! I have to say that I'm still shaky on what's going on with the more intricate uses of ActiveRecord like the above, but I do understand much more than I did before, and I owe that to your excellent writing.

I followed along, and after making the relevant updates in seeds to test the relationships, I think it's functional. The Student> #` instead of something like `=> #`.  Is the return supposed to look like the former?
Comment: Correct, `has_many` associations return a CollectionProxy which is an array like object.
Comment: Aha!  I went back to see if I could then use any other finder methods to poke around in the proxy and discovered through the returns that I'd mistyped in the User model `foreign_key: 'Teacher_id'`.  Uncapitalizing the T made the return come out with all the info.

Cheers!


Find something out about a former process

Question: Yesterday my vServer was shut down by my provider cause of some unusual load. They told me there were multiple processes running with the name dtdfs. I also see in the log that there was some some high network traffic. I now changed all passwords and restarted the server. I also tried to find a program named "dtdfs", but without any success. I also unsuccessfully grep'd the logs for that name.
I didn't have any process logging applications manually installed (it's Debian system). It isn't a highly important server (just a development server hosting some git repos), but I'd like to learn from that and find out what happened.
Where should I start? What about that dtdfs process? Is there a way afterwards to get more info about that process?
Answer: While a process is running, /proc/{pid}/exe is a symbolic link to the executable it originally ran from, but after the fact you're pretty much out of luck.
As for this mysterious "dtdfs", it could be anything, even /bin/ls ... a process can change its commandline after it starts, which is probably what was seen if your provider was using ps to investigate.
Answer: I found it on two of my systems in /tmp.  Since you rebooted before looking for it, it was not there to find.  I have yet to find out how I was hacked but both systems do run proftpd.
Answer: I saw the hack in a link from Debian bugtraq ML. This afternoon or tomorrow i will sniff connection to find the websites it try to connect... I'll post some news thereafter!
Comment: Do you have a link to that mailing list post? Thanks.
Answer: The /tmp/dtdfs being run from your /tmp, which I also found on a number of systems at the same time/date turned out to be a proftpd exploit, and dtdfs was part of a botnet flooding program being run in /tmp. The ip coded in it traced back to a UK address, if you have a plesk server then parallels released a hotfix for it just a few days ago. If its just stand alone proftpd on debian or ubuntu then proftpd's site had the hotfix posted as well a few days back. Its always best to not run these services at all if your not even using them, or turn it on when you do need it, typically proftpd has been pretty good IMO up until this one.
Comment: Exactly, Plesk and ProFTP. The joke is that there are millions of options with Plesk, but not one to turn off FTP. I disabled it now from manually. Thanks for the detailed explanation and the botnet info.


Embed a single field from an existing content in ckeditor

Question: I managed to embed the full content or teaser using Entity Embed module in Drupal 8 but, is it possible to embed a single field which contains text or html without coding
Comment: `Full` and `teaser` are view modes showing different fields. You could create a third view mode (`/admin/structure/display-modes/view`), configure the this node display mode to show only one specific field (`/admin/structure/types/manage/NODE_TYPE/display/VIEW_MODE`) and then embed them as usual.
Answer: You can accomplish this using tokens. The exact token used will vary based on your configuration, but if you wanted to embed a the current user's first name, you could use something like [current-user:field_first_name]. Here's one article about them. https://www.ostraining.com/blog/drupal/tokens-in-drupal-fields/


Seriealize() Aajax com problema

Question: Tenho vários formulários em um html, e quero enviar com o Ajax cada formulário, estou usando o serialize(). Mais não está dando certo, onde estou errando?
 <div class="resultado_<?php $i++; echo $i ?>">

Cadastro Completo

  <form method="post" id="favoritos" novalidate="novalidate">

      <input type="hidden" name="id_empresa" value="<?php echo $row["id"]?>" class="id_empresa">

   <input type="submit" value="Favoritos">

</form>

Ajax
$(document).ready(function() {
    $("#favoritos").submit(function() {
    $.ajax({
        type: "POST",
        url: 'enviar_atualizar.php',
        data: $(this).serialize(),
        success: function (data) {
            // Inserting html into the result div
            $('.resultado_'+formID).html(data);
        },
        error: function(jqXHR, text, error){
            // Displaying if there are any errors
            $('.resultado_'+formID).html(error);
        }
    });
    return false;
});

});
retorna isso no console
Uncaught ReferenceError: formID is not defined
Answer: Provavelmente a variável formDetails não foi declarada ou por não estar dentro de $(document).ready(function() { ... }); ela não tenha conseguido pegar o FORM, você pode resolver simplesmente usando assim:
$(document).ready(function() {
    $("#favoritos").submit(function() {

        $.ajax({
            type: "POST",
            url: 'enviar_atualizar.php',
            data: $(this).serialize(),
            success: function (data) {
                // Inserting html into the result div
                $('.resultado_'+formID).html(data);
            },
            error: function(jqXHR, text, error){
                // Displaying if there are any errors
                $('.resultado_'+formID).html(error);
            }
        });
        return false;
    });
});

O $(this) vai se referir ao elemento que recebeu o evento submit, no caso o próprio <FORM>
Comment: editei minha resposta, está retornando um erro no console
Comment: @WagnerMartinsBodyboard formID não foi definido, de onde deveria vir esta var? Dê detalhes.

Seriealize() Aajax com problema


HTML5 pattern for validating IP with mask

Question: I'm trying to create a HTML5 pattern for input text with and IP address and mask together, like this:
10.120.15.30/28 or 184.108.40.206/24
I found one html5 pattern at http://html5pattern.com/Miscs but is only for IPv4 without mask
<code>((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}$
</code>
I tried add before
<code>    (\/).((([0-2])|(0-9))|(3[1-2]))
</code>
but is not working. Any ideas?
Comment: As webpage to test the pattern there is http://html5pattern.com/Make_Your_Own, is where i'm testing the patterns
Answer: <code>((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}/(?:\d|[12]\d|3[01])$
</code>
Demo.
I simply added <code>/(?:\d|[12]\d|3[01])</code>to the pattern you provided:
<code>/          // match a slash
(?:        // then match either one of
    \d     // a single digit
|
    [12]\d // any number from 10 to 29
|
    3[01]  // 30 or 31
)
</code>
Comment: Aren't the prefixes only 24-31 as in http://en.wikipedia.org/wiki/Subnetwork#Subnet_and_host_counts, i.e. `(/(2[4-9]|3[01]))?`
Comment: I think the first sollution was the correct, as I could remark a single host as xx.xx.xx.xx/32
Comment: Perfect! I was only using html5patterns, but with regex that works like a charm. Thank you! :)


How to calculate the birth date ? And sum of digits of n?

Question: Naga was born in the year 19n. 'n' is a two digit number. In the year 2014 he completed 'n' years  of his age.
The sum of the two digits of 'n' is-
Let Naga was born -19XY
Then how to corelate the value of n to find answer??.
Comment: Hint: What is the expression from which you can calculate his age (in 2014)? We know that it's $n$, but is there another way to express it?
Comment: As you can see, "the year 19n [where] 'n' is a two digit number" is a non-standard mathematical notation that is difficult to do arithmetic with. Can you rewrite it as a regular mathematical expression that you can do arithmetic with?
Comment: I am thinking  and taken it as n×n
Answer: 2014 - n = 1900 + n and solve for n.


Estrutura de tabela para sistemas de amizades em PHP

Question: Estou a desenvolver um sistema de amizades em meu sistema e gostaria de saber qual a melhor maneira de organizar a tabela que cuidará de tais registros amigos:
Já pensei em algo tipo:
Tabela "amigos" (apenas 3 colunas)
-----------------------------------
   id | usuario | usuarioamigo

Porém não sei se é a melhor maneira a se fazer e muito menos como poderia fazer a relação da consulta para saber se um usuário é amigo de outro usuário.
Qual a melhor maneira de se fazer isso e como fazer?
Comment: Primeiro você deve verificar se um usuário também pode ser um amigo, se sim, receio que um auto-relacionamento possa vir a resolver o seu problema.
Answer: Essa é a forma mais simples tendo usuario e amigo. Na consulta você verifica se ID do usuário combina com o ID do amigo e vice versa, em usuario ou em usuarioamigo
select * from amigos
where ( usuario = $IDUser or usuarioamigo = $IDUser )
  and ( usuario = $amigo  or usuarioamigo = $amigo  )

referência 1 , referência 2
Comment: @Igor, Sim está correta, não vejo motivo para evitar.
Comment: Acho que pude entender... Então essa organização da tabela `amigos` está correta?
Comment: Não seria uma boa ideia utilizar dois inserts?  `INSERT INTO amigos values(amigo_id, usuario_id) VALUES (70, 80), (80, 70)`. Pois eu tive problemas no meu servidor (acho que por causa do `OR`), que está deixando tudo muito lento!
Comment: @WallaceMaxters, também é uma opção, mas nesse caso serão muitas linhas duplicatas.


Windows10 GPO proxy setting applied without values

Question: I'm trying to set up proxy via AD GPO. I followed this guide and configured the IE10 setting in user preferences (screen in Italian):

When I log into an account for which the policy applies I see the proxy as enabled but the proxy host field is empty! If I disable the proxy option and run gpupdate /force it will be enabled again, so it seems the policy is received... But why only partially?

Client is Win10 Pro 19041.28.
Thanks
Answer: Try enforcing the policy looks like it's not applied.
alternatively you can use registry
go to User Configuration > Preferences > Registry and create 3 registry parameters in the following registry key:
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings]:

    ProxyEnable (REG_DWORD) = 00000001;
    ProxyServer (REG_SZ) = fileserver.wdc.ca:3112;
    ProxyOverride (REG_SZ) = 192.*;

Comment: Thanks, I tried setting the enforce flag but I've the same result. If I get no other options I'll go for the registry keys..
Comment: Using registry worked, thanks


Passing a struct with multiple entries in c++

Question: I am trying to pass a coordinate, which is defined as struct with 2 integer parameters (the struct is called coord) the following way:
UpdateB({0,0});

where the input argument is of type coord (i.e. in the above statement I am trying to pass a coordinate 0,0). UpdateB is some function. I am getting an error, any ideas what
the problem could be?
Comment: syntax errors, such as missing ;  }  {   etc. I think it doesn't like the curly bracket notation in UpdateB({0,0}), but I don't see what's wrong with it.
Answer: Make a constructor accepting two argumnets.
Pass it as follows:
MyFunc(Point2d(0,0));
Answer: Pavel's got it spot on. If you want to create the struct instance as you're passing it to the function, you'll need to make a constructor for it. Then create a new instance of coord as the argument you're passing to the function. For the struct, something like...
struct coord
{
    int x, y;

    coord(int xvalue, int yvalue)
    {
        x = xvalue;
        y = yvalue;
    }
};

...should do the trick. Then just run...
UpdateB(coord(x, y));

...where x and y are your values.
Comment: A better constructor declaration is with initialization list:

struct coord {
  coord(int xvalue, int yvalue) : x(xvalue), y(yvalue) {}
  int x, y;
}
Answer: The syntax you are using would be valid C++0x (uniform initializers) and valid C99 (compound literals).
In C++03 you have to use either user-defined constructors or helper functions, the curly-brace syntax only works for aggregate initialization.
If your struct is a POD and you need it to stay one, you have to use a helper function:
coord make_coord(int x, int y) {
    coord c = {x, y};
    return c;
}

UpdateB(make_coord(x, y));

Otherwise, as already mentioned, give it a constructor
Comment: I have seen before `UpdateB( (coord){1,2} )` working in g++ (no need for the helper function), but I doubt whether this is proper C++...
Comment: @David: In C++98/03 it isn't, g++ supports compound literals as an extension.
Answer: Pavel Radzivilovsky's solution is right (+1).
However you have to know that the coming new standart C++0x will allow the syntax of your example if you provide a constructor with two parameters (and maybe if you provide a constructor with initializer list but that's not useful here).
This feature is already available in GCC starting v4.4, if you use it you can enable it by enabling C++0x.


is there any way to use .indexOf to search a javascript array in mirth?

Question: I am trying to find a string in a javascript array in the transformer of a mirth channel. Mirth throws an error when I try to use indexOf function. My understanding is that indexOf is something that browsers add in, rather than a native part of the javascript language itself. ( How do I check if an array includes an object in JavaScript? )
So is array.indexOf just not supported in Mirth? Is there any way to use .indexOf in Mirth? Maybe an alternate syntax? Or do I need to just loop thru the array to search?
Answer: This is how I search arrays in a Mirth js transformer:
var Yak = [];
Yak.push('test');

if(Yak.indexOf('test') != -1)
{
    // do something
}

Does this give you error?
Comment: turns out it was JVMs prior to 6.23 where this was broken. After playing around some more, and comparing Java versions, I can say that we have indexOf working on 6.23 or higher. I think it was down somewhere around 6.04 where it was still broken.
Comment: This method gives me an error. We're using Java 6, build 23, with Mirth 1.8.2. If you're using something newer, please let me know.
Comment: I am using Mirth latest (2.2.1).
Answer: Mirth uses the Rhino engine for Javascript, and on some earlier versions of the JVM, indexOf appeared to not be supported on arrays. Since upgrading our JVM to 1.6.23 (or higher), indexOf has started working. However, we still have legacy code that, when searching arrays of strings, I just use a loop each time:
var compareString = "blah";
var index = -1;
for (var i = 0; i < myArray.length; ++i)
{
    if (myArray[i] == compareString)
    {
        index = i;
        break;
    }
}

If you need to do this frequently, you should be able to use a code template to manually add the indexOf function to Array.
Set the code template to global access, and try out something like this (untested code):
Array.prototype.indexOf = function(var compareObject)
{
    for (var i = 0; i < myArray.length; ++i)
    {
        // I don't think this is actually the right way to compare
        if (myArray[i] == compareObject)
        {
            return i;
        }
    }

    return -1;
}

Answer: var arr = ['john',1,'Peter'];

if(arr.indexOf('john') > -1)
{
    //match. what to do?
    console.log("found");
}
else
{
    console.log("not found");//not found .. do something
}

Answer: var i = ['a', 'b', 'c']

if(i.indexOf('a') > -1)
{
       ///do this, if it finds something in the array that matches what inside the indexOf()
}
else
{
    //do something else if it theres no match in array
}


Getting wrong values in HashMap

Question: I have created HashMap for storing Brand:Car key value pair and inserted two car brands and their details.But on invoking .get(key) method I'm getting last stored values.
public class MapTest {
public static void main(String args[]) {

    MapTest map=new MapTest();
    map.test();

}
public void test() {
    HashMap<String,Car> vehicle=new HashMap<>();
    Details def=new Details();
    Car car=new Car();
    car.name="Mustang";
    def.model="SportsRoof";
    def.model_no=1969;
    def.color="Blue";
    car.features.add(def);
    vehicle.put("Ford",car);
    car.name="R8";
    def.model="Coupe";
    def.model_no=2009;
    def.color="Black";
    car.features.clear();
    car.features.add(def);
    vehicle.put("Audi",car);
    System.out.println(vehicle.get("Ford").name);
    System.out.println(vehicle.get("Ford").features.get(0).model);
    System.out.println(vehicle.get("Ford").features.get(0).model_no);
    System.out.println(vehicle.get("Ford").features.get(0).color);
}

Other Clsses
public class Car {
    String name;
    List features=new ArrayList<>();
    public Car() {

    }
}
public class Details {
    String model;
    int model_no;
    String color;
    public Details() {

    }
}
}

Output
R8
Coupe
2009
Black
Answer: You're reusing the same car object over and over again.  So, you've really not inserting different cars into the hashmap, you're inserting the same car object.  However, an unintended side effect is that when you change, e.g. the name of the car, you change it everywhere in the map.
So, your code should look something like this:
HashMap<String,Car> vehicle = new HashMap<>();
Details def= new Details();
Car car = new Car();
car.name = "Mustang";
def.model = "SportsRoof";
def.model_no = 1969;
def.color = "Blue";
car.features.add(def);
vehicle.put("Ford",car);
// create a new Car object
car = new Car();
car.name = "R8";
def.model = "Coupe";
def.model_no = 2009;
def.color = "Black";
car.features.clear();
car.features.add(def);
vehicle.put("Audi",car);

Comment: So I have to create two car objects ?
Answer: In Java objects are stored based on references. You are initializing car variable only one time and assigning it to all keys of your Map.
You need to create different Car instances for different keys in your Map. And you need to create different instances of class Details too.

Getting wrong values in HashMap


Link which leads to comments

Question: I simply wish to put a link at the head of node, which leads at the beginning of comments.
I did not find clear answer on this subject.
I try this, but does not work :
<?php print l('
title
', '#comments', array('html' => TRUE)); ?>

Is there a solution under drupal?
Answer: Creating a link like this will not create the desired output. When looking at the l() function comments on the Drupal API page, the following is suggested to make internal anchors work:
l(t('Comments'), $_GET['q'], array('fragment' => 'comments'));

What happens is you tell Drupal to create a link to the current page, and add #comments as an anchor (fragment).
This means you can also link to the comments from other pages, by simply changing the $_GET['q'] parameter to the desired path.

Link which leads to comments


Do there exist vector spaces over a finite field that have a dot product?

Question: I've stumbled in the german wikipedia over the question if a vector space over a finite field exists, that has a dot product.
Definition of dot product
A dot product over a $\mathbb{K}$-vector space V is a mapping $F : V \times V \rightarrow \mathbb{R}$ which is...
... bilinear: $\forall a, a_1, a_2, b, b_1, b_2 \in V \forall \lambda_1, \lambda_2, \mu_1, \mu_2: $
$\begin{align*}
    F(\lambda_1 \cdot a_1 + \lambda_2 \cdot a_2, b) &= \lambda_1 \cdot F(a_1, b) + \lambda_2 \cdot F(a_2, b)\\
    F(a, \mu_1 \cdot b_1 + \mu_2 \cdot b_2)         &= \mu_1 \cdot F(a, b_1) + \mu_2 \cdot F(a, b_2)
\end{align*}$
... symmetric: $F(a, b) = F(b,a)$
... positive definite: $\forall a \in V: F(a,a) \geq 0 \land ( F(a,a) = 0 \Leftrightarrow a = 0)$
My try
Please correct my choice of words if you know what I mean and if you know how to write it in English. I am not used to write math texts in English.
$\mathbb{K} := \mathbb{Z} / 2 \mathbb{Z}$
Let $V$ be a $\mathbb{K}$-vector space over the set $\{0,1\}$.
$\mathbb{K}$ is a finite filed.
Define $\langle 0, 0 \rangle := 0$, $\langle 1, 0 \rangle := \langle 0,1 \rangle := 1$ and $\langle 1, 1 \rangle = 1$.
symmetry
$\langle, \rangle$ is symmetric per definition
bilinear form
$f(1 + 1, 1) = f(0,1) = 1 \neq 0 = 1+1 = f(1,1) + f(1,1)$
Is it possible to define a dot product for a bigger vector space / finite field?
(If the answer is yes, please give me an example)
edit: argh - $f(a,a) = 0 \Leftrightarrow a = 0$, but $f(a,b)$ can be 0. I always forget that :-/
Comment: Should not $F$ take values in $\mathbb K$? Either way, the notion of *positive* is not defined in finite fields, so you'll have to do without that axiom.
Comment: Indeed. It is in fact easy to prove that the [prime field](http://en.wikipedia.org/wiki/Prime_field) of an [ordered field](http://en.wikipedia.org/wiki/Ordered_field) is isomorphic to the rationals.
Comment: See [this question](http://math.stackexchange.com/q/49348/11619) for more discussion, why an inner product in a vector space over a finite field does not work. Basically it is what LVK says: we cannot set aside a subset of positive elements. You can study quadratic forms (or related bilinear forms) though, if you are not afraid of vectors being orthogonal to themselves.
Comment: ... But if you define $\langle 0,1\rangle=\langle1,0\rangle=\langle0,0\rangle=0$ and $\langle1,1\rangle=1$ you do get something that seems to work. But only for the one-dimensional space - otherwise the problem of the set of "positive" elements not being closed under addition raises its ugly head.
Comment: @JyrkiLahtonen: You seem to be saying $\langle p,q\rangle=pq$. Are you suggesting to call the quadratic residus positive and the non-residus negative? That would be weird, but is the only notion I can think of where "positive" is closed under _multiplication_.
Comment: @Marc: I only wanted to replace OP's map with a bilinear one (for the field of two elements). Your idea of declaring squares as the set of positive elements is interesting, but doesn't allow for more than 1-dimensional inner product spaces (AFAICT). Undoubtedly you knew that :-)
Answer: Certainly the "obvious" inner product of $(v_1,\dots v_n)$ with $(w_1,\dots w_n)$ given by $\sum_n v_n w_n$ is defined for any (finite dimensional) vector space. It is symmetric and bilinear and fairly useful. It is used extensively, for example, when discussing linear codes over finite fields. (The codes are vector spaces!)
There isn't any reason to discouraged that the "positive definite" condition is missing. There are many interesting inner product spaces where the inner product is not positive definite... even over $\mathbb{R}$! The inner product of Minkowski space is not positive definite, for example, and this is the setting for special relativity.
Positive definiteness is kind of a "Euclidean ideal" that we would hope for, but the Minkowski space example shows that nature isn't always Euclidean, and that non-positive-definite inner products arise naturally.


Converter fracao de hora no formato hh:mm:ss

Question: Meu conjunto de dados de horarios esta armazenado na variavel time = [0., 0.08333333,   0.16666667,   0.25, 0.33333333, 0.41666667, 0.5 , 0.58333333,  0.66666667,  0.75,   0.83333333,   0.91666667, 1. , 08333333, 1.16666667]
Alguem sabe me dizer se existe uma maneira simples de converter isso no formato hh:mm:ss?
Eu tentei criar uma funcao, mas esta dando erro:
import datetime as dt
from datetime import timedelta

def time2dt(time):

    seconds = int(time*60*60)
    minutes, seconds = int(divmod(seconds, 60))
    hours, minutes = int(divmod(minutes, 60))
    return dt.datetime(hours, minutes, seconds) + dt.timedelta(time % 1)

    dates   = [time2dt(time[i]) for i in np.arange(len(time))]
    datestr = [i.strftime('%H:%M:%S') for i in dates]

TypeError: int() argument must be a string or a number, not 'tuple'
Comment: Fazendo isso, aparece um outro erro: AttributeError: type object 'datetime.time' has no attribute 'time'
Answer: Esse erro está acontecendo por que  o divmod que você está chamando não devolve um número - para ter um resto de divisão em Python, use simplesmente o operador % . Divmod devolve a parte inteira e o resto da divisão - mas não é por isso que todas as outras funçoes (o "int" em particular) vai poder trabalhar automaticamente com uma sequência.
Faça o programa por partes, sem esperar que a linguagem seja "mágica" (por que ela não é, ela é bem racional), e você vai ter o resultado esperado - mais pra frente, conforme você tiver mais desenvoltura, pode se preocupar em querer encurtar as linhas de código:
minutes = time // 60
seconds = time % 60

em vez do incorreto minutes, seconds = int(divmod(time, 60)) que você tem aí.
(o  // é o operador de divisão "inteira" que trunca o resultado).
Além disso, outro problema que você tem mais pra baixo é tentar criar um datetime.datetime passando apenas horas, minutos e segundos: datetimes precisam do dia, mes e ano.  - crie um objeto datetime.time com dia, mes e ano, e depois sim, combine como desejar com outros objetos.
E por fim, não diretamente relacionado com seu problema - mas você não deveria mais estar usando Python 2.7 - em menos de dois anos essa versão estará completamente sem suporte de nenhum tipo - faz quase 10 anos que foi lançada. As versões 3.x do python são as atuais e tem várias facilidades e novas funcionalidades.
Comment: Obrigada! Eu fiz umas alteracoes aqui, e agora esta funcionando...quanto ao uso do python, eu estava usando a versao 3.6, mas tive problemas, travava com frequencia e por isso acabei voltando pra versao mais antiga mas com certeza, em algum momento, acabarei voltando a ela novamente


How to mock inner function while testing the outer function in JEST

Question: I am writing an express JS app with TypeScript using functional programming so I don't have any classes and methods in my service.
I have a method called "getData" in one file:
export const getData = async () => {
    const filePath = path.join(__dirname, '../../data/movies.json');
    return MOVIE_METADATA === undefined ? readJsonDataFromFile(filePath) : MOVIE_METADATA;
}

I am using this method in my service in another file like this:
const findMovieById = async (movieId: string) => {
    const movies: any[] = await getData();
    return movies.find((movie) => movie.imdbId === movieId || movie.id.toString() === movieId);
}

I want to test my service method "findMovieById" and I want to mock the inner method "getData" to return a mocked response however I am unable to do that.
I see a lot of people using SpyOn but that works with a class and then a method but I only have a method.
I also tried jest-mock-extended npm package but the problem remains the same.
I would appreciate it if you could help me here or point be to some resources where I can learn how to mock inner functions while testing outer level functions.
Answer: The test with mocks of getData can be implemented like this:
import * as dataService from "../getDataService";
import { findMovieById } from "../findMovieService";

it("should work with original implementation", async () => {
  const movie = await findMovieById(1);
  expect(movie.title).toEqual("Movie with id 1 from ORIGINAL function");
});

it("should work with mocked implementation", async () => {
  jest
    .spyOn(dataService, "getData")
    .mockResolvedValue([
      { imdbId: 1, title: "Movie with id 1 from MOCKED function" },
    ]);
  const movie = await findMovieById(1);
  expect(movie.title).not.toEqual("Movie with id 1 from ORIGINAL function");
  expect(movie.title).toEqual("Movie with id 1 from MOCKED function");
});

You just need to spyOn the getData function and mock the implementation with mockResolvedValue.


FAPI #prefix YAML filter tag

Question:   button_submit:
   '#prefix': '
text<button>button text</button>'
   '#suffix': '
'
   '#value': Send
   '#type': submit

I have the code above in YAML form. When I edit the code, I see the button tag; when rendering, only the following markup is left.

ALGOasd
<input id="edit-button-submit" class="button js-form-submit form-submit" type="submit" value="Send" name="op" data-drupal-selector="edit-button-submit">

It´s clear that I have some filter, but I can't find it out. I also tried putting a <button> in a container item, but the same thing happens.
Why does this happen? How can I fix it?
Answer: You need to include the #allowed_tags property which is applied to #markup, #prefix, and #suffix. (See: Pass raw html to #markup)
button_submit:
  '#prefix': '
text<button>button text</button>'
  '#suffix': '
'
  '#value': Send
  '#type': submit
  '#allowed_tags':
    - div
    - button

FAPI #prefix YAML filter tag


How to assess if two electricity consumption sets are corresponding?

Question: I need to compare two outputs of electricity consumption measurement system coming from one source (one company) and assess whether they are corresponding. If not, it may prove that one of the systems may be faulty.
The outputs are in form of hourly consumption data sets, 8784 entries, over the period of one year.
Besides correlation, what other methods can I use to achieve this task?
Comment: The first option: two different systems measure electricity consumption in one company/building. Is "correspondence" a proper name?
Comment: When you say "corresponding" do you mean are the two sets of measurements measuring the same thing, perhaps with some level of discrepancy, or do you mean measuring two different things that should be similar in their behavior? For example, two different monitors taking electricity consumption readings for the same building, or two different monitors in two different buildings that are reasonably close together?
Answer: Since these are a time series, you have to be careful. If both time series are increasing (or decreasing) over the year, a straight-up correlation will be misleading. That's how various websites show clever correlations between things like coffee production in Peru and movies in which Kevin Bacon starred. Have you looked at this question in this forum?
Would it be useful to aggregate to larger time periods? Have you already looked at the average usage per hour, per day, per month for each over the year? Are they reasonably close, just eyeballing it? Then there are tests for whether two groups have the same mean/variance, and it sounds like you have a paired example, that you can look at by week and by month.
There are also time-series-specific comparison methods, as pionpi_ says in their answer.
The key issue with time series is that they have autocorrelation: things tend to be the same from day to day and week to week, etc. If yesterday was hot, today will likely be hot. July temperatures are more like June temperatures than January temperatures. Etc. So each hour's electricity usage is not independent of the previous or next hour's usage.
Answer: there are many measures of distance for time series data. see Fu 2011 and Liao 2005.


What is maximum number of variables that we can use to run a cluster analysis?

Question: To do one clustering analysis, the model that I developed contains some 30 variables. I need to run this clustering for some 2-3 million data points. I need to know whether number of variables that I intend to use (30) is just too many? Would my result be impacted 'coz of large number of variables?
Also there would be issues with processing limitations of tool (spotfire) that I am using for this exercise. But that is secondary concern at this moment.
Answer: What makes you think there is a limit? Most clustering algorithms just use distance functions, and these usually are linear in the number of variables.
However, not every result will be meaningful. There are issues associated with high-dimensional data (albeit most people would consider 30 to be just "medium" dimensionality).
The most obvious one is that the notion of distance itself is often rather meaningless. Say, your first variable is "shoe size", the second is "age". How can you expect an euclidean distance function to perform a meaningful distance computation?
However, even when you are in the situation that the euclidean distance is meaningful, simple methods such as k-means and "hierarchical clustering" may not work very well due to the low contrast in distances. Others may be hard to parameterize, as you need to give a distance threshold. So you will need more advanced methods (and spotfire probably only offers the most basic ones, unfortunately).
You might however want to check out:

Subspace clustering (Wikipedia), in particular a survey article such as:
Kriegel, Hans-Peter; Kröger, Peer; Zimek, Arthur (2009), "Clustering high-dimensional data: A survey on subspace clustering, pattern-based clustering, and correlation clustering", ACM Transactions on Knowledge Discovery from Data
Correlation clustering (same wikipedia article and survey), when you have correlations in your attributes
Problems of mining high-dimensional data in general, in particular the "curse of dimensionality" (link is to Wikipedia again, but a different article). Many people think that you cannot mine high-dimensional data at all, but there is research that shows that high-dimensional data can work, or not (again from Wikipedia. time series are a particular type of high-dimensional data - often in the thousand dimensions - that works very well, in the first article the authors touch the issue of distance functions):
Houle, Michael E.; Kriegel, Hans-Peter; Kröger, Peer; Schubert, Erich; Zimek, Arthur (2010). Can Shared-Neighbor Distances Defeat the Curse of Dimensionality? Scientific and Statistical Database Management.
Bernecker, Thomas; Houle, Michael E.; Kriegel, Hans-Peter; Kröger, Peer; Renz, Matthias; Schubert, Erich; Zimek, Arthur (2011). Quality of Similarity Rankings in Time Series. Advances in Spatial and Temporal Databases
Comment: Your notion "k-means and "hierarchical clustering" may not work very well due to the low contrast in distances" is interesting. Could you elaborate a bit?
Comment: Have a look at "When is "nearest neighbor" meaningful?" by Beyer, Goldstein, Ramakrishnan. And after all, k-means is based on "nearest cluster center", and hierarchical clusering on "merge nearest two clusters".
Comment: @Anony-Mousse, I understand what you are suggesting on distanced being meaningless if your variables are at different scales. All of my 30 variables will fall in two categories. For one set (15 variables) values will be btw 0-50 and for other set values (dollar amounts) would be btw 0-100K. Is there way I can normalize variables so that both set of variables are assessed on same scale? For analysis, all variables are equally important, so analysis should treat distances at same scale.
Comment: Partially. If the values are on different scales, even a 2D distance can be meaningless. Say somone has houshold size 3 people, and donated $100, and the other household is 2 people, and they donated $100000. The dollar amount completely dominates the difference in household size.
Once you get to more variables, read up on the curse of dimensionality. Often (but not necessarily, see Houle et al.) all distances appear to be the same, and somewhat random.
Answer: If only for crossvalidation purposes, it would seem to make sense to choose a random subset of your millions of cases.  But 30 variables shouldn't be a problem even with, say, several thousand, let alone with hundreds of thousands or millions.  You have more than enough information to map out the different relationships you want to explore.
Comment: Seeing as there are so many rows of data, the suggestion to set aside a subset for training and then use the rest for crossvalidation seems very sensible.
Comment: Thanks Ronaldo. Your comment gives me confidence in model that I prepared to run cluster analysis on.


Notation for functions vs. numbers

Question: I understand that $f$ represents a function while $f(x)$ represents the value of a function, but while I can easily see how to apply this convention to work with functions instead of numbers in some circumstances, e.g.,
$$\sin(x)\text{ becomes } \sin\text{,}$$
$$\cos(x)\text{ becomes } \cos\text{, and}$$
$$g(x)\text{ becomes } g\text{,}$$
it isn't clear to me how to to express the functions corresponding to the numbers
$$x^{2}\text{, or}$$
$$2\cdot x\text{.}$$
Short of defining new symbols, like $S$ or $I$ (which I've seen for the function corresponding to $x \mapsto x$), can one say things like $$\left(\cdot\right)^{2}\text{ for }x^{2}\text{, or}$$
$$2\cdot \left(\cdot\right)\text{ or }2\left(\cdot\right)\text{ or }2\cdot\text{ for }2\cdot x\text{?}$$
What is the general idiom for expressing such functions concisely?
Comment: Informally, there is nothing wrong with $x^n$. For the formal way, see http://en.wikipedia.org/wiki/Function_%28mathematics%29#Notation
Answer: A good question. There are various approaches.
Formally, in simple cases such as the ones in the question, you can get away with giving a name to the identity function $\mathrm{Id}$ which returns its argument unchanged. Then, by analogy with, say $\sin^2$, the function that squares its argument becomes $\mathrm{Id}^2$ and the function that doubles its argument is $2\,\mathrm{Id}$.
If you're really devious, you can even decide to name the identity function "$x$", and declare that everything is a function of a hidden variable with some other name. That can quickly get confusing if you have other named functions around, though. If your audience are algebraists, they will probably like this approach.
The full-featured bells-and-whistles solution, however, is to use the applied lambda calculus, in which the function that squares its argument is notated $(\lambda x.x^2)$ or $(\lambda y.y^2)$ or $(\lambda z.z^2)$ ... you get the pattern. The variable that follows the $\lambda$ is bound by the function expression and not visible outside. Thus you can write $(\lambda x.x^2)(20)=400$. The notation also allows you to write functions that take functions as arguments, such as $(\lambda f.f(42))$, or functions that return other functions, such as $(\lambda x.(\lambda y.x+y))$.
The lambda calculus is one of the bedrock formations of computer science, but not much used by contemporary mathematics -- even though it was originally invented as a possible general foundation for mathematics before computers were even invented. Mathematics sometimes uses notations such as "... the function $x \mapsto x^2$ ..." for $(\lambda x.x^2)$, but this $\mapsto$ notation is rarly used inside larger expressions.
Comment: You can quickly run into trouble that way, however, because now you're treating juxtaposition as _function composition_ when you write $\sin x$, but as _pointwise multiplication_ in $2x$ (and implicitly in $x^2$). That's bound to create confusion sooner or later if you do it with abandon. For cases such as this I think it will be clearer to write everything with explicit $x$'s and then eschew $(\cdots)'$ in favor of $\frac{d}{dx}(\cdots)$. In the end, when you're writing for humans, _clarity_ should be the final arbiter.
Comment: @rax There's some ambiguity in $\operatorname{Id}^2$: it could mean either the pointwise product of the identity function with itself, or the composition $\operatorname{Id} \circ \operatorname{Id}$ (the second one happens to $\operatorname{Id}$ itself). I guess the standard interpretation depends on context.
Comment: The "devious" approach you describe would seem to be the most convenient (and in practice, widely used). E.g., when one writes (or thinks) $$f'(x)=[\sin x + x^{2}\sin(x+1)]'$$when$$f(x)=\sin x + x^{2}\sin(x+1)$$ and then subsequently uses theorems about the combination and composition of *functions* to write, say (just as an illustration), $$f'(x)=(\sin x)' + x^{2}\cdot[\sin(x+1)]'+2x\cdot\sin(x+1)$$ or
$$f'(x)=(\sin x)' + x^{2}\cdot\sin'(x+1)\cdot(x+1)'+(x^{2})'\cdot\sin(x+1)$$
isn't one (or at least *shouldn't one be*) doing just that: treating $x$ as the *function* $\mathrm{Id}$?
Comment: True -- I was imagining that one declares once and for all that one is working with pointwise multiplication rather than composition by saying something like "we're working in the commutative algebra of functions".

Notation for functions vs. numbers


How do you distinguish an upper mordent from a trill?

Question: I recently learned of the upper mordent. (first ornament in this image from Wikipedia)

To me, it looks identical to the trill from the table of ornaments I'm familiar with:

When encountering this symbol, how do you determine whether it is an upper mordent or a trill?
Answer: It is a question of period and context, as there was not really a standard way of notating ornaments for a long time and even what existed changed over time. In Bach's notation for example the upper mordent (in german we call it "prall trill") did not exist, and both the short and the long squiggle were used for a trillo (also in fact I do not know of any ornament table that includes the upper mordent). In later music (classical, romantic) the short squiggle became pretty exclusively the upper mordent (in that times people the upper mordent seemed to be quite popular).
So with sufficiently recent music you are quite safe in taking the short squiggle as upper mordent. For baroque era the safest bet would be to get an ornament table from the composer or a composer from a similar time and area as reference.
If you need a nice collection of ornament tables and specifications in baroque keyboard music have a look at this article:
https://publish.iupress.indiana.edu/read/jean-henry-d-anglebert-and-the-seventeenth-century-clavecin-school/section/3ab36d99-c045-458e-87a0-568f3e0bbe49
EDIT: Also of course it depends on the edition. Does the edition try to replicate the composers notation? Or does it try to translate it to modern notation? Or is the editor just doing what he wants?


Finding generating function in a closed form : $\sum_{n=1}^N(3n^2-10n)\cdot2^n$

Question: I'm currently stuck on the last section of my assignment...
It asks me to find a generating function in a closed form
the only part im struggling is $\sum_{n=1}^N(3n^2-10n)\cdot2^n$ or $\sum_{n=1}^N(\text{quadratic}(n))C^n$
I have no clue on how to convert this...
any assistance would be appreciated thank you
Answer: Hint. Here is a general route.
We assume $x \ne 1$. One may recall the standard geometric evaluation:
$$
1+x+x^2+...+x^n=\frac{1-x^{n+1}}{1-x},\tag1
$$ then by differentiating $(1)$ we have
$$
1+2x+3x^2+...+nx^{n-1}=\frac{1-x^{n+1}}{(1-x)^2}-\frac{(n+1)x^{n}}{1-x}, \tag2
$$ multiplying $(2)$ by $x$ and differentiating once more gives
$$
1+2^2x+3^2x^2+...+n^2x^{n-1}=\frac{d}{dx}\left(\frac{1-x^{n+1}}{(1-x)^2}-\frac{(n+1)x^{n}}{1-x}\right). \tag3
$$
Comment: would it be a different story if $\sum_{n=0}^N(3n^2-10n)\cdot2^n z^n$ or $\sum_{n=0}^N(\text{quadratic}(n))C^n z^n$ cause thats what we've been doing
Comment: @MathNoob It is the same story, you just have to consider $\sum_{n=0}^N(3n^2-10n)\cdot x^n$ then put $x=2z$ since $2^nz^n=(2z)^n$.


Dell VRTX - slow cluster shared storage

Question: I have a brand new Dell VRTX box set up as a Failover Cluster running HA Hyper-V virtual machines.  This is my first time setting up clustering, and my first time with one of these boxes, so I'm sure I've missed something.
The virtual machines are experiencing high disk latency and bad performance when accessing their VHD(x) files located on a Cluster Shared Volume.
The VRTX has 10 x 900 GB 10K SAS drives in RAID 6 configuration, and the VRTX has the redundant Shared PERC 8 controllers.  Both blades have full access to the virtual disks.  There are two M520 blades installed, each with 128 GB RAM.  MPIO is configured for the PERC 8 controllers.  Operating system on the blades is Server 2012 (NOT R2).
The RAID 6 array is split into a small (8 GB) volume for cluster quorum witness and a large (6.5 TB) volume for a Cluster Shared Volume (mounted on the nodes as C:\ClusterStorage\Volume1)
An example of slow disk access:  logging into a Server 2012 VM and having Server Manager come up automatically.  Disk access goes to 100%, with write speeds at 20 MB or so, read speeds of 500 KB or so, and Average Response Time of over 1000 ms, sometimes spiking at 4000-5000 ms or so.  It's the latency that really worries me.
Is there something specific I should look at in my configuration?  It doesn't seem to matter whether I use VHD or VHDX, dynamic or static.
Comment: Have you actually formally benchmarked it?
Comment: @Chopper3 - Well, not really.  I tried running a few different disk benchmark programs on the blades themselves, but couldn't figure out how to get them to benchmark a volume mounted as a directory, and their write tests were destructive.  I bet I could run one of them on a VM though, with a new VHD.  I'll try that.
Comment: You could try using IOmeter, as it's able to create a test file w/ a size you choose (specified by # of sectors, 512 bytes each for that system).
I'd also recommend checking the latency that's reported in PerfMon if you're looking at the data in TaskManager right now - I don't know what data its graphs are based off of, but I personally wouldn't trust it alone.
Also, if this is a brand new unit, don't be afraid to call support. They've likely seen this problem before, and would be happy to help work out the kinks.
Answer: This:

Fault Tolerant Shared PERC 8 Card Configuration — [...] The default cache policy for
  virtual disks created in this configuration is write-through. In this
  mode, write completion information is returned to the host after the
  data is written to the disk.

is the ultimate performance killer. Change the cache policy to write-back if it is supported for your application and does not result in possible inconsistencies within the written data. Note that I have no idea if and by which mechanism the PERC8 cache is being mirrored to the other instance. As the cached data needs to be accessible from both controllers, it obviously would be necessary for consistency.
Comment: It would appear that write-through is the only method supported.  I attempted to create an additional virtual disk and the only choice it gave me was write-through.
Comment: @NorbyTheGeek try triggering Dell support about this. Virtualization loads on non-writecached controllers with HDD arrays are known to perform poorly due to a high amount of synchronous writes they incur.
Comment: If you actually did turn on local caching in the controllers, that would invalidate the cluster file system that you're trying to use, which is probably why you're not seeing the option to do it.  If you want to use CSV, any caching has to be coherent across all the hosts that have access to the volume.
Comment: @JakeOshins there are cache mirroring mechanisms, mostly seen implemented in dual-controller storage appliances. I have no idea if the PERC8 has any support for cache mirroring.
Comment: Yes, that's why I made a distinction between local caching and coherent caching.
Comment: According to Dell Support, the dual fault-tolerant configuration does not support write caching.  Only the single controller configuration supports caching.  Disappointing, for sure.  I am following @Erik and his Dell forum threads for workarounds / updates.
Answer: I have experienced the exact same performance issue with a VRTX with the Dual SPERC8. What I have done to work around this at the moment is, change the dual config to a single config. This way I am able to use write-back, which performs way way better.

The exact steps:

Remove the second SPERC 8 controller
Remove the second expander
Re-cable the internal SAS connections
Downgrade chassis to 1.25 (works the same as upgrading, no special steps needed)
Delete all VD's (backup data/VM's if needed)
Power cycle entire VRTX (remove and reconnect power cables to be sure)
create VD('s) with write-back enabled

To see the performance difference check this/my thread at:
http://en.community.dell.com/support-forums/servers/f/906/t/19587459.aspx
Update:
Test results:
Dual PERC / RAID6 / Write Through: Read 2500 MB/s Write 200 MB/s
Dual PERC / RAID10 / Write Through: Read 2500 MB/s Write 400 MB/s
Single PERC / RAID6 / Write Back: Read 2500 MB/s Write 2700 MB/s
As long Dual PERC is bound to Write Through policy, I would stick with a Single PERC setup
Comment: Thanks for adding specific performance data, although it typically would not be about plain throughput but the number of IOPS you can do with the setup. The most important and most revealing sentence from the Dell Support reply to your Dell Forums post is ***"The VRTX is not a full-featured storage appliance"***. They really should post that prominently to the product page and into tech specs.
Comment: @syneticon-dj  I have contacted support and they recognize/are aware of this performance issue. The specialists, so they say, are looking into this issue. I am currently waiting for a troubleshooting and performance tuning guide for the Dual Controller setup.
Comment: This rather seems like a design decision than a support issue. I am curious about how they are going to "fix" it, assuming the hardware as well as the firmware are coming from LSI.
Comment: I received an official reply by Dell. They admit that a Dual PERC setup is not suitable for any virtual environment. They also recognize that Dell sales department wasn't correctly trained on this configuration. So @NorbyTheGeek maybe you need to work something out with Dell as well. See my earlier mentioned thread for some more details.
Comment: I have been following your Dell thread, and this unfortunately is the answer.  The process went fine, I did not need to delete the VD's, just downgrade / upgrade the CMC firmware.  With the single SPERC8, write caching is enabled and performance is greatly improved.
Answer: It is no longer required to remove the second SPERC controller to be able to use write-back instead of write-through as described in Erik's post. You can now disable the second PERC8 controller from the CMC. In the current firmware (1.35), the second disabled controller can be set as disabled and requires manual intervention to activate if the primary active controller were to fail. The usefulness of this is not really detailed in the patch notes, but this "fix" is meant to allow people to enable Write-Back and get rid of the abysmal performance you have when using both controllers in Write-Through.
Automatic failover (cold failover, causing disconnect) is a feature that will be release later. A lot later will be the actual "active/active" firmware update, which would allow "live" failover without downtime.
Steps:

Download VRTX CMC firmware version 1.35 or higher.
Shut down all your blades.
In the CMC interface, press "Chassis Overview > Update".
Select both checkboxes for the CMC controllers in the "CMC firmware" heading and press "Apply CMC Update".
Enter the location of the CMC firmware file and Apply it.
The CMC will show you its progress. Uploading takes about 8 minutes, applying the update a few minutes more. The CMCs will reboot after applying the update and you will get kicked out of the webinterface.
Once the CMC has rebooted, browse to the "Storage > Controllers > Troubleshooting" section.
For the SPERC of your choice, select the "Disable RAID controller" option and apply. This will reboot your storage component.
Once rebooted, go to "Storage > Virtual Disks > Manage" and select "Edit: Write Policy" and pick "Write Back" instead of "Write Through" for all your virtual disks (unless you have a reason not to).
The change above will be carried out immediately, but it is still suggested to reset the CMC once more under "Chassis Overview > Power > Control" with "Reset CMC (warm boot)".
Boot your shut down blades.

This will allow you to have a second PERC8 installed in your VRTX, in case the other fails. But you will have to do a manual intervention to fail over in case of failure. I suppose this is primarily meant for hard to reach locations (remote offices without IT staff or easy access for Dell support technicians). This is also what we use it for.
Hopefully by end of the year we will have the automatic failover feature and then in the course of next year the true active/active config with write-back enabled (synchronized caches). I'm not going to hold my breath for the synchronized cache firmware fix... I suspect that won't be an easy one for Dell.
Answer: Install VirtuCache in ESXi (in each VRTX blade) and have it cache to a NVME SSD in PCIe form factor that is local to the host or you can cache to host RAM. VRTX has plenty of PCIe slots,  so insert a $400 1.6TB Samsung PM1725 NVME SSD in one of the slots and use it as cache media with VirtuCahe. More details here https://virtunetsystems.com/improving-storage-performance-of-dell-poweredge-vrtx/

Dell VRTX - slow cluster shared storage


Stretching iframe in HTML5 in display:Fixed

Question: I was trying to stretch an iframe to all page and I maded with the next post
https://stackoverflow.com/a/7011716
But below of the frame, I would like to add some buttons, something like this:

        <button ... />
        <button ... />

But all the time the iframe covers all the web page and I have no way to show the small  until bottom or below of the iframe using 25px.
Answer: Change this:
#wrap { position:fixed; left:0; width:100%; top:0; height:100%; }

to this:
#wrap { position:fixed; left:0; width:100%; top:0; bottom : 35px; }

Demo : http://jsfiddle.net/4BJ7f/
Answer: Then try to make iframe height not 100%. Make it smaller ;)
Take a look here - it's work.
Answer: Add buttons block inside #wrap and style absolute position.
html:

        <button>Button</button>
        <button>Button</button>

Css:
#wrap { position:fixed; left:0; width:100%; top:0; height:100%; }
#iframe { display: block; width:100%; height:100%; border:0}
#buttons {position: absolute; bottom: 0;height: 25px;}

http://jsfiddle.net/SQ6Fq/


Network Storage for Final Cut Studio Lab

Question: The university I work for is renovating our digital media lab and we are looking at implementing some sort of NAS for students working in Final Cut Studio. This will be used for class projects so after each semester the NAS will be erased for the next wave of students. In the past we relied on external hard drives however that was clumsy and there were cases of data loss. We are looking at some devices from drobo, netgear, etc instead of more enterprise level devices.
Has anyone had any experience with a situation like this and have any recommendations? We are not sure where to start looking and was wondering if there were any major performance issues with Final Cut. There will be about 15 computers in the lab that will use the nas.
Comment: Are you doing SD or HD?
Comment: Some of both, although it will be predominantly HD.
Answer: You're going to want to, at the very least, test out using Final Cut with a NAS (any NAS!) to make sure the throughput will support your needs.  It'll depend not only on the appliance used but also on the network between that appliance and your clients, and what bottlenecks may exist.  Also, depending on the number of clients, the NAS itself may be a bottleneck - 10 people doing simultaneously high bandwidth I/O to the same disk is sure to perform poorly.
Some back of the envelope calculations may help you here:

What's peak bandwidth/client needed?
Given that and one interface's speed (Gb? 10Gb? don't overlook bonding options) you can figure out how many clients each interface can support.
Each interface has to have enough disks behind it to support that same amount of I/O.

Now you've got some rough hardware specs to look for: gross network and disk capacities are a start.
Answer: For that many machines I would recommend a fibre channel array rather than NAS - especially if you are going to work on Hi-Def projects.  We are using a Fibrenetics array.  There is an Apple store in Hollywood that caters to the studio and broadcast facilities in setting up storage and Final Cut systems and is great with working within a budget.  They will help you with options for how to set this up.  We use them because of their expertise even though we are on the other side of the country.  Look up Melrose Mac (www.melrosemac.com) and ask for Sandy!
Answer: If Fibre-Channel makes you cringe from expense, you can get most of the same performance at a fraction of the (component) cost by using SAS. On 7.2K RPM disks I've been able to get 275 MB/s out of mine for largely sequential loads, and considering that Gigabit Ethernet is 125 MB/s that's pretty darned good. Even random writes (those 10 HD streams hitting disk simultaneously) were pretty respectable at around 60 MB/s. Using higher performance drives like 10K or even 15K RPM will get you more random performance. If you can afford Raid1, you won't deal with parity-calc overheads which should pump throughput up even more.
If you have been using external drives for this, I'm presuming you're using either USB (25MB/s) or possibly ESATA (275MB/s). If you've been putting up with USB performance, then a DroboElite/DroboPro or maybe a Drobo FS on GigE should give you plenty of performance. Just be sure to use fast disks, as random I/O will be the thing that will bring everything to its knees.
If you were using ESATA external drives, then you already have a performance expectation that's pretty high. In that case, the Drobo series may not be able to keep up, simply due to network-level resource contention if nothing else. GigE is 125 MB/s and it doesn't take many fast writers to saturate it. In this case it may be a better investment to pick up two or three of them and apportion students to the units as needed as a way to balance the load.


Form Authentication : Roles (MVC 4) C#

Question: I am trying to implement Forms Authentication in my Application. I various examples and looked at the samples and questions provided in this forum and ASP.net MVC but I just can't get it to work.
I manage to authenticate my user but the roles does not seem to work :-(
I have setup my Web.Config as follow :
<authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
In my Controller I set the Index page to AllowAnonymous and then check in there if the user is authenticated. If not then redirect to the login page..
[AllowAnonymous]
    public ActionResult Index(string sortOrder, string searchString,string currentFilter, int? page)
    {
        if (!Request.IsAuthenticated)
        {

            return RedirectToAction("Login", "Account");

        }
//Find all the employees
        var employees = from s in db.Employees
                       select s;
//Pass employees to the view (All works fine)
return View(employees.ToPagedList(pageNumber, pageSize));
}

This all is working 100%
My Login code looks like this :
 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(User user, string returnUrl)
    {
        var myUser = db.Users.Where(b => b.UserName == user.UserName).FirstOrDefault();
        if(myUser != null)
        {
            if(myUser.Password==user.Password)
            {
                //These session values are just for demo purpose to show the user details on master page
                //Session["User"] = user;
                ICollection<UserAccessLevel> levels = db.UserAccessLevels.Where(b => b.UserId == myUser.UserId).ToList();
                //Session["levels"] = levels;

                //Let us now set the authentication cookie so that we can use that later.
                FormsAuthentication.SetAuthCookie(user.UserName, false);

                return RedirectToAction("Index","Employee");
            }
        }
        ViewBag.Message = "Invalid User name or Password.";
        return View(user);
    }

I also have the following code in the Global.asax file :
 protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
    {
        if (FormsAuthentication.CookiesSupported == true)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                try
                {
                    //let us take out the username now
                    string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                    string roles = string.Empty;

                    using (TrainingContext entities = new TrainingContext())
                    {
                        User user = entities.Users.SingleOrDefault(u => u.UserName == username);

                        roles = "admin";//user.Roles;
                    }
                    //Let us set the Pricipal with our user specific details
                    e.User = new System.Security.Principal.GenericPrincipal(
                       new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
                }
                catch (Exception)
                {
                    //somehting went wrong
                }
            }
        }
    }

When I log in my FormsAuthentication_OnAuthenticate executes and everything looks good. My User is set and my roles in the session is also there...
But when I click on the details of my Employee/Index screen it takes me back to the login screen (I expect it to take me to the details of the employee I clicked because I am logged in and I am setup as an admin role)
Please can you assist me to try and get to the problem. I sat for more than 18 hours already trying to figure this out.
I already looked at these solutions and as you can see most of my code comes from there...
codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF
codeproject.com/Articles/342061/Understanding-ASP-NET-Roles-and-Membership-A-Begin
codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form
in case you need more detail about my code you can also download it from GitHub
https://github.com/Ruandv/Training/tree/FormsAuthentication
I will appreciate your assistance.
Comment: Can you post waht you have in your Authorize attribute class?
Comment: I dont have a custom Authorize attribute class. I am making use of the standard one.
Answer: If you go to your Database and look for the table that assigns roles to users (probably generated by SimpleMembership?), does your user have an "admin" role?
Looks like you're only assigning the role in the FormsAuthentication_OnAuthenticate method without actually setting it in the DB.
// Your method (...)
User user = entities.Users.SingleOrDefault(u => u.UserName == username);
roles = "admin";//user.Roles;

And, although I'm not entirely sure, [Authorize(Roles = "admin")] may be using your Role Provider and checking if the user has/doesn't have the role in the database.
Comment: Thank you for pointing the database part out. I added the role in the DB and everything worked. All that time wasted.

Form Authentication : Roles (MVC 4) C#


Iterating through a series to add a character to a string using a while loop. The loop never breaks though on full data. What can I do?

Question: I have created a function that iterates through a column of strings with two distinct exact lengths. When subsetting my data into 100, I have no problems, but when I run the function on the full data ~230K, the while-loop never breaks. Below is the function:
def add_dash(df):
    n = 0
    results = []
    while n <= len(df[:-1]):
        if len(df[n]) == 7:
            results.append(df[n][:3] + '-' + df[n][3:])
            n += 1
        elif len(df[n]) == 13:
            results.append(df[n][:4] + '-' + df[n][4:6] + '-' + df[n][6:9] + '-' + df[n][9:])
            n += 1
        else:
            pass
    return(results)

Because I've tested it on a smaller set, I can't think of why the loop wouldn't end on a larger set. Any insight will be greatly appreciated!
Comment: What if `len(df[n])` is not 7 or 13?
Comment: As a very basic debugging step, at the top of your loop, print `n` and `len(df[:-1])`.
Answer: As @JohnGordon pointed out, if len(df[n]) is not 7 or 13, you never update your value of n. To fix that:
def add_dash(df):
    n = 0
    results = []
    while n <= len(df[:-1]):
        if len(df[n]) == 7:
            results.append(df[n][:3] + '-' + df[n][3:])
            n += 1
        elif len(df[n]) == 13:
            results.append(df[n][:4] + '-' + df[n][4:6] + '-' + df[n][6:9] + '-' + df[n][9:])
            n += 1
        else:
            # Otherwise, n is always 0
            n +=1
    return(results)

Answer: you need to increase the 'n' value every loop
so:
while n <= len(df[:-1]):
    if len(df[n]) == 7:
        results.append(df[n][:3] + '-' + df[n][3:])
    elif len(df[n]) == 13:
        results.append(df[n][:4] + '-' + df[n][4:6] + '-' + df[n][6:9] + '-' + df[n][9:])
    n += 1
return(results)

Answer: Try the below code,
def add_dash(df):
    n = 0
    results = []
    while n <= len(df[:-1]):
        if len(df[n]) == 7:
            results.append(df[n][:3] + '-' + df[n][3:])
        elif len(df[n]) == 13:
            results.append(df[n][:4] + '-' + df[n][4:6] + '-' + df[n][6:9] + '-' + df[n][9:])
        else:
            results.append('')
        n+=1
    return(results)


Class add property on all objects in python

Question: I found an issue while programming on python. I have the class Dinero (money in english) which has all properties for the currency in DnD.
class Dinero:

    def __init__(self, copper_pieces, silver_pieces, electrum_pieces, gold_pieces, platinum_pieces) -> None:
        self.copper_pieces = copper_pieces
        self.silver_pieces = silver_pieces
        self.electrum_pieces = electrum_pieces
        self.gold_pieces = gold_pieces
        self.platinum_pieces = platinum_pieces

    def __str__(self):
        return "Dinero obtenido:\n  Copper: "+str(self.copper_pieces)+"\n  Silver: "+str(self.silver_pieces)+"\n  Electrum: "+str(self.electrum_pieces)+"\n  Gold: "+str(self.gold_pieces)+"\n  Platinum: "+str(self.platinum_pieces)

    def add_gold(self, gold):
        self.gold_pieces += gold

    def agregar_dinero(self, dinero):
        self.copper_pieces += dinero.copper_pieces
        self.silver_pieces += dinero.silver_pieces
        self.electrum_pieces += dinero.electrum_pieces
        self.gold_pieces += dinero.gold_pieces
        self.platinum_pieces += dinero.platinum_pieces

Then I have my class named Mochila (bag in english) which has a list of items and a Dinero class.
import dinero

class Mochila:

    def __init__(self, dinero:dinero.Dinero=dinero.Dinero(0,0,0,0,0), items:list=[]):
        self.items = items
        self.dinero = dinero

    def meter_item(self, item):
        self.items.append(item)

    def sacar_item(self, item):
        self.items.remove(item)

In my main I set 2 different mochila's and the mochila2 is taking the value of the mochila1's Dinero.
import dinero
import mochila

mochila1 = mochila.Mochila()
mochila2 = mochila.Mochila()

print(mochila2.dinero)

nuevo_dinero = dinero.Dinero(10, 10,200,10,10)

print(mochila2.dinero)

mochila1.dinero.agregar_dinero(nuevo_dinero)

print(mochila2.dinero)

mochila2.dinero.agregar_dinero(mochila1.dinero)
mochila1.dinero = dinero.Dinero(0,0,0,0,0)

Why is this happening and how can I solve this?
Answer: Ok, so it looks like both dinero instances are the same, as in if you comment out your str method, you will see they take up the exact same space in memory, so with:
print(mochila2.dinero)
print(mochila1.dinero)

You get back:
<__main__.Dinero object at 0x0000025D90EC0B08>
<__main__.Dinero object at 0x0000025D90EC0B08>

This is because when you set the default dinero in mochila's constructor, it is using the same default every time, not creating a new instance each time. To fix this, and considering you probably always want a new mochila to start of with 0 money anyway, try jus moving the instantiation of dinero to the constructor:
class Mochila:

    def __init__(self, items: list=[]):
        self.items = items
        self.dinero = Dinero(0, 0, 0, 0, 0)


Google analytic is showing Package Name

Question: Recently I have upgraded GAv4 from GAv3 , But there are some activities where I did not applied GA code but that package names are showing on DashBoard But where I have used these code showing screen name.
// Get tracker.
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
    TrackerName.APP_TRACKER);

// Set screen name.`enter code here`

t.setScreenName(screenName);

// Send a screen view.
t.send(new HitBuilders.ScreenViewBuilder().build());

for Java and

    <bool name="ga_autoActivityTracking">true</bool>

    <screenName name="com.mypackage">Screen Name
</screenName>

in xml.
plz help me.
Answer: you are setting screen name as your package name that's why its showing package name..use <string name="ga_appName">AppName</string> and set screen name from code somthing like that t.setScreenName("MainActivity");
Comment: Thanks for your answer, but if I use AppName then it will show appName on dashboard, But I don't want to show anything for that activities, where I did not applied GA code.

Google analytic is showing Package Name


Is this a valid reasoning for solution of Spivak Chapter 1 Problem 10?

Question: I am trying to solve the exercise problems from Spivak Calculus. I am new to proof based approach. Please, go through my reasoning for this problem, and point out whether it is valid or not, or if it is wrong altogether. It's not even close to clean, so if you can provide an elegant solution it would be great.
Problem Statement:
Express the following without absolute value signs, treating various cases separately when necessary.

$|a+b|-|b|$

My Solution:
For case 1: $ a,b>0 $

$a+b-b = a$

For case 4: $ a,b<0 $

Then if we consider $c,d>0$   and $a=-c$ and $b=-d$
  Then,
  $|-c-d|-|-d| $
  $=|-(c+d)|-d$
  $=c+d-d=c$
$c$ is the Positive value of $a$, so case 1 and case 4 yields same result.

For case 2: $ a>0, b<0 $

$Let, b = -c,$ where $c>0$
   $|a-c|- |-c| = |a-c|- c $
   Let the positive difference $|a-c|=k$
   Therefore, $k-c$

For case 3: $ a<0, b>0 $

$Let, a = -d,$ where $c>0$
   $|-d+b|- |b|=|b-d|-b$
    Let the positive difference $|b-d|=k$ , which is same in value as in case 2.
  Therefore, $k-b$.
    But $b=c$.
    Therefore cases 2 and 3 yield same result => $k-b$.
Comment: I would think it would be desirable to give final answers in terms of $a$ and $b$.
Comment: I am not quite sure how to express $k$. I know |a-b| or |b-a| will yield the same result. Is the solution even correct? Did I get the right solution?
Answer: Problem Statement: Express the following without absolute value signs, treating various cases separately when necessary.

|a+b|−|b|

Your approach is valid, but I would rather express the final result in terms of the parameters $a,b$. You should start defining the following 4 cases, based on the sign of the expresions within the absolute values:
case 1
$b>0$  and $a+b>0$ ($a + b>0$ is equivalent to $a>-b$)
Then, we get $a+b−b=a$
case 2
$b>0$  and $a<-b$
$|a+b|−|b|=-(a+b)-b=-a-2b$
case 3
$b<0$  and $a>-b$
$|a+b|−|b|=a+b-(-b)=a+2b$
case 4
$b<0$  and $a<-b$
$|a+b|−|b|=-(a+b)-(-b)=-a$
As you noticed, you can group the cases and end  just with 2 different formulas. I leave that to you.
Comment: This is a helpful answer. Thanks. I cannot upvote, otherwise would have.
Answer: As noted in a comment, it seems this exercise intends the final answer to use only the variables $a$ and $b$.
For $a,b>0$, you have already done this, and for $a,b>0$, it is easy enough to substitute $-a$ for $c$. For the other two cases, however, you will get hung up on what to do with $k$. For example, if $a>0$ and $b<0$, you don't know whether $a+b$ is positive or negative, so you cannot make a simple substitution for $k$ without using absolute value.
The solution to this problem is to choose better cases. In general, the cases of an absolute value expression are determined not by what variables are used, but by what is inside each of the pairs of absolute value brackets. Specifically, one thing happens when a subexpression inside an absolute value is positive, and a different thing happens when the subexpression is negative.
So separate cases for $b>0$ and $b<0$ still make sense, because $b$ is inside an absolute value by itself, but it makes no sense to do separate cases for  $a>0$ and $a<0$, no matter how you combine them with the $b$ cases.


How to check whether session live or expired in Quickblox iOS SDK?

Question: I know that, any session will be expired after last request (made before 2 hours) to the Quickblox server. When I create a session, I'm able to find [QBBaseModule sharedModule].tokenExpirationDate but I'm not sure how it works and how should I check for whether session is live or expired?

How to check whether session is live or expired?
If I create a session, I'll get  [QBBaseModule sharedModule].tokenExpirationDate for next 2 hours, now within an hour I'll made a request to the server, would it update [QBBaseModule sharedModule].tokenExpirationDate date too?
Answer:
By checking tokenExpirationDate.
tokenExpirationDate is updated in every response from QuickBlox. So answer is - yes.


Get clean date without any HTML tags

Question: I am using the Date module together with a view to display dates, and I need to get the date timestamp. The problem is that $fields['date_in_timestamp'] content comes wrapped in HTML.
 1468473300

I need only the value and no HTML.
PS: my field "date_in_timestamp" will apply a "U" format for the timestamp.
One possible way I found is described in https://www.drupal.org/node/423870, comment #9. The problem is that this applies to all those who have a certain format, and I don't know how to distinguish them from other similar formats.
Is there any way to get the machine name of the date format?
Answer: The solution that worked for me in this case was easier than I thought.
Solution:
In the configurations of the view
1.-
Select settings Style ->
Customize HTML field -> None

Uncheck Add default classes

2.-
In Rewrite results -> Select Strip HTML tags

Get clean date without any HTML tags


How to change environment variable for already installed Cygwin services

Question: For example, I need to switch Cygwin sshd service from 'ntsec' to 'nontsec' mode on quite a few Windows machines without re-installing the service.
Answer: The variables are stored under
<code>/HKLM/SYSTEM/CurrentControlSet/Services/{service name}/Parameters/Environment
</code>
registry key. So, the following commands do the trick for sshd example:
<code>regtool set /HKLM/SYSTEM/CurrentControlSet/Services/sshd/Parameters/Environment/CYGWIN nontsec
# don't run the following commands one-by-one unless you want to lose remote access
cygrunsrv -E sshd && cygrunsrv -S sshd
</code>


What Is the maximum - Minimum Size of bat player Can use In cricket?

Question: What Is the maximum - Minimum Size of bat which player Can use In cricket. Many Players use small bats and other types like different sizes at different time and situation.
Answer: Quoting from Law 5, The Bat:

5.7 Bat size limits
5.7.1 The overall length of the bat, when the lower portion of the handle is inserted, shall not be more than 38 in/96.52 cm.
5.7.2 The blade of the bat shall not exceed the following dimensions:
Width: 4.25in / 10.8 cm
Depth: 2.64in / 6.7 cm
Edges: 1.56in / 4.0cm.
Furthermore, it should also be able to pass through a bat gauge as described in Appendix B.8.

plus some other minor points about coverings etc. No minimum size is specified.


Visual studio 2017 c# BLL& DAL

Question: Tenho um problema de como guardar e tirar uma imagem da base de dados.
Gostaria de saber uma maneira de introduzir a imagem na base de dados tendo em conta que o numero de contribuinte é a chave primaria e que depois numa outra form possa usar codigo para ir busca-la há datagridview e por as informaçoes numa picturebox
<code>public class BLL {
    public class Imagem {
        static public object loadpic(int Numero_de_contribuinte) {
            DAL dal = new DAL();
            SqlParameter[] sqlParams = new SqlParameter[] {
                new SqlParameter("@Numero_de_contribuinte", Numero_de_contribuinte),
            };
            return dal.executarScalar("select Imagem from Imagem where @Numero_de_contribuinte=@Numero_de_contribuinte", sqlParams);

        }
        static public DataTable Load() {
            DAL dal = new DAL();
            return dal.executarReader("select * from Imagem", null);
        }
        //Insere a imagem relativa ao numeroo de contribuinte
        static public int insertImagem(byte[] img, string Numero_de_contribuinte) {
            DAL dal = new DAL();
            SqlParameter[] sqlParams = new SqlParameter[] {
                new SqlParameter("@img", img),
                new SqlParameter("@Numero_de_contribuinte", Numero_de_contribuinte)

            };

            return dal.executarNonQuery("INSERT into Imagem (Imagem,Numero_de_contribuinte) VALUES(@img,@Numero_de_contribuinte)", sqlParams);
        }
    }

    private void button2_Click(object sender, EventArgs e) {

        // Code Snippet
        MemoryStream ms = new MemoryStream();

        pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

        byte[] buff = ms.GetBuffer();
        int g = BLL.Imagem.insertImagem(buff, textBox2.Text);

        /*  OpenFileDialog open = new OpenFileDialog();
              open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
              if (open.ShowDialog() == DialogResult.OK)
              {
                  Bitmap bit = new Bitmap(open.FileName);
                  pictureBox1.Image = bit;
                  int a = BLL.Imagem.insertImagem(bit, textBox1.Text);

              }*/

    }
    private void button3_Click(object sender, EventArgs e) {
        int o = Convert.ToInt16(textBox2.Text);

        BLL.Imagem.loadpic(o);

    }
</code>
Comment: obrigado ja esta so vou por pelo menos a imagem do design para se ter uma ideia :)
Comment: Olá Pedro, não poste imagens do seu código, coloque o próprio texto do seu código na pergunta.
Comment: Sou novo nisto,para a proxima ja sei
Comment: Não precisa esperar a próxima é só clicar no link "editar" no final da pergunta e alterar :)
Comment: Dê uma olhada nesse link para ter ideia de como fazer:
https://www.c-sharpcorner.com/UploadFile/deepak.sharma00/how-to-save-images-in-mysql-database-using-C-Sharp/
Comment: vou dar uma vista de olhos
Comment: Qual é exatamente a sua dúvida?
Comment: Eu gostaria de conseguir guardar a imagem na base de dados .
e depois conseguir ao clicar na datagridview demonstrar a imagem numa picturebox. até agora só consegui por os dados que levam letras e numeros a serem guardados.
Answer: Eu sugeria uma abordagem fácil e rápida de se fazer que é guardares o URL da imagem na Base de Dados. Não precisas de guardar a imagem em si, só precisas de garantir que ela existe no caminho que puseste na BD. Depois do lado do C#, na PictureBox só precisas de colocar a URL no método PictureBox.Load(string URL) Method.
A única coisa que precisas de ter atenção é se o local da imagem não for o mesmo. Então caminhos absolutos não iram funcionar. Tens que usar um caminho relativo.

Visual studio 2017 c# BLL& DAL


Can the geometric realization increase the dimension?

Question: Let $M$ be a smooth manifold of dimension $n$, and $\mathcal{U}$ any open cover of $M$, in particular $\mathcal{U}$ is not necessarily good or finite. Consider then the geometric realization of the nerve of $\mathcal{U}$. Is this homotopic/weakly equivalent to a space of dimension $\leq n$ (e.g. covering dimension)?
As I understand it, the nerve theorem tells me that if my open cover is a good one, this geometric realization will automatically be weakly equivalent to my original space $M$. This clearly doesn't need to happen if my open cover is badly chosen, e.g. if $\mathcal{U} = \{M\}$ I will just get a zero-dimensional point. But what I am hoping for is that even an arbitrarily bad cover will still give me something which is "essentially" at most $n$-dimensional.
Feels somewhat intuitively true, but I am not quite sure where I would start with a proof or what results might be helpful. Any ideas?
Answer: No.  For instance, let $M=\{0,1,2\}$ (a $0$-dimensional manifold) and consider the open cover consisting of $\{0,1\},\{0,2\},$ and $\{1,2\},$ whose nerve is $S^1$.
More generally, let $X$ be any simplicial complex, and let $M$ be the set of faces of $X$, considered as a discrete space.  For each $x\in X$, let $U_x=\{m\in M:x\in m\}$.  Then $(U_x)_{x\in X}$ is an open cover of $M$, and it is easy to see that its nerve is exactly $X$.
Note that similar statements also hold in higher dimensions: if $M$ is any nonempty positive-dimensional manifold and $X$ is any finite connected simplicial complex, then there is an open cover of $M$ whose nerve is $X$.  To prove this, let $f:M\to |X|$ be any continuous surjection (which exists by the Hahn-Mazurkiewicz theorem, for instance).  Now take the open cover of $|X|$ by open stars of vertices, whose nerve is $X$, and pull it back to an open cover of $M$ via $f$.  Since $f$ is surjective, this pulled back open cover has the same nerve.
(The connectedness assumption cannot be dropped, though, since the nerve of any open cover of a connected space is connected.)


Interaction Plot error: The lines do not meet

Question: Hello I wanted to develop an alternative regression equation just to prove that my first regression equation is a better fit.
I want to show the possibility that my independent variables my be interacting with each other. To show that I wanted to plot an interaction graph.
I will first write the multiple regression equation and then the interaction plot and also the resulting plot.
> interact_plot(Poly, pred = x2, modx = x1)
Warning message:
-1.13290847281745 is outside the observed range of x1

What does this warning message mean?
And I do not really know how to interpret this? Does this mean they are no interacting? Do they have to meet at some point?
Thanks for your help, really in need.
Answer: This question is better suited for Cross Validated, but the answers are pretty straightforward:
1. What does this warning message mean?
From the arguments in interact_plot() it looks like you're using jtools.  The jtools::interact_plot documentation notes that the modxvals argument can be used to specify the range of moderator values.
If modxvals is left to the default (NULL), then:

the customary +/- 1 standard deviation from the mean as well as the mean itself are used for continuous moderators.

But there's no guarantee that your actual observed values include values up to +/- 1 SD from the sample mean.
The warning you're seeing was added as a heads up that the plot is using moderator values that don't appear in your data, but which do fall within the +/- 1 SD default range.  You most likely don't need to worry about this.
2. Do they have to meet at some point?
An interaction effect does not need to have moderator slopes "cross" in the plot of the data, but you will see that the angles of the slopes would cross at some point, if the plot extended far enough along the x-axis.  In the plot you posted, imagine if the x values continued off the left end of the graph - pretty soon, the slopes you see would, in fact, overlap.
You can usually rely on this rule of thumb for interpreting visualizations of interaction effects.  (But better to check the coefficients in your model, to make sure.)
Comment: wow.. you are a life saver. Thanks for all the explanation. I have a one more question though. How can I check the coefficients? Sorry if that is a dumb question.
Comment: and sorry. I am new to this "coding community" so I do not really know the difference between these two websites.


OpenVPN port share with Apache - client IP is not preserved

Question: I have a port-share setup with OpenVPN and Apache over HTTPS which works nicely. However, in my Apache logs the requests are logged with the OpenVPN server IP, rather than the client's actual IP.
This makes any analysis of these logs useless, and I'd like to log the client's IP. How can I do that?
Answer: It doesn't look like this will be possible - the only way you'd be able to do this is if OpenVPN were to intercept your HTTP requests at layer 7, and insert a header (something like X-Forwarded-For) with the client's IP in the request.  Then you could use a custom log format, or something like mod_rpaf to ensure that IP ended up in the logs.
There's no mention of this feature in the OpenVPN docs, and I suspect they're just passing the TCP connection straight on once it's clearly not an HTTP request.  Your best bet is probably to bring up a second IP address on your server and split the services like that.


restoring table data from cassandra snapshot don't gossip to other nodes in cluster

Question: I'm restoring to a deleted table data from a cassandra snapshot.
This is what I'm doing:
Logging to first node.
Taking all files from snapshot and copying them to the table data directory.
Executing
nodetool refresh <keyspace>

and data is showed ok on that node, but not transmitted to others in cluster.
I'm aware the reason may be related to timestamps on records, so using advice I try deleting data on tables, executing
TRUNCATE

on node previously to this process, but with the same results.
Answer: Have you tried a nodetool repair -full   on the other nodes?
You will need to do the same refresh process on all the nodes, so the table should appear on all the nodes after that.
Answer: I know is a quick and dirty solution, but when I face this problem my solution was:
COPY Usuario (id , usuarioId, organizacionId, descripcion, estado , ultimoCambio, json , sesion) TO 'Usuario.csv';
COPY Usuario (id , usuarioId, organizacionId, descripcion, estado , ultimoCambio, json , sesion) FROM 'Usuario.csv';

And I prefer backup these csv than snapshots. Doing this process, rows are recreated and correctly copied to every node in cluster.
Comment: sstableloader (https://docs.datastax.com/en/cassandra/3.0/cassandra/tools/toolsBulkloader.html) could give you also the same functionality.


No access to Google Cloud Storage bucket after installing new Google Cloud Storage

Question: I had to remove and reinstall Google Cloud Storage and Google Bigquery. Since then I don't have access to the bucket I created before (error message is <code>"Access denied"</code>). I also can't find the bucket in Google APIs Console. How do I get access to the bucket again?
Comment: I've answered below, but a side question: did you delete the project from the console while you still had data that you needed in the bucket?
Answer: If you deleted the project, then any buckets associataed with the project are gone along with it.  Access denied can happen for a period of time while the buckets are still being cleaned up.  Eventually this access denied error should turn into a Not Found error and you should be able to re-create a bucket with the same name.
Comment: Thanks, no it seems I deleted the bucket by mistake. Project is still there.


Rails error: unable to open database file (SQLite3::CantOpenException)

Question: I created a Rails web app, pushed to github, pulled down onto a Raspberry Pi.
Ran "rake db:create RAILS_ENV=production" along with db:migrate.
When I run the WEBrick server (in production environment), it works perfectly.  But when I try to run it through Apache, I get the Phusion Passenger error screen:
Web application could not be started
unable to open database file (SQLite3::CantOpenException)
 /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/connection_adapters/sqlite3_adapter.rb:26:in `initialize'
/usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/connection_adapters/sqlite3_adapter.rb:26:in `new'
/usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/connection_adapters/sqlite3_adapter.rb:26:in `sqlite3_connection'

I already changed the owner and group of the production.sqlite3 file to be "www-data", and chmod 666.  Also edited the database.yml file so it contains the full path to the database files rather than the relative path.
Not sure what else to try.
Comment: Maybe u have not migrated, so is the error. do: rails db:migrate
Answer: It's because nginx create www-data user, and this user don't have a previlegues to read sqlite3 file and your app...
You need to run this command:

sudo chown -R www-data:www-data rails_project/
sudo chmod -R 777 rails_project/


How to Validate using jquery?

Question: I have a input field like Vehicle Registration Number,  how to validate using jquery this input below condtions:-
i) Min Size - 4 Characters
ii) Should contain atleast 3 Alpha characters
iii) First 2 Characters should be alpha

var registration=$("#add-car-registration").val();

if(registration==""){
$.alert({title:"Information",content:"Enter Registration Number"});
return false;
}

if (registration.match('(.*?[a-zA-Z]){0,3}')) {
$.alert({title:"Information",content:"Minimum 2 alphabets"});
return false;
}

if(registration.length<4){
$.alert({title:"Information",content:"Min 4 Characters Registration Number"});
return false;
}

Comment: try reading the documentation https://jqueryvalidation.org/documentation/
Comment: Give a try from your side. Then we can correct it.
Answer: I would use regex to validate your input as the follow:
$(".myform").submit(function(e){
  var vrn = $("#vrn").val();
  if (vrn.length < 4) {
    alert("Min. 4 chars");
    e.preventDefault();
  } else if (!vrn.match(/^[A-Z1-9]{2}/gi)) {
    alert("First 2 chars must be alpha");
    e.preventDefault();
  } else if (!vrn.match(/([A-Z1-9].*){3}/gi)) {
    alert("Atleast 3 chars must be alpha");
    e.preventDefault();
  } else {
    alert('success')
  }
});

JSFiddle
Answer: You cant do separate conditions, you should use if, else if, etc... to make the correct way, also you need to detect the submit event and block it if is not validated (not with return because return will stop everything). for example (note i changed your alerts into normal alerts to test it):
UPDATE: i improved the number validation to match the format (example: TG24 V 2234)
$(".myform").submit(function(e){

  var registration = $("#add-car-registration").val();
  var format1 = /(?=(?:.*?[A-Za-z]){2})/; //minimum 2 alphabets
  var format2 = /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/; //numbers, alphabets and spaces

  if(registration==""){
    alert("Information\nEnter Registration Number");
    e.preventDefault();
  }
  else if (!(format1.test(registration)) || !(format2.test(registration))){
    alert("Information\nMinimum 2 alphabets, numbers and spaces only");
    e.preventDefault();
  }
  else if(registration.length<4){
    alert("Information\nMin 4 Characters Registration Number");
    e.preventDefault();
  }
  else{
    $(this).submit();
  }

});

You can test here: https://jsfiddle.net/cw0954sh/3/
Comment: Minimum 2 alphabets condition not working and also first two letters should be alphabet., hw to do solve it , plz help me.
Comment: i think your regular expression is not correct, i dont know how the Vehicle Registration Number structure, can you give me an example?
Comment: like this, TG24 V 2234
Comment: OK, i improved the code and tested with two regular expressions, i hope it helps you to understand how it works

How to Validate using jquery?