Convert If Statement into Switch

Question: I have this If statement and I would like to move them into Case-Switch
Here is my if Stataments:
if (rResponse.ErrorCode[0] == 0x20 && rResponse.ErrorCode[1] == 0x03)
    ErrorMsg = "COMM_FRAME_ERROR";
if (rResponse.ErrorCode[0] == 0x20 && rResponse.ErrorCode[1] == 0x04)
    ErrorMsg = "JAM";
if (rResponse.ErrorCode[0] == 0x20 && rResponse.ErrorCode[1] == 0x05)
    ErrorMsg = "NO_CARD";

How can I do that?
Comment: I think Itay has better explained same way you could use nested switch also.
Comment: @Pratik in my experience it is better to not next switches. It can make it very hard to read. Since this looks like it would be from a error handling section of the program I would think it best to either do as Itay said or make a "parser" for both bytes I'll post my idea as a answer.
Comment: @RobertSnyder Agreed Completely. I always avoid use of switch statements, i better take use of `Database or any generic function(list or any entity)`
Comment: now that is something I don't know about. I will have to look into that because I just got done doing something similar to what the OP is doing on a project of mine..and my response is similar to my approach to solving it. Could you elaborate more on your thoughts?
Comment: @RobertSnyder i have posted my thought.It's not what is required for such small problems but to create `Entities` like enum which are expnadable this may be used.
Answer: if (rResponse.ErrorCode[0] == 0x20) {
  switch(rResponse.ErrorCode[1]) {
    case 0x03:
      ErrorMsg = "COMM_FRAME_ERROR";
      break;
    case 0x04:
      ErrorMsg = "JAM";
      break;
    case 0x05:
      ErrorMsg = "NO_CARD";
      break;
  }
}

Answer: If u want both in switch case:
switch(rResponse.Errorcode[0])
case 0x20:
    switch(rResponse.ErrorCode[1]) {
        case 0x03:
            ErrorMsg = "COMM_FRAME_ERROR";
            break;
        case 0x04:
            ErrorMsg = "JAM";
            break;
        case 0x05:
            ErrorMsg = "NO_CARD";
            break;
    }
    break;

Answer: Can omit or change the exception,
if (rResponse.ErrorCode[0] == 0x20)
        {
            switch (rResponse.ErrorCode[1])
            {
                case 0x03:
                    ErrorMsg = "COMM_FRAME_ERROR";
                    break;
                case 0x04:
                    ErrorMsg = "JAM";
                    break;
                case 0x05:
                    ErrorMsg = "NO_CARD";
                    break;
                default:
                    throw new InvalidOperationException();
                    break;
            }
        }

Answer: switch(rResponse.Errorcode[0])
{
 case 0x20:
  switch(rResponse.ErrorCode[1])
  {
    case 0x03:
        ErrorMsg = "COMM_FRAME_ERROR";
        break;
    case 0x04:
        ErrorMsg = "JAM";
        break;
    case 0x05:
        ErrorMsg = "NO_CARD";
        break;
  }
  break;
}

Comment: Mr. Anand, Don't you you think we have the same the answers?
Answer: You can try something like this..
 switch (rResponse.ErrorCode[0] + rResponse.ErrorCode[1])
       {
        case (0x20 + 0x03):
              ErrorMsg = "COMM_FRAME_ERROR";
              break;
       case (0x20 + 0x04):
              ....
      }

though this may not suite all the situations,
Answer: Although with the information provided Itay's response might be best. But if this error portion is on a larger scale then maybe something as follows might be worth a go. (Similar approach, just makes it easy to add on.
private string GetError(byte response1, byte response2)
{
    var ErrorMessage = "";
    switch (response1)
    {
        case 0x20:
            ErrorMessage = ParseCardErrors(response2);
            break;
        case 0x21:
            ErrorMessage = ParseDeviceErrors(response2);
            break;
        default:
            ErrorMessage = "Unknown Error";
    }

    return ErrorMessage;
}

private string ParseCardErrors(byte response)
{
  switch(response)
    {
        case 0x03:
          return "COMM_FRAME_ERROR";
        case 0x04:
          return "JAM";
        case 0x05:
          return "NO_CARD";
        default:
            return "Unknown card Error";
    }
}

private string ParseDeviceErrors(byte response)
{
  switch(response)
    {
        case 0x03:
          return "COMM_FRAME_ERROR";
        case 0x04:
          return "Unplugged";
        case 0x05:
          return "No device";
        default:
            return "Unknown device Error";
    }
}

Answer: I might be posting a very diffrent solution this question but it can answer @Robert question:
class Program
{
    //This can be included in Seprate class also
    public enum ErrorMessages
    {
        //Store any Values as Key and Pair
        // Provide and easy way to update answers
        Error1 = 1,
        Error2 = 2,
        Error3 = 3,
        Error4 = 4
    }

    public static void Main()
    {
        ICollection<EnumValueDto> list = EnumValueDto.ConvertEnumToList<ErrorMessages>();

        foreach (var element in list)
        {
            Console.WriteLine(string.Format("Key: {0}; Value: {1}", element.Key, element.Value));
        }
        Console.Read();

        /* OUTPUT:
           Key: 1; Value: Error1
           Key: 2; Value: Error2
           Key: 3; Value: Error3
           Key: 4; Value: Error4
        */
    }

    public class EnumValueDto
    {
        public int Key { get; set; }

        public string Value { get; set; }

        public static ICollection<EnumValueDto> ConvertEnumToList<T>() where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
            {
                throw new Exception("Type given T must be an Enum");
            }

            var result = Enum.GetValues(typeof(T))
                             .Cast<T>()
                             .Select(x => new EnumValueDto
                             {
                                 Key = Convert.ToInt32(x),//values are arbitary here any datatype will work
                                 Value = x.ToString(new CultureInfo("en"))
                             })
                            .Where(err => err.Key==3) //Instead of 3 as key here use Response variable instead
                            .ToList()
                            .AsReadOnly();

            return result;
        }
    }

}

Convert If Statement into Switch


How to Identify dependent variable from my dataset?

Question: I have a dataset which consists of 50 variables. I want to programmatically(using python) identify what is my dependent variable is. Are there any tests to separate the dependent variable from independent variables in the dataset?
Any ideas would be highly appreciated!
Comment: If you don't know from outside the data which variable is dependent, I think you would have your work cut out to discover which it is. @Atirag's criterion seems to me no criterion at all, as a dependent variable can't be distinguished from its main predictors that way.
Comment: @mkt Being misguided isn't a criterion for closure.
Comment: This is a misunderstanding about statistics, or machine learning if anyone prefers. I initially voted to close as unclear but @Peter Flom's answer made it worth keeping in my view.
Comment: depends on what your variables are and the functions that relate them. If a variable's value changes when another of the variables change then it is dependent, otherwise independent.
Comment: I'm voting to close this question as off-topic because this is misguided and not answerable with statistics.
Comment: @NickCox I also said 'not answerable with statistics', which is a better description of the problem. I could have chosen 'Unclear what you're asking', but I don't think shoehorning our actual reasons into that category is always necessary or worthwhile.
Answer: You cannot do this in the way you describe.  Which variable is dependent is a matter for you to figure out from substantive knowledge.
Suppose you had a data set that consisted of height, weight and age of a bunch of adult humans. Which is the dependent variable? There's no way to know from just the numbers. Given what we know about humans, we can say weight is dependent on height and age. But the data don't tell us that and you could run a regression with any of these as the DV.
Or, if you had an experiment, then you would have to know which variables were manipulated by the experimenter.  Suppose you had a randomized controlled trial in which some people got a medication and others did not and there was a variable for symptom severity and a bunch of other variables.  Well, YOU know that the medication was manipulated. But the computer won't know unless you tell it.
EDIT: It reminds me of something I read (I think it was by Douglas Hofstadter but I am not sure and can't find it):

Computers are logical but not reasonable and people are reasonable but not logical.


Pre-Built Theme, how to transfer header to blocks

Question: I am moving at a glacial pace at theming, even following guides, because I think I am having trouble understanding the relationship between all parts of drupal theming. If someone can help me with the following issue, it should make me better understand how I am to configure everything else
Basically, I want to know the ideal way to theme this header which is static html to transfer into a block or a region so that I can theme it. I initially just included it using php include statements, but realize this is not good practice in drupal, and am looking for  the proper way to do it.

             Login

                <form role="form">

Login Form

                            <input type="text" class="form-control" placeholder="Username">

                            <input type="password" class="form-control" placeholder="Password">

                                <input type="checkbox"> Remember me

                        <button type="submit" class="btn btn-ar btn-primary pull-right">Login</button>

                </form>

                <form role="form">

                        <input type="text" class="form-control" placeholder="Search...">

                            <button class="btn btn-ar btn-primary" type="button">Go!</button>

                </form>

Thanks for the help,
Matthew Beal
Answer: Essentially you have the User Login & Search Form blocks so you could add the following to your themes' .info file:
regions[login] = Login
regions[search] = Search

Clear the site cache and visit your Blocks page (admin/structure/block) and you should see 2 additional regions. Place the User Login block in the Login region and the Search Form block in the Search region.
In page.tpl.php in your theme, use the following code:
<?php if (!empty($page['login'])): ?>

   Login

    <?php print render($page['login']); ?>

<?php endif; ?>

<?php if (!empty($page['search'])): ?>

    <?php print render($page['search']); ?>

<?php endif; ?>

This will give you a starting point and you can start overriding output in your theme by using functions and templates. It should be possible to achieve almost the exact code you're looking for.
You're obviously using Bootstrap, have you tried using the Drupal Bootstrap theme as a starting point?
Comment: I am using Bootstrap, correct. I think that I am using it as a starting point, as in I am using the bootstrap_subtheme folder. Is there something else I ought to do to use it as a starting point?
Comment: Have you followed the sub-theming guide at https://www.drupal.org/node/1978010


Bayesian Inference: Modeling checkout times at a store

Question: I am currently learning how to use Bayesian inference. I have been making up problems (by defining some population parameters) and then trying to infer those values from samples. I recently made up a problem that I cannot figure out how to solve.
I would like to model the time that it takes to checkout at a grocery store. In this model, there are two main parts. The first is, the time it takes the cashier to ring up and bag the items. The second is, the time it takes to pay the cashier.
I have chosen to model the time it takes the cashier to scan and bag $k$ items (assume for simplicity that the same number of items are always purchased) as a gamma distribution:
$S \sim \textrm{Gamma}(k, \theta_1)$
The $\theta_1$ parameter is the average time it takes to scan and bag one item. So this is modeling the sum of $k$ exponential random variables (with rate parameter $1/\theta_1$).
I have chosen to model the time it takes to pay the cashier as an exponential variable:
$P \sim \textrm{Exponential}(\theta_2)$
The total time it takes to checkout is the sum of the time it takes to scan and bag plus the time it takes to pay:
$W_i \sim S + P$
If I directly observe the random variables $s_i$ and $p_i$ (and I know the number of items k), then the inference problem for $\theta_1$ and $\theta_2$ is easy. The likelihood function for $s_i$ is the gamma distribution and the likelihood function for $p_i$ is the exponential distribution. Standard Monte Carlo sampling techniques can be used to obtain their posterior distributions.
However, if all that I know are the total waiting times $w_i$ (and $k$), then I do not know what the likelihood function should be. From the research I have done, it appears that in general sums of random variables do not have closed form PDFs.
How can this kind of problem be solved? Are there certain approximations that could be made to obtain a closed form likelihood?
I am currently using the pymc3 library to do Bayesian inference. I realize that it is possible to perform a numerical integration to evaluate the convolution of two PDFs, but this is computationally expensive and I'm not sure it would be possible to obtain the gradient of such a function, which would rule out the use of Hamiltonian Monte Carlo sampling (e.g. NUTS).
Answer: Hello, qsc. I am very sympathetic to your quest of learning Bayesian statistics by posing problems to yourself, and then trying to solve them. However, this method also meets many roadblocks at times, such as here.
You are not trying to infer $\theta_1$ and $\theta_2$ individually (which is easy), so I assume you are attempting to infer them from their convolution, and working backward, given your assumptions on the distributions taken by $S$ and $P$.
So the first step is solving this convolution problem. Based on wikipedia's convolution page, the convolution of Exponential's is a Gamma, and the convolution of Gamma's is yet another Gamma, so based on some intuition, I imagine the conv. you are looking for would also produce a Gamma. Here, you are in luck, because as you found, most convolutions do not have closed-form answers as easy as this.
However, where you are out of luck, is that there does not seem to be a known, documented way of performing convolution via Bayesian methods, and then using that to go backwards somehow. This is a simple roadblock that I hope you figure out how to overcome with enough research.


Create map that show user Location and last user's post

Question: I don't know my question is cheap or good !:(
I want to create a map that shows on users location and last post like Azadnegar's map or Drupal.org front page.
I know I should use openLayers, CCK, views but I can't build as well as Azadnegar!
I want to know how create map like its map, I mean how can I config our modules.
in this site get user location in registration form in list box,how create like it?
what map her use?How create views?or ...
please explain whit detail !
Answer: Once I had to do the very same thing and followed this good video by Drupal Therapy. It uses GMap (API 2) + Location modules instead of Open Layers, but if you're on D6 this is still a good solution. If you enable user-locations and node-locations functionalities in the modules page, you'll find predefined Gmap user/nodes location views. If you need to associate geographic information only on certain content types (and not to all nodes), you'd better enable location-CCK and just add and configure a location field to your desired content type, then create your Gmap view.
Hope it helps you to start with maps in Drupal.


Why is the formula for standard error of the sample mean and standard error of the sample proportion different?

Question: Trying to understand this intuitively and haven't been able to find any explanations for this.
If the formula for the standard error of the sample proportion is:
$$\sigma_\hat p = \frac{\sigma_X}{n}=\frac{\sqrt{n\!\cdot\!p(1-p)}}{n}=\sqrt{\frac{p(1-p)}{n}}$$
where $X$ is the sum of the results of $n$ independent trials of picking a $1$ or an $0$,
why is the formula for the standard error of the sample mean,
$$\sigma_\bar x=\frac{\sigma}{\sqrt{n}}$$
?
In both formulas, the sample size, $n$, is deflating the standard error, but why is one deflating by $n$ and the other one by $\sqrt{n}$ ?
Comment: You are not comparing the same things.  Consider a dataset consisting only of zeros and ones and apply both formulas: you will see they are equivalent.
Answer: You have various different standard deviations and standard errors there.  Trying to unpick them, for given $p$:

An individual trial has variance $p(1-p)$ and standard deviation $\sqrt{p(1-p)}$
The sum of $n$ independent trials has variance $np(1-p)$ and standard deviation $\sqrt{np(1-p)}$
The mean of $n$ independent trials has variance $\frac1n p(1-p)$ and standard deviation $\sqrt{\frac1n p(1-p)}$; this last expression is sometimes called the standard error of the sample mean or of the sample proportion

So the standard deviation of the mean is indeed $\frac1n$ of the standard deviation of the sum, and is $\sqrt{\frac1n}$ of the standard deviation of an individual trial, as you say in your question. You are comparing different things, as whuber has commented.


Should you use an equivalence or an implication in a definition?

Question: In a definition like the following:

An object $x$ is called $P$ if [and only if] it has properties $p$ and $q.$

should one use an implication (if) or an equivalence (if and only if)?
It makes sense to use an equivalence seen as this is a definition and not a set of necessary conditions. However, in many texts I see the use of just an implication. Which is correct in the formal or stylistic sense?
Comment: Related: http://math.stackexchange.com/questions/566565/are-if-and-iff-interchangeable-in-definitions
Comment: I do agree with you! One must use equivalence! :)
Answer: It is quite common to use if instead of iff in definitions because it reads better.
An alternative is to use when instead of if.
A definition like "$x$ is called a blip when $x$ satisfies $p$ and $q$" is metalanguage.
The mathematical statement "$x$ is a blip iff $x$ satisfies $p$ and $q$" is true, as consequence of the definition, but is not quite the same thing.


Measure of "subspace", has it a sense?

Question: Let for exemple $(\mathbb R^3,m_3)$ where $m_3$ is the Lebesgue measure on $\mathbb R^3$ and $(\mathbb R^2,m_2)$ with it's Lebesgue measure $m_2$. We now define the measure $m$ of $\mathbb R^2$ with the exterior mesure $$m^*(E)=\inf\left\{\sum_{k=1}^\infty |B_i|\mid B_i=\mathcal B_i\cap \mathbb R^2, E\subset \bigcup_{i=1}^\infty \mathcal B_i\right\}.$$
So $\mathcal B_i$ are balls of $\mathbb R^3$ and $B_i$ are balls of $\mathbb R^2$ but obtained form balls of $\mathbb R^3$ and $E\subset \mathbb R^2$.
My question is the following one: Is there a constant $C$ s.t. $$m_2(E)=Cm(E)$$
or at least $C,D$ s.t. $$Cm_2(E)\leq m(E)\leq Dm_2(E).$$
What I in fact would like to do, is to define a measure of subspace, but I'm not sure if it really has a sense.
Answer: Every ball in $\mathbb{R}^2$ can be obtained by projecting balls in $\mathbb{R}^3$: say $B$ is a ball in $\mathbb{R}^2$ with center $(x,y)$ and radius $r$; let $\mathcal{B}$ be the ball in $\mathbb{R}^3$ with center $(x,y,0)$ and radius $r$, then "$\mathcal{B}\cap \mathbb{R}^2= B$" in your notation.
So $m=m_2$.

Measure of "subspace", has it a sense?


Unable to submit rendered field

Question: I have a custom form with text field and a submit button.
$form['bid_amount'] = array(
  '#type' => 'textfield',
  '#title' => t("Your Bid"),
  '#prefix' => '
',
  '#suffix' => '
',
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Calculate your bid'),
  "#ajax" => array(
  'callback' => 'custom_callback',
  'wrapper' => 'test-ajax',
  'method' => 'replace',
  'effect' => 'fade',
  ),
);
}

What I want to do is, when 'bid_amount' is empty, and button is clicekd, 'bid_amount' should be rendered again with a prefilled value.
This is what I can do.
But at this time, when again button is clicked, with FILLED field of 'bid_amount', it shows up again with suggested value. Actuly it should be submitted this time.
Here is how I am rendering this ....
function custom_callback(&$form, &$form_state) {

    $next_bid = 100;
    return array(
      '#type' => 'ajax',
      '#commands' => array(
        ajax_command_replace("#test-ajax", render($form['bid_amount'] = array(
              '#type' => 'textfield',
              '#title' => t("Your Bid"),
              '#value' => $next_bid,
              '#prefix' => '
',
              '#suffix' => '
',
        ))),
      )
    );
}

Comment: That code would cause a notice or an error: _Only variables should be passed by reference_.
Answer: I was facing the same issue.  I think the render function doesn't add "name" to the html so the form values are not submitted. I fixed this by adding them in the array
'#attributes' => array(
  'class' => array('edit-bid-amount'),
  'name' => 'bid_amount'
),

The function now is
function custom_callback(&$form, &$form_state) {
  $next_bid = 100;
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace(
        "#test-ajax", render($form['bid_amount'] = array(
          '#type' => 'textfield',
          '#title' => t("Your Bid"),
          '#value' => $next_bid,
          '#prefix' => '
',
          '#attributes' => array(
            'class' => array('edit-bid-amount'),
            'name' => 'bid_amount'
          ),
          '#suffix' => '
',
          )
        )
      ),
    )
  );
}

Hth,
Sadashiv
Comment: This code has the same issue the code shown in the question has: It would cause a notice or an error: _Only variables should be passed by reference_.

Unable to submit rendered field


Why read fails with cqlsh query when huge tombstones is present

Question: I have a table with huge tombstones.So when i performed a spark job (which reads) on that specific table, it gave result without any issues. But i executed same query using cqlsh it gave me error because huge tombstones present in that table.

Cassandra failure during read query at consistency one(1 replica
  needed but o replicas responded ,1 failed

I know tombstones should not be there, i can run repair to avoid them , but apart from that why spark succeeded and cqlsh failed. They both use same sessions and queries.
How spark-cassandra connector works? is it different than cqlsh?
Please let me know .
thank you.
Answer: The Spark Cassandra Connector is different to cqlsh in a few ways.

It uses the Java Driver and not the python Driver
It has significantly more lenient retry policies
It full table scans by breaking the request up into pieces

Any of these items could be contributing to why it would work in SCC and not in CQLSH.


Sql Column had no values

Question: I have a sql table that I am trying to add a column from another table to. Only when I execute the alter table query it does not pull the values out of the table to match the column where I am trying to make the connection.
For example I have column A from table 1 and column A from table 2, they are supposed to coincide. ColumnATable1 being an identification number and ColumnATable2 being the description.
I tried this but got an error...
alter table dbo.CommittedTbl
add V_VendorName nvarchar(200)
where v_venkey = v_vendorno

It tells me that I have incorrect syntax... Anyone know how to accomplish this?
Comment: Why are you duplicating an nvarchar(200) value and storing it in both tables? This is wasteful to store redundantly and, since it's a name it's likely to change, which means you will have to update in more than one place. Typically surrogate keys are used to make this linkage.
Comment: You'd get much more helpful answers if you were to provide us with your extant structure.
Comment: Do it in two statements. Remove the where clause from the alter table statement and have a look at how you can use `update` to move the data from one table to another.
Answer: alter table dbo.CommittedTbl
add V_VendorName nvarchar(200);

go

update c
set c.V_VendorName = a.V_VendorName
from CommittedTbl c
join TableA a
on c.v_venkey = a.v_vendorno;

go

I'm just guessing at your structure here.
Answer: alter table 2 add column A <some_type>;
update table2 set column A = (select column_A from table2 where v_venkey = v_vendorno);

Your names for tables and columns are a bit confusing but I think that should do it.
Answer: There is no WHERE clause for an ALTER TABLE statement.  You will need to add the column (your first two lines), and then insert rows based upon a relationship you define between the two tables.
ALTER TABLE syntax:
http://msdn.microsoft.com/en-us/library/ms190273%28v=sql.90%29.aspx
Answer: There are several languages within SQL:
DDL: Data Definition Language - this defines the schema (the structure of tables, columns, data types) - adding a column to a table affects the table definitions and all rows will have that new column (not just some rows according to a criteria)
DML: Data Manipulation Language - this affects data within a table, and inserting, updating or other changes fall into this and you can update some data according to criteria (and this is where a WHERE clause would come in)
ALTER is a DDL statement, while INSERT and UPDATE are DML statements.
The two cannot really be mixed as you are doing.
You should ALTER your table to add the column, then INSERT or UPDATE the column to include appropriate data.
Answer: Is it possible that you want a JOIN query instead? If you want to join two tables or parts of two tables you should use JOIN.
have a look at this for a start if you need to know more LINK
hope that helps!

Sql Column had no values


Serialize Struct in Binary, Packed Format

Question: Is there a way in C# to serialize a struct to a binary stream (MemoryStream) such that the binary representation is equivalent to how the struct is visually layed out (i.e. no padding)?
In C/C++, you use #pragma commands to tell the compiler to pack the struct's so that there is no padding between the fields.  This is helpful if you have two apps passing messages back and forth via sockets.  With packing disabled, you can simply "send" the contents of the struct over the socket and not have to worry about packing each field individually into a binary buffer (also have to do endianness swapping if necessary).
Answer: Not unless you use unsafe code. Use Protocol Buffers or Thrift or something like that; I wouldn't recommend .NET built-in binary serialization based on my experience. You could also serialize/deserialize with BinaryWriter/BinaryReader (use reflection or pre-generate serialization code). As for packing, you can control it with the [StructLayout] attribute.
Comment: For info - protobuf-net doesn't support structs (only classes), and I'm pretty sure dotnet-protobufs doesn't either. I don't know about Thrift.
Answer: You can use the [StructLayout] and [FieldOffset] attributes to control the way your struct's fields are packed (google 'marshalling' for more info), and then use the following to generate a binary representation of your struct that can be sent through your network stream:
public static byte[] GetBytes<TStruct>(TStruct data) where TStruct : struct
{
    int structSize = Marshal.SizeOf(typeof(TStruct));
    byte[] buffer = new byte[structSize];
    GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
    Marshal.StructureToPtr(data, handle.AddrOfPinnedObject(), false);
    handle.Free();
    return buffer;
}

The downsides:

Its not idiomatic .NET
You need unmanaged code permissions
The buffer pinning might impact performance
Your structure cannot have references (there are special cases for strings and arrays)


Integral with trig functions and substitution

Question: How to integrate: $\int_0^T\cos(T-s)\sin(s)ds$? I was trying to use $\cos(a+b)=\cos a\cos b-\sin a\sin b$ and substitute $\cos(s)=u \Rightarrow \sin(s)ds=du$ but it does't help.
Comment: First of all, if $u = \cos s$, $du = -\sin s ds$.
Answer: \begin{align}
\int_0^T \cos(T-s) \sin s \, ds &= \int_0^T (\cos T\cos s +\sin T \sin s) \sin s \, ds \\
&= \cos T \int_0^T\cos s \sin s \, ds + \sin T \int_0^T \sin^2 s \, ds
\end{align}
For $\int_0^T\cos s \sin s \, ds$, use substitution rule: $u=\cos s$, $du=-\sin s \, ds$
For $\int_0^T \sin^2 s \, ds$, recognize that $\sin^2 s = \frac 12(1-\cos (2s)$ and integrate the latter expression.
Answer: Substituting $u=T-s$,
$$I=\int_{0}^{T}\cos{(T-s)}\sin{(s)}\,\mathrm{d}s\\
=\int_{0}^{T}\cos{(u)}\sin{(T-u)}\,\mathrm{d}u\\
=\int_{0}^{T}\cos{(s)}\sin{(T-s)}\,\mathrm{d}s.$$
Adding the first and last lines,
$$2I=\int_{0}^{T}\sin{(T-s+s)}\,\mathrm{d}s\\
=\int_{0}^{T}\sin{(T)}\,\mathrm{d}s\\
=\sin{(T)}\int_{0}^{T}\,\mathrm{d}s\\
=T\sin{(T)}.$$
Hence,
$$I=\frac12 T\sin{(T)}.$$
Comment: [Convolution integral $\displaystyle\int_0^t \cos(t-s)\sin(s)\ ds$](http://math.stackexchange.com/q/813987/123277).


Programatically create field collection into Profile2 on new user creation

Question: I've set up my own custom multi-step registration form, because I just couldn't find a way of making anything out there do what I want. I've found other questions on here like this one and this one which have basically got me 95% there. My main problem now is that I've got a series of field collections in my Profile2 fields, and I just can't seem to find out what my code needs to be in order to get it done properly.
*At this point in the code I've created a new user ($user), and their profile2 ($profile2) and I'm trying to format my fields from my form so that I can throw them all into the $profile2 object.
field_activities

field_start_year
field_end_year
field_text

My code so far is:
$field_collection = entity_create('field_collection_item', array('field_name' => 'field_activities'));
$field_collection->setHostEntity('profile', $profile2);
$field_collection->field_start_year = $entry['start_year'];
$field_collection->field_end_year = $entry['end_year'];
$field_collection->field_text = $entry['text'];
$field_collection->save(FALSE);

And the error I'm getting is:

Fatal error: Call to a member function setHostEntity() on a non-object

Which would make more sense to me if $profile2 wasn't an object, but it is.
I've got too many unknowns to figure this out at the moment, is it the right code? can I build a create a field collection item on a newly created profile2 object? do I populate all the fields of the profile object first, and then once it's saved, then add the field collections, etc.
Comment: I'd guess you need to save the profile2 object before using it as a host entity, and also the entity type is `profile2`, not `profile`, so I would guess `setHostEntity('profile', $profile2);` needs to be `setHostEntity('profile2', $profile2);` The error you're getting is saying that `$field_collection` is not an object, it doesn't mention the `$profile2` variable
Comment: Ok, thanks for this, I wasn't sure what my entity type was 'profile' or 'profile2'. I'll have a go at setting up my profile and then using it as the host, see how I get on
Comment: That comment has really helped, it made me realise where the problem lay, it's very nearly working now, it's not throwing back any errors, but it doesn't appear to actually be saving anything. Since my field collection has unlimited values, I've got this function looping through each returned answer in the form, and whilst it appears to output each new field collection entity fully filled, it doesn't get written to the profile2 information, any ideas?
Answer:
Fatal error: Call to a member function setHostEntity() on a non-object

The error means that you are trying to call setHostEntity() method on a non-object, in other words the $field_collection is not an object (NULL probably).
So please check one line before, which is:
$field_collection = entity_create('field_collection_item', array('field_name' => 'field_activities'));

So basically you are trying to load field_activities field collection, but it is not there, therefore your $field_collection is FALSE as per entity_create  API:

Return value: A new instance of the entity type or FALSE if there is no information for the given entity type.

Therefore please make sure your field_activities exists as field collection (e.g. at /admin/structure/field-collections), or add additional failing scenario to your code, so when $field_collection is FALSE, do not execute further code.
For valid examples using field collections, check: Entity metadata wrappers page.
Comment: I agree with you . vote up


Template Haskell resolve type aliases

Question: I'm using template Haskell to generate data about a type. For many reasons I need the type to be used to be "normalized". So it shouldn't be a type alias/synonym. I really don't want to disallow using type aliases in the construct since some types that are used can become huge.
So now I have the problem that when a user specifies a type it doesn't match the type I expect. For example if I have this definition:
data MyData a = MyData Int

type Foo = MyData String Int Bool

serializeMyData :: TH.Type -> TH.Q [TH.Dec]
serializeMyData ty = ..

type Foo = MyData Int

And then later in I call this serializeMyData like this:
$(serializeMyData =<< [t| Foo |] )

Then in the serializeMyData it will find a ConT Foo. This is correct since the user has specified the type alias. But is not useable for me.
So my question is how can I resolve type aliases?
Any help is appreciated!
Answer: The function resolveTypeSynonyms :: TH.Type -> Q TH.Type can be found in the library th-abstraction.

Template Haskell resolve type aliases


How to reset tp link router settings

Question: I have changed the routers IP Address to 192.168.1.1 to 192.168.3.1. But now I cant access them both. What do I do?
Answer: Set manually your ip address on your computer, like 192.168.3.20, mask 255.255.255.0.
You should be able to reach 192.168.3.1.
Answer: If this is a SOHO NAT router (D-Link, Belkin, etc.) and you have not disabled your DHCP server, then re-acquire the DHCP configuration by either rebooting or releasing and renewing. You should then be able to access the NAT router's web management interface by heading over to your default gateway address via the web browser.

How to reset tp link router settings


How to correctly choose model based on BIC?

Question: I have a question about Bayesian Information Criteria. (GARCH models)
I have looked for so many hours but still very confused about this BIC especially a negative one. As far as I am concerned it is okay to have a BIC that is negative, but the interpretation of them are different in each book on website. I am not looking for sophisticated answer just a normal explanation as if you were to explain someone who is not math or statisticians.
Given same data,length and number of observation which model is better, based on BIC?

-4.98749
-4.995782
-4.9864

I am using R software and running 3 models, GARCH-t, GJR model, and simple GARCH (1,1) model. So, I am trying to see which model is better, based only on BIC.
I have already concluded what model is better based on other factors but this makes me confused.
Comment: The origin is effectively arbitrary. Smaller BIC (further left on the number line) is better by the criterion.
Comment: You should report the software platform that you are using to do this (R, Stata, Ox, ...), because definitions can be different.
Comment: @Glen_b has already answered your question but it will help if you mention what your data is, how many observations and variables are involved etc.
Answer: To at least make sure this has an answer:
The origin is effectively arbitrary. Smaller BIC (further left on the number line) is better by the criterion.
However, one ting to beware of if you compare BICs produced in different ways (using different models, or even the same models produced on different software) is the constants involved in the likelihood; it's common to drop constant terms, but if different models/software don't treat them in an equivalent way the BICs won't be comparable. Sometimes software will tell you exactly what computation is being performed in which case you can usually sort these issues out. When they don't, some detective work may be required. With the same model on different software this is usually easy to spot (and adjust for). With different models you may be able to figure out what is happening if there's a subset of models in common.
Answer: In your example, the model with the smallest BIC value, -4.995782, can be taken as the preferred model; but the strength against the other models is nearly non-existent.    Typically one would see much larger differences between BIC scores and one model would be clearly preferred; but in your example, the three models are doing an nearly identical job of describing the data.
In fact, with such tiny BIC differences, using other factors to pick the preferred model sounds like exactly the right thing to do.
Comment: But beware of the conservatism in BIC.  AIC in most cases is more likely to find the model with the best independently-validated predictive discrimination.
Answer: I can only agree on the issue with tiny differences as this example states. In general, what I can say from my personal experience (mainly academic), BIC differences can be be treated according to the following boundaries:
If the absolute difference $\delta$ is greater 10, the smaller BIC value is considerably better.
$\mid BIC_1-BIC_2\mid > 10$
If the absolute difference $\delta$ is greater 5, the smaller BIC value is likely to be better.
$\mid BIC_1-BIC_2\mid > 5$
If the absolute difference $\delta$ is smaller 2, the smaller BIC does not indicate to be better than the other.
$\mid BIC_1-BIC_2\mid < 2$
Statistics is both, art and science.
Comment: Do you have a reference for interpreting the magnitude of the difference between BIC values in this way?
Comment: This is from the learning material of Georgia Tech's ISYE6501 class, by Prof. Sokol. Unfortunately I have no material I am allowed to share.
Comment: Following Jeffrey-Raftery's (1995) guidelines, if the difference in BICs between the two models is 0–2, this constitutes 'weak' evidence in favor of the model with the smaller BIC; a difference in BICs between 2 and 6 constitutes 'positive' evidence; a difference in BICs between 6 and 10 constitutes 'strong' evidence; and a difference in BICs greater than 10 constitutes 'very strong' evidence in favor of the model with smaller BIC.


Problems with accessing private files uploaded via file field in a webform

Question: I have a webform with a file field configured to private files. When I'm logged in as a superuser (uid=1) and trying to download the file, I get access denied.
I was trying to debug this, and this is what I noticed.
All private files served by the file_download() function that is called in the system.module. This function validates if the file exists and request the file headers using file_download_headers() function that triggers hook_file_download().
In the webform_file_download() function the module determines whether the file was a webform upload and grant or deny file access based on access to the submission. It validates access permission by calling webform_submission_access(). When I run dpm($account) in this function, I get an anonymous user when I'm trying to access the private file. When I browse recent log messages I have the entry below:
access denied   06/02/2015 - 11:23  system/files/webform/cv-uploads/cv.pdf  Anonymous

When I change the URL to file that doesn't exist, I get this:
page not found  06/02/2015 - 11:26  system/files/webform/cv-uploads/cv.FDP  admin

As you can see for some reasons when the module is trying to get access to the file that does exist, I get access denied and the user is anonymous. When the file doesn't exist, I get page not found and the user is a logged in user.
Any ideas why this happens?
UPDATE
I've added the following code to my index.php but I still get anonymous user when I'm trying to access the file.
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

+ global $user;
+ watchdog('user', '
'. print_r($user, TRUE) . '
');

menu_execute_active_handler();

I've copied over the whole site including database and files to my local machine, and I'm not experiencing this issue. There's should be some settings that does this on the live site.
UPDATE 2
I've noticed that on the live site we have a list of disabled functions that I'm not aware of. Maybe it will help somehow.
disable_functions = apache_child_terminate, apache_setenv, define_syslog_variables, escapeshellarg, escapeshellcmd, eval, exec, fp, fput, ftp_connect, ftp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put, ftp_raw, ftp_rawlist, highlight_file, ini_alter, ini_get_all, ini_restore, inject_code, mysql_pconnect, passthru, php_uname, phpAds_remoteInfo, phpAds_XmlRpc, phpAds_xmlrpcDecode, phpAds_xmlrpcEncode, popen, posix_getpwuid, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid, posix_setuid, posix_setuid, posix_uname, proc_close, proc_get_status, proc_nice, proc_open, proc_terminate, shell_exec, system, xmlrpc_entity_decode, parse_ini_file,show_source,shell_exec

Comment: What is the account id the dpm($account) gives you?
Comment: It's 0. Here's the serialized string `a:4:{s:3:"uid";i:0;s:8:"hostname";s:15:"xxx.xxx.xxx.xxx";s:5:"roles";a:1:{i:1;s:14:"anonymous user";}s:5:"cache";i:0;}`
Answer: If you are using private file system every module can prevent you from downloading a file. It comes from file_download_header function:
function file_download_headers($uri) {
  // Let other modules provide headers and control access to the file.
  // module_invoke_all() uses array_merge_recursive() which merges header
  // values into a new array. To avoid that and allow modules to override
  // headers instead, use array_merge() to merge the returned arrays.
  $headers = array();
  foreach (module_implements('file_download') as $module) {
    $function = $module . '_file_download';
    $result = $function($uri);
    if ($result == -1) {
      // Throw away the headers received so far.
      $headers = array();
      break;
    }
    if (isset($result) && is_array($result)) {
      $headers = array_merge($headers, $result);
    }
  }
  return $headers;
}

So basically you should discover which implementation of hook_file_download returns -1. You can do that by printing (or writing into watchdog) value of $function variable inside if ($result == -1) { statement (so you will know that this function is responsible for giving -1 result).
However, there is also other case when you'll get access_denied() - if none implementation of hook_file_download will return file headers.
So try to figure out which function (=> module) prevents you from downloading file, then debug that function and try to deduct why.
Comment: I did that and it returns just "webform". That's why I was debugging webform_file_download().
Answer: The problem was caused by the Varnish on the server. Below is the settings for Varnish.
# Always cache the following file types for all users. This list of extensions
# appears twice, once here and again in vcl_fetch so make sure you edit both
# and keep them equal.

if (req.url ~ "(?i)\.(pdf|asc|dat|txt|doc|xls|ppt|tgz|csv|png|gif|jpeg|jpg|ico|swf|css|js)(\?.*)?$") {
  unset req.http.Cookie;
}


Access gem source code in Cloud 9

Question: I would like to open up and edit gem source code but I can't figure out how to in cloud 9.
Stack Overflow wants me to make this question longer but it really is that simple. Where is the damn code at?
Comment: Are you still having this issue? If not please choose an answer to accept, or submit your own. Also upvote any that have been helpful
Answer: Cloud9 operates like any other terminal. The following is helpful if the gem has a unique name, as you will get fewer (better) results. I will use will_paginate for example:
sudo locate will_paginate

Since Cloud9 comes packaged with light permissions for the main user, you will benefit most from using sudo like above.
On my machine, the results include sub-directories in the two following locations:
/home/hstevens/.gem/ruby/gems/will_paginate-3.0.7
/usr/local/lib/ruby/gems/1.9.1/gems/will_paginate-3.0.7

Depending on whether you installed your gem as root or not, your results should include one or both of the above locations. (Actual paths may vary slightly.)
Comment: sudo locate gem_name doesn't do anything. I use will_paginate so I even tried that exact example. I've searched/opened files with the terminal before but it's very tedious(and won't let me open it outside the terminal). I'm asking how can I manually look through the folders the same way you browse through your application files. If anything, I would like to browse and learn about the external code I'm using and this is just too painful to do in the terminal.
Comment: Oh you are talking about the IDE's file browser? I suggest you put that in your question. And `locate` may not be installed on your VM then. I am used to it so much at work (CentOS 7) that I forget it is not installed by default everywhere.
Answer: You can find the location of gems by issuing one of the following commands:

rvm gemdir
gem environment (look for the gem path)

Access gem source code in Cloud 9


Universal coefficient theorem for homology

Question: When Hatcher discusses the universal coefficient theorem for homology (section 3.A, pg. 261), he first takes the exact sequence of chain complexes
$$0 \rightarrow Z_n \xrightarrow{i_n} C_n \xrightarrow{\partial_n} B_{n-1} \rightarrow 0,$$
where $i_n$ is the inclusion and $\partial_n$ is the boundary. Here, the complexes $(Z_n)$ and $(B_n)$ have trivial boundary maps.
Then, he shows that we can tensor it with a given abelian group $G$ to obtain a new short exact sequence of chain complexes
$$0 \rightarrow Z_n \otimes G \xrightarrow{i_n \otimes~1} C_n \otimes G \xrightarrow{\partial_n \otimes~1} B_{n-1} \otimes G \rightarrow 0.$$
From this new short exact sequence of chain complexes, he constructs a long exact sequence of homology, as usual. Because of the triviality of the boundary maps in $(B_n)$, $(Z_n)$, this long exact sequence of homology looks like this:
$$\dots \rightarrow B_n \otimes G \rightarrow Z_n \otimes G \rightarrow H_n(C; G) \xrightarrow{\Large \Phi} B_{n-1} \otimes G \rightarrow \dots$$
What I can't understand is: why is the map $H_n(C ; G) \xrightarrow{\Large \Phi} B_{n-1} \otimes G$ not always zero? After all, isn't $H_n(C ; G)$ just a quotient of the kernel of $\partial_n \otimes 1$ to begin with? And shouldn't this map, $\Phi$, be essentially induced by $\partial_n \otimes 1$??
Comment: Which *explicit* examples have you tried?
Answer: I know this is an old post, but came across it when I was asking myself exactly the same question. And I would like to share my thoughts on that.
So, I believe that the point is that the maps $\partial_n \otimes 1: C_{n} \otimes G \rightarrow B_{n-1} \otimes G $ and the boundary $ \partial_n \otimes 1: C_{n} \otimes G \rightarrow C_{n-1} \otimes G $ are not the same maps.
Indeed, let  $(\partial_n)^r : C_{n} \rightarrow B_{n-1}$ be the restriction of $ \partial_n: C_{n} \rightarrow C_{n-1} $ to its image, and let $j: B_{n-1} \rightarrow C_{n-1}$ be the inclusion. Then, notice that the map between $C_n \otimes G$ and $B_{n-1} \otimes G$ appearing in the question actually is $ (\partial_n)^r \otimes 1.$ Moreover, it is clear that $\partial_n = j \circ (\partial_n)^r.$ From this, and from the fact the tensor functor may not preserve injectivity, one can conclude that $\Phi: H_n(C, G) \rightarrow B_{n-1}\otimes G,$ which is induced by $(\partial_n)^r,$ is not necessarily zero.
Answer: The group $H_{n}(C,G)$ is defined as the homology of the sequence $$...C_{n+1}\otimes G\rightarrow C_{n}\otimes G\rightarrow C_{n-1}\otimes G...$$
If we denote the map $C_{i}\rightarrow C_{i-1}$ by $d_{i}$, then this is $\ker d_{n}\otimes i/Im  d_{i+1}\otimes i$. Here $B_{n-1}$ lives in $C_{n-1}$, and $Z_{n}$ lives in $C_{n}$. So by taking the kernel of $Im d_{i+1}\otimes i$ you can only quotient out $B_{n+1}$, not $B_{n}$. I suspect this is the source of your confusion. Some pencil and paper may be helpful for the purpose if you are confused with the notations.


post data and captcha to a site with php

Question: I am trying to post data to a url from php. I have checked codes like below from this forum.
$url = 'http://www.someurl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );

But my target site has a captcha as well.
How do I load the captcha on my php and submit it with captcha answer?
I had a look at the link. Didn't get the final solution though. How to retrieve captcha and save session with PHP cURL?
also How to retrieve captcha and save session with PHP cURL? and http://hungrycoder.xenexbd.com/general/how-to-submit-a-form-using-php-curl-fsockopen.html
My target site has code like below
<form method="post" action="action_form.php" name="frm_sms" id="frm_sms"> < input     type="hidden" name="nav" value="sms" />

I don't need to bypass the captcha but I only want to load a neat form and captcha img but no other junk and submit info with captcha answer.
Comment: to make  my site ad less and data efficient for users
Comment: What you want to do with a `target` site? (only for curiosity)
Answer: You will have to first fetch the captcha image using cURL and save the contents of any session cookie that it sets, or note the captcha identifier (depends on how their captcha works) and then save a copy of the image to your server.
Then in your form display the copy of the captcha to your visitor.  Add an input field for them enter the captcha solution add their input to your $myvars string, and send the cookie or captcha id that was set with the image along with the form post.
That's one way you can forward their captcha on to your user.  Or maybe they have an API you can sign up for.


Does every totally disconnected perfect subset of reals contain a non empty perfect subset of measure zero?

Question: It is well known that if $P$ is a totally disconnected perfect compact subset of reals, then $P$ is homeomorphic to the Cantor set. My question is that whether $P$ always contain a non empty perfect subset of measure zero?
A more particular question is the following: Let $0<r<1.$ Similar to the Cantor set, the fat Cantor set $C_r$ is obtained from the unit interval $[0,1]$ by inductively removing middle third open intervals of size $r/3, r/9$ and so on. I am interested in the collection of $r\in (0,1)$ such that  the set $C_r$ contains an uncountable null perfect subset.
Comment: Not sure yet about the first question. The second question is trivial: It's clear that every $C_r$ has measure zero. (To get a Cantor set of positive measure you need to take a variable ratio at each stage...)
Comment: Oops. Yes, your $C_r$ has positive measure - I read the definition wrong.
Answer: The answer to your first question is yes.
Let $P$ be a subset of $\mathbb R$ which is homeomorphic to the Cantor set $C=\{0,1\}^\omega.\ $ Since $C$ is homeomorphic to $C\times C,$ it follows that $P$ can be partitioned into continuum many nonempty perfect sets, most of which will have Lebesgue measure zero.
Since every uncountable Borel set contains a homeomorph of the Cantor set, it follows that every uncountable Borel set contains a nonempty perfect set of Lebesgue measure zero.


Link to send private message to current user in the node (author of the content)?

Question: Is it possible to create a link to send private message to CURRENT USER in the node (to the author of the node content to be more precise). I'm using the Privatemsg module.
I was trying to do this with the Display suite dynamic fields, but I am not able.
I found that the Privatemsg module comes with an option to "Display link on the selected content types. So, I have the "contact current member link" right in the content type, but it shows only for logged in users.
Is there any configuration or hook that I can implement to show the same link to anonymous user?
This is the code that shows the link.
function privatemsg_node_view($node, $view_mode) {
  $types = array_filter(variable_get('privatemsg_link_node_types', array()));
  $url = privatemsg_get_link(user_load($node->uid));
  if (in_array($node->type, $types) && !empty($url) && ($view_mode == 'full' || (variable_get('privatemsg_display_on_teaser', 1) && $view_mode == 'teaser'))) {
    $node->content['links']['#links']['privatemsg_link'] = array(
      'title' => t('Contact member'),
      'href' => $url . '/' . t('Message regarding @node', array('@node' => $node->title)),
      'query' => drupal_get_destination(),
      'attributes' => array('class' => 'button radius privatemsg-send-link privatemsg-send-link-node'),
    );
  }
}

To make it clearer, I don't want anonymous user to send messages. What I want is just a link to log in for anonymous users. Expressing it with pseudo-code...
global $user;

if (isset($user->roles[1])) {
  // Do not show button to Anonymous user and show something else or a button to log in (THE CODE FOR LOG IN)
  echo "something else";
}
else {
  // Show button to logged in user (the code of "Send author a message" button)
}

Comment: Privatemsg does not support private messages from anonymous users, that's why there's no link. You can't add it.
Comment: Pleaseee, understand me! I don't want anonymous user to send message.What I want is just a link to login, when the user is logged out. Just that
Comment: I've found the solution. It is explained in the answer below. Thank you
Comment: look at [this](https://drupal.org/node/1356340) and [this](https://drupal.org/node/1360752) post...you can find the answer, or at least can be helpful...
Comment: mixerowsky, thank you alot for your answer. The links you have shared is very helpful, anyway, i found that privatemsg module comes with an option to "Display link on the selected content types", and with that, you have a link "Send author a message" right in the content type or node that you want. This link can be customized with css and the text can be altered with stringoverrides module. Thank you bro ;)
Comment: Hello again mixerowsky. Do you know how to show that link to anonymous user also? Thank you
Comment: @user1754562 Privatemsg links don't work for anonymous.  There is an outstanding feature request for this: https://drupal.org/node/1988848
Comment: yes, it is impossible to send private message to anonymous user, that user is not registered...
Comment: But I DON'T want to send private message to anonymouse users (I know that this is impossible). I just want to show that link ("Send Author a Message") to anonymouse user also. Right now it show only for logged in users. thank you
Comment: There is no need to show that link, you can add link to send email to node author...try with [Contact Link](https://drupal.org/project/contactlink) or [Node feedback](https://drupal.org/project/node_feedback) module...
Comment: That's a request of my client. I'm working on it, to show that link to the anonymous users... Or maybe a link to redirect to login page. I'll be back when i did it. Thank you
Comment: than you can create field with custom text and link to login page and show that field only for anonymous users using [Field Permissions](https://drupal.org/project/field_permissions) module...
Comment: I've found the solution. It is explained in the answer below. There was no need to use that module. Thank you
Answer: I did it with a Display suite custom code field. With it I am able to use some PHP code.
global $user;
// If the user is anonymous (role=1) show this; otherwise show nothing.
if (isset($user->roles[1])) {
  print l(t('Contact member'), 'user/login', array('attributes' => array('class' => array('radius', 'button'))));
}

So, when the user is logged-in, this code above will be replaced with the contact member link (Send author a message).


How to update all injected objects with new live data

Question: I am using Dependency injection, Coordinators & the MVP design pattern.
Once a user logs into my app, I get their account object from Firestore in my AppCoordinator. This account object and other services are injected into my 'TabBarCoodinator' which injects them into all child coordinators and they do the same with presenters, etc.
init(_ navigationController: UINavigationController,
     _ firestoreRepository: FirestoreRepositoryProtocol,
     _ firebaseCloudStorageService: FirebaseCloudStorageServiceProtocol,
     _ firebaseCrashlyticsService: FirebaseCrashlyticsServiceProtocol,
     _ notificationService: NotificationServiceProtocol,
     _ account: FIRAccount,
     _ alertHandlerService: AlertHandlerServiceProtocol) {

    self.navigationController = navigationController

    super.init()

    self.coord1 = Coord1(
        firestoreRepository,
        firebaseCloudStorageService,
        geoLocationService,
        alertHandlerService,
        account,
        delegate: self)

    self.coord2 = Coord2(
        firestoreRepository,
        notificationService,
        alertHandlerService,
        account)

    self.coord3 = Coord3(
        firestoreRepository,
        firebaseCloudStorageService,
        firebaseCrashlyticsService,
        geoLocationService,
        alertHandlerService,
        account,
        delegate: self)
}

I have set up a listener in the AppCoordinator to listen for changes to the account object. When changes occur, I want this to propagate down into all other classes that the account is injected into so no objects have an outdated account object.
The problem I am facing is how to propagate account object changes to all children classes.
Each part of the app, such as the 'EditProfilePresenter', plays a role in editing a piece of the account object. An edit is made to the account object in a particular presenter and changes are pushed to Firestore.
This results in a huge issue, all account objects that have been injected into other coordinators and presenters from the AppCoordinator are now out of date. The only up-to-date object is the 'EditProfilePresenter' account object and the one held in the AppCoordinator due to the listener.
How can I either propagate the updated information to all objects using the account object or, how should I set up my objects to have a single source of truth for a user account object? Ideally, I want the injected account to reference the original stored on the AppCoordinator, not a copy or clone of it.
Things I have considered:

Set up three individual listeners for the three main parts of the app. Each listener would manage that slice of the apps account object. However, this results in 3 reads for a single update which is not great for scalability at all.
Store the account object on the FirestoreRepositoryService. Most classes requiring this service use the account object and it is instantiated in the app coordinator so should be shared throughout all classes. However, this sounds bad as it breaks the responsibility of the service simply performing Firestore related requests.
Use a singleton to manage the account state which is shared and used by all classes needing it. This would mean the account object is always kept updated in a single place with a single listener. However, this would drastically reduce testability & readability due to the account object no longer being injected as well as creating tight coupling throughout the whole app on a single object that whose state is shared everywhere.
Look into restructuring the account object where information is split into specific sections of the account object. Ideally, one tab should only deal with its assigned slice of the information and would not have the whole account object. Rather, it would have a sub-collection within the account object. However, shared information that is commonly used everywhere, such as a name, would either be stored on the account object or in a sub-collection resulting in even more reads required to maintain data and a few other drawbacks.
Setup a notification to be sent out every time the app coordinator receives an account update and register for this notification in every object that uses the account object. However, this again feels like a really poor way of dealing with the issue due to the overhead of needing to ensure every object is registered to this notification or the data will be inconsistent.

I am really not sure what to do, any help on how to deal with this would be appreciated!
Comment: I'd go with the first option. It's the cleanest solution. I'm not sure why you're concerned about the number of reads. It should be a relatively inexpensive operation.
Comment: @RobertCrabtree Because on a larger scale, one write resulting in 3 reads on a common operation within the app seems like it will add up very quickly.
Answer: I could not find an answer to this, so instead, I decided to go the Singleton route and everything is working perfectly.
My main concern with using a singleton was around the testability of the code, however, I have circumvented this through exposing an extension method on the singleton enabling me to set up mock data for the user object in my unit tests.
Sure, this means theoretically I could accidentally call it in the live code, but an aptly named function indicating it is for creating mock data is enough for me.
Furthermore, I could unit test the code on the singleton in one place and not have to repeat the same test in multiple places which is a huge plus.
Here is the code. If anyone does come up with a solution to updating injected object data that would be great.
class CurrentUserService: CurrentUserServiceProtocol {

// Vars so I can override them in unit tests
var firebaseCrashlytics: FirebaseCrashlyticsServiceProtocol
var firestoreRepository: FirestoreRepositoryProtocol

private (set) var userListener: ListenerRegistration?
private (set) var user: FIRAccount?

static let shared = CurrentUserService()

init() {
    self.firebaseCrashlytics = FirebaseCrashlyticsService()
    self.firestoreRepository = FirestoreRepository()
}

func setUser(user: FIRAccount, ref: CollecitonRef) throws {
    self.user = user
    setupAccountListener(docId: user.id, ref)
}

func setupAccountListener(docId: String, _ ref: CollectionReference) {

    userListener?.remove()

// Setup listener however you need to do it in your code
    userListener = self.firestoreRepository.readById(
        docId: docId,
        from: ref,
        returning: FIRAccount.self,
        withSnapshotListener: true) { (result, account) in

            switch result.succeeded {
            case false:
// Log error
            case true:
                if let account = account {
                    self.user = account
                } else {
                    // Log error
                }
            }
    }
}

func updateUser(_ account: FIRAccount) {
    self.user = account
}

func logoutCurrentUser() {
    self.user = nil

    userListener?.remove()
    self.userListener = nil
}

}

extension CurrentUserService {
    func setMockUserData(_ account: FIRAccount) {
        self.user = account
    }
}


Getting \displayLilyMusic to output chord symbols

Question: I have a simple jazz-style lead sheet with a melody and chord symbols.

I need to transform the input in a way that every note/chord gets its duration printed (and also its absolute pitch). For example, I want this (note that \language is set to english):
\relative c' {
  \time 6/8
  cs'4. b8 fs d | a'4. g8 d b | fs'2. | bar "|."
}

to be converted to this:
\absolute {
  \time 6/8
   cs''4. b'8 fs'8 d'8 |
   a'4. g'8 d'8 b8 |
   fs'2. | \bar "|."
}

Luckily, this is exactly what \displayLilyMusic does, and also lets you redirect the output to a text file.
Now I want the same for the chords, but with \displayLilyMusic, something like this:
\new ChordNames \chordmode {
  b2.:maj7.3- | g:maj7 | e:min7 |
}

gets converted to this:
\new ChordNames {
  2. |
  < g' b' d'' fs'' >2. |
  < e' g' b' d'' >2. |
}

You can see that duration is included, but chords are translated to notes. What I need is:
\new ChordNames {
  b2.:maj7.3- |
  g2:maj7 |
  e2:min7 |
}

Is there a way to get an output of the chord symbols instead of the notes?
Comment: a simpler / more logical syntax for your first chord (a minor chord with a major seventh) is :`b2.:min7+` or `b2.:m7+`
Comment: Thanks, @ElementsinSpace. I'm still learning and I would have thought that ```min7``` would make my 7th minor.
Answer: Essentially, no.  Chord input gets translated into notes (slightly annotated to mark the root of the chord and get the right octaves for the chosen inversion) during the input, and they get translated to a markup by the chord namer.  What exact input got used is lost in the process.
If you want to really cheat, you can pick off the input location of the chord event and then just read and regurgitate the input causing it.  Of course this will not reflect any transpositions or similar changes done to the music.
It would be tedious but comparatively straightforward to take the chord naming function and change it to crank out not a markup but an input string.  I don't think someone did this yet.
Comment: Thanks for your insights! I'll try ```quickly``` to be able to manipulate the original music text and transform it exactly how I need.
Answer: First of all: Something like g:maj7 is just syntax candy for <g' b' d' fs'>. \chordmode is a special keyword that tells the parser to create such chords. This means that after parsing the file Lilypond does not know that this was entered using \chordmode. (And there is no real functional difference between these two.) One might argue the Lilypond's way of transforming chord specifications to notes to chord names is a bit stupid, but well.
Probably the way to go would be using Frescobaldi. Frescobaldi comes with it's own Lilypond parser written in python, accessible by the python-ly package, which also provides a commandline tool ly.
Thus Frescobaldi is able to do what you want: Choose Tools->Musical Transformations->Pitches and you'll find a point for transforming relative pitch to absolute pitch. Also under Tools->Musical Transformations->Rhythm you'll find an option to make rhythms explicit (i.e. adding the duration to each note).
The relative to absolute thing can also be done using the commandline tool, but the explicit rhythms are supported by python-ly but have no option to use it from the CLI.
Comment: @nuncaeslupus Using Frescobaldi or python-ly does not transform chord mode into chords. So there is no need to transform it back.
Comment: Thank you! And what about getting the chord back from the notes or not transforming the chords at all? Is there such functionality in ```python-ly```? I have been looking at the package, but I wasn't able to find it.
Comment: I am looking at ```quickly```. It seems I would be able to get what I need using it. Thanks for directing me to the right way!
Comment: `quickly` is pretty much a somewhat early redesign of `python-ly` with all caveats that come with using early software. Basically the background is that the python lexing module `parce` has received support for lexing Lilypond code, so people behind Frescobaldi and python-ly decided to switch away from maintaining their own Lilypond lexer to using `parce`.
Comment: Actually, according to the Goal section of ```parce```'s [website](https://parce.info/overview.html#goal), "_parce_ was written to replace the LilyPond-parser in the Frescobaldi editor", so probably Lilypond code was the first language to be supported by ```parce```.
Comment: @nuncaeslupus Yes, that might be. Point is: You might run into weird situations with quickly, as it is somewhat new.


Xamarin Open Content Page In Project Android

Question: I want to open Xamarin forms page from Xamarin Android project.
I have a popup page. I want to call from project Android open popup page in current content page but not using new NavigationPage.
await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(new MyPopUpPage()));

Comment: You don't have to use a `NavigationPage` when using `PushModalAsync`
Answer: Use the following code instead
await Xamarin.Forms.Application.Current.MainPage.Navigation.PushPopupAsync(new MyPopUpPage());

The popup method is also simple
await Xamarin.Forms.Application.Current.MainPage.Navigation.PopPopupAsync();

Refer to
https://github.com/rotorgames/Rg.Plugins.Popup/wiki/Navigation#xamarinformsinavigation-navigationextension


How can my module add xml sitemap entries?

Question: I have a module with a page callback handler for the path "products". So if the user navigates to products/apples then the module presents a page about our apples, and if they go to products/oranges then etc. These pages include detail about the various products.
I would like XML Sitemap to be populated from my module. After all, it's my module that knows what products exist, their descriptions etc.
Any hook or anything I can use for that?
Answer: The base function you call is xmlsitemap_link_save().
I am unaware of any documentation on how to use this, but nodes get added to the sitemap via xmlsitemap_node_nodeapi() which in turn calls xmlsitemap_node_create_link().  The code for that should provide some guidance on how to build $link.
Comment: Brilliant, thanks. Looks like I just loop through my paths chucking them at `xmlsitemap_link_save()` with `'type'=>'custom'`. Thank you!


TransactionTooLargeException android Parcable

Question: I am getting TransactionTooLargeException while opening new activity ( with passing huge data) but I have refer few links for solution and at the end I got solution by this link I go with solution 3 (decreasing api level). It works for me.
But I want to know if there is a more convenient way to achieve this functionality or what should I do in this scenario.
Comment: Possible duplicate of [What to do on TransactionTooLargeException](https://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception)
Comment: *Google Play will require that new apps target at least Android 8.0 (API level 26) from August 1, 2018, and that app updates target Android 8.0 from November 1, 2018.* ... decreasing api level is not a solution at all
Comment: You can save the data to a database like Realm or you can save it in SharedPreference and retrieve it in the next Activity.
Comment: @Selvin okay then what should I do for this problem ? because I want save my activities state.
Comment: @AkashAmin yes you are right at your point of view to use Database and sharedPreference but at this stage I can't use those. because it need to change lot of thing in project.
Comment: Shared Preference is easy to use.You can save any type of data. If its json use a gson library to get the string value and then store it.
Comment: @Selvin do you think is there any other solution for this problem ?
Answer: I had this issue before, I had to choose between
1 - Remove unnecessary data from the object I wanted to pass around (in my case it had arrays full of data not needed on the destination Activity).
2 - Implement a singleton to pass around data. Imagine you are going from Activity A to Activity B:
Create PassDataSingleton.class:
public class PassDataSingleton {

    private static PassDataSingleton instance;
    private ObjectTypeYouWantToPassAround object;

    public static PassDataSingleton getInstance() {
        return instance;
    }

    public void setObjectIWantToPassAround(ObjectTypeYouWantToPassAround object){
        this.object = object;
    }

    public ObjectTypeYouWantToPassAround getObjectIWantToPassAround(){
        return this.object;
    }
}

and on Activity A, before starting Activity B, call
PassDataSingleton.getInstance().setObjectIWantToPassAround(yourObject);

on Activity B, you get the object:
PassDataSingleton.getInstance().getObjectIWantToPassAround();

PS:

Of course the names and types of my example can (should) be changed
This same code sample works with lists, just use ArrayList< ObjectTypeYouWantToPassAround> instead
Comment: **Singleton is not a solution for passing data between Activities ...**  It will obviously will not in case of ActivityA->ActivityB->background->proccess killed->ActivityB from recent
Answer: You could store your data in a static field, then access it from wherever you want, instead of sending large datas beetween activities. Transactions are limited to 1 mb, almost nothing for data exchange.
Or you could also store it in you user data folder, or sdcard as a temp file in your current activity, and read from that file from your new activity and then delete it.
Comment: Static field is not a solution ... It will obviously will not in case of ActivityA->ActivityB->background->proccess killed->ActivityB from recent
Comment: I meant a static field in a class that is not an activity, or else it would hold reference to the activity and leak memory. Sorry I forgot to mention. the field must not hold a referecence to a context. It really depends on what data it is, so if you do it wisely, there is no problem.
Comment: My comment is not about context leak but that it will obviously become null in this scenerio: ActivityA->ActivityB->background->proccess killed->ActivityB from recent(**static field is null and we are in ActivityB**) ...  *It really depends on what data it is, so if you do it wisely, there is no problem.* **no,** obviously **the problem will exists every time**
Comment: He could also save his data on storage like I said, it could be a possible solution for the case you describe.


How to test Websocket Client with Jest and react-testing-library

Question: I'm using create-react-app, Jest and react-testing-library for the configuration of the chatbot project.
I have a React functional component that connects to a WebSocket server and DOM changes according to WebSocket messages, for example
const LiveChat = () => {
  const [socket, setSocket] = useState(null)

   useEffect(() => {
    setSocket(new WebSocket('ws://localhost:1234'))
   }, [])

  useEffect(() => {
    socket && socket.onmessage = message => { handleAgentMessages(message.data) }
  }, [socket])

  const handleAgentMessages = message => {
     const { messageContent, messageType, secureKey } = JSON.parse(message)
     if (messageType === TEXT && messageContent) {
       alert(messageContent)
       playChatMessageSound()
     }
       ...
   }

   return (

          ...

   )
}

I want to test when a TEXT message comes, is alertbox appeared with conteining message etc. I have looked through the internet and I find jest-websocket-mock library, but it seems that I need to mock the client with this library as well, but I just want to mock server and expect the client to connect the mocked WebSocket server, do you have any ideas?
Comment: Great, this not being solves gives be great confidence...
Answer: I am not sure if this is the right way or not. But this works for me,
    global.sendMsg = null;
    global.WebSocket = class extends WebSocket {
        constructor(url) {
            super("wss://test");
            global.sendMsg = null
        }

        addEventListener(event, cb) {
            if (event === "open") {
                cb();
            } else if(event === "message") {
                global.sendMsg = cb;
            }
        }
    };

    test("testing message",() => {
      render(<LiveChat />);
      global.sendMsg({data:"test-msg"});

      expect....
    })

Basically, I overwrote the WebSocket class and stored the message event callback to a constant, and trigger it on the tests to imitate the server message.
Answer: Another way to do this is to inject the web socket server into a custom Jest environment. I had to do this due to Websocket is not a constructor error.
In your jest.config.js file
...
  testEnvironment: "./custom-dom-environment.",
...

custom-dom-environment.js
// my-custom-environment
const JsDomEnvironment = require('jest-environment-jsdom').TestEnvironment;

class CustomEnvironment extends JsDomEnvironment {
  constructor(config, context) {
    super(config, context);

  }

  async setup() {
    await super.setup();
    // Allow setting up a websocket server in jsdom environment
    this.global.WebSocketServer = require('ws');
  }

  async teardown() {
    await super.teardown();
  }

  getVmContext() {
    return super.getVmContext();
  }
}

module.exports = CustomEnvironment;


Custom Filter missing on Security Filter Chain

Question: I have a simple Security Config with one CustomFilter(MyAuthorizationFilter) added before FilterSecurityInterceptor.
<code>@Configuration
@EnableWebSecurity(debug = true)
@Profile({ "local", "test" })
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableResourceServer
public class SecurityLocalConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.addFilterBefore(new MyAuthorizationFilter(), FilterSecurityInterceptor.class);
    }

}
</code>
I see it in the logs when application is started.

2019-08-02 12:31:59.090  INFO 74924 --- [  restartedMain]
o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any
request,
[org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@28d34c24,
org.springframework.security.web.context.SecurityContextPersistenceFilter@4787d4da,
org.springframework.security.web.header.HeaderWriterFilter@2219138f,
org.springframework.security.web.csrf.CsrfFilter@2042e42,
org.springframework.security.web.authentication.logout.LogoutFilter@518b63cb,
org.springframework.security.web.savedrequest.RequestCacheAwareFilter@20d72122,
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4ab8dbdc,
org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3114a62d,
org.springframework.security.web.session.SessionManagementFilter@29a651d9,
org.springframework.security.web.access.ExceptionTranslationFilter@4d655a42,
com.test.cash.http.filters.MyAuthorizationFilter@3dfefde8]

However MyAuthorizationFilter is missing in the security chain,  when I make API call. I am not sure what is that I am going wrong with?
<code>Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  LogoutFilter
  OAuth2AuthenticationProcessingFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]
</code>
Answer: I had same question before. My situation is that it creates two filter chains that one of it contains the original 11 filters, another one contains original 11 filters and custom filters. It is possible that you use annotation @EnableResourceServer which will automatically build the filter chains of those 11 filters with higher order.


Custom preview page on Webform

Question: I want to theming only preview pages on Webform. Is it possible?
Comment: What are "good" and "easy" in this context? Don't make me drag this out of you, if you want some help, ask a proper, **specific** question! :)
Comment: Ok, getting somewhere. Please edit your question and describe exactly what it is you want to do, that will help it to remain opened, and you to hopefully receive some answers. Hint: your question will be at least a couple of paragraphs long, not a single line.
Comment: Yes. Drupal is written in PHP, therefore it will be possible.
Comment: Well, is there a good and easy solution for this? I mean, create a tpl files and edit it.
Comment: I mean, can I create a webform--preview.tpl.php file?
Answer: I find two solution links, please check them:
Sol-1: https://www.drupal.org/node/1430034 (Most relevant solution)
Sol-2: How to theme a webform - D7 (It another solution to theme webform with another tpl name: webform-form.tpl.php. Here is the link which provide tpl code.)
I guess you need to use node--webform.tpl.php and also add preprocessor in template.php.
<code>function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}
</code>
And when you create tpl file you can check preview variable to check and theme accordingly.
If this doesn't help try second solution.
See similar issue here.
Answer: You fill find it very hard to do this in a tpl.
Use a form_alter hook and check if you are on the preview step:
<code>$page_count = $form_state['webform']['page_count'];
$page_num = $form_state['webform']['page_num'];
$preview = $form_state['webform']['preview'];
if ($preview && $page_num === $page_count) {
   ...
}
</code>

Custom preview page on Webform


how to fix parse error syntax error, unexpected '"', expecting ',' or ')'

Question: Parse error: syntax error, unexpected '"', expecting ',' or ')' in /home/givecoin/public_html/script/common.php on line 475
<code>$q = $sql->prepare("UPDATE `".$dbtable_prefix."Settings` SET `value` = ? WHERE `name` = 'version'");
</code>
line475
Comment: the quotes you use around your 'version' argument don't look right, they are both different to everywhere else in the string.
Comment: @DarrenLamb The quotes look correct to me. `'version'` is a string literal and the backticks are for identifiers (column & table names)
Answer: Try by adding new line after each string part. Eg:
<code>$q = $sql->prepare(
  "UPDATE `" .
  $dbtable_prefix .
  "Settings` SET `value` = ? WHERE `name` = 'version'"
);
</code>
This won't fix the problem, but it will provide you a better line information: the code you posted does not have any parsing error, so I think your problem is before the line 475.
When PHP, or Byson/FLEX (the parser/lexer behind php), tells you that there was an unexpected character, then it tells you what it expect: the line simply correspond to where it could not find the expected characters.
If it awaits a ',' or a ')', this means you probably have an error before the line 475, for example:
<code>474. $a = ($b
//------^ missing ')'
475. $q = $sql->prepare("")
</code>
This would (I did not test) fail


Is there a term for chords where a Roman numeral would be considered meaningless?

Question: I'm trying to go deeper into my study of chromatic harmony.
I was reading through the Tonal Harmony textbook, and it says that a "simultaneity" is "a chord for which a traditional Roman numeral label would be of secondary importance." The glossary says "the use of a traditional Roman numeral label is meaningless for such chords because the resulting tones do not function in the traditional sense."
When these chords come up in the book, they simply write out the actual letter for the chord instead of a Roman numeral.
However, when I looked up this term online, I didn't see anything come up related to the definition they provided.
Have any of you encountered different terminology for chords that are better explained without the use of Roman numerals? I don't know if other texts refer to this concept in a different way once they get to areas of deeper chromatic harmony.
Let me know any thoughts or knowledge you have about this; I'd appreciate it. Thanks in advance!
Comment: I can't say I'm familiar with the term. We had a question here that I remember being about a chord with every note of D harmonic minor in it; I imagine that's the kind of scenario you're talking about, where the idea of functional harmony starts to break down into voice-leading and clustery textures.
Comment: I vaguely remember some weird chords where one triad was plonked on top of another, seemingly unrelated triad.  I definitely remember this from a jazz improv class but maybe it also came up in a classical context.  Sorry I don't remember more clearly.
Comment: @aparente001 - That reminds me of the stacked chords brought up in a question on this website about "The Point of No Return" from *Phantom of the Opera*.
Comment: @Dekkadeci - I'm not strong enough in theory to write an answer.  Would you?
Answer: Roman numerals are just one of many notation conventions; to base definitions of harmony around how well they can be conveyed by roman numerals sounds, to me, like mistaking map for the territory. There is not one single overriding reason for which a chord might fall into the category of "not being described well by roman numerals", even the simplest triad can fall into this category if it appears in an atonal piece of music.
If such a word is necessary because you are specifically talking about notation, I'd probably just make up a word like "non-numerable".
I haven't read the textbook you're referring to, but it sounds like it might be hinting at non-functional harmony?
Answer: Roman numerals are useful for describing music with a well-defined tonic.  Once you start having to describe a chord as 'V7 of III of bVII' (and I've seen worse) it's time to just use chord names 'E7, Am6 etc.'  And in today's music we can get out of that realm pretty quickly.
A 'simultaneity' as I understand it is a collection of notes that can't even be usefully named in this way without monstrosities like 'F♯m9add6sus2(omit root)' (and I've seen worse than that too!)   The voices just lead to a combination of notes with no useful name, functional or descriptive.  Stop looking for shortcuts, write the notes!
I don't think 'simultaneity' can be considered a standard term.  If you want to use it in an essay or something, better explain it.
Comment: 'V7 of III of bVII' – I'd rather say this should be described as "V⁷ of Ⅱ", or "Ⅴ⁷ of Ⅴ of Ⅴ" which is plausible enough.


How do I let the module know where the external library is located?

Question: On a fresh installation of Drupal 8, I installed a third-party module that requires an external library. I uploaded the library to the site.
How do I let the module know where the external library is located?
Comment: What module did you install and how did you install it?
Comment: Generally, modules need to be installed with Composer, which will handle the installation of the libraries for you. That said, sometimes modules do it differently. See if you can find documentation on the download page, or a README in the module folder for installation instructions.
Comment: International Phone is the module in question.  I don't have a test system set up on my PC and I don't want to go that way.  The server is my test system.  Therefore, Composer is out of the question.  That said, surely there must be a manual way to point to the desired file location.
Comment: Composer is not listed as a requirement of Drupal 8, but it's essentially required. I've never seen anyone who has been able to put together a proper tutorial on how to use D8 without Composer. See this person's comments: https://www.drupal.org/forum/support/installing-drupal/2020-05-18/installing-drupal-8-with-or-without-composer#comment-13620817
Answer: The International Phone module's page says that Composer is required to install the module. The module doesn't have a setting page where you can say where the library has been copied, and that is expected, from a module that requires Composer.
Composer is not a tool you normally use on a production server, and using the production server as test server is pretty wrong.
When I have to install Drupal on a shared hosting that doesn't allow me to use SSH, I install Composer on the local computer, I use a Composer template to copy  Drupal in a directory and I add the modules I need with composer require. I can then use that directory for a local site where I can verify that adding a module, or updating the site, doesn't cause issues.
When a module requires Composer, there aren't other ways to let it know where the libraries from which it depends have been installed.
They are loaded from the autoload.php file created from Composer. You could manually create that file, but that would be a bad idea, especially because that file is created basing on some settings present in the composer.json file that comes with Drupal core.
Answer: Yes, I was told by several individuals that a server was not the place to develop Drupal apps.  While clutching their pearls in horror, what they didn't understand is that the server is not a production server, but simply a space I rent on a server to experiment with Drupal.
However, as I have now spent two months reading, studying, and experimenting, I see that Drupal development really has to be done on a PC or similar and then uploaded.  It is unfortunate that a server-based system cannot be developed on a server.  But it is what it is.
I have therefore made the decision to stop trying to make Drupal work for me.  Instead, I am going with HTML5 and JQuery and build my own system.  After two months of this, I probably could have already had a working system.
Comment: Yeah, Drupal has a steep learning curve. Generally, you need to build a few sites first to learn how it works, before you can branch out and start building creative sites that do new things.


response.getOutputstream error to generate piechart

Question: I am putting
OutputStream outStream = response.getOutputStream();

in my jsp file to open the excel file in browser.
I am getting exception,
   java.lang.IllegalStateException: OutputStream already obtained

Source
<%@page import="java.io.File"%>
<%@page import="java.awt.Image"%>
<%@page import="org.jfree.chart.ChartRenderingInfo"%>
<%@page import="org.jfree.chart.entity.StandardEntityCollection"%>
<%@page import="org.jfree.chart.ChartUtilities"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.io.OutputStream"%>
<%@page import="org.jfree.chart.JFreeChart"%>
<%@page import="org.jfree.chart.ChartFactory"%>
<%@page import="org.jfree.data.general.DefaultPieDataset"%>
<%@page import="java.awt.image.RenderedImage"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>

<%
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Poor", new Double(43.2));
dataset.setValue("Average",  new Double(55.2));
dataset.setValue("Good",  new Double(4.2));
dataset.setValue("Excellent", new Double(43.2));
JFreeChart chart = ChartFactory.createPieChart("MY CHARTR", dataset, true, true, true);
OutputStream os=response.getOutputStream();
RenderedImage image = chart.createBufferedImage(800, 800);
ImageIO.write(image,"png", os);
%>

Exception:
java.lang.IllegalStateException: getOutputStream() has already been called for this response

Answer: You have already written to the outputstream when outputting ...tags. Remove the html tags and just leave the JSP scriptlets. It would also be advisable to not have linebreaks between the scriptlet tags


Drupal_goto => POST $result as node Title

Question: In order to be able to add a new node whenever a searched string is not found, I've added the following code in my theme directory as search-results.tpl.php.
<?php if ($search_results): ?>

<?php print t('Search results');?>

  <ol class="search-results <?php print $module; ?>-results">
    <?php print $search_results; ?>

  <?php print $pager; ?>
<?php else: ?>
  <?php drupal_goto('node/add'); ?>
<?php endif; ?>

After clearing the cache, this works fine.
Is it possible to POST the searched string to the node/add section? For example, if I am looking for "car" and the string is not found, I should be redirected to node/add  with "car" showed as node title.
Answer: You add this line before your code:
$search_term = arg(2);
Send it in your drupal_goto, but you need to specify which content type to add (here i chose "article"):
<?php drupal_goto('node/add/article', array('query'=>array('title'=>$search_term))); ?>
And hook your node form in a custom module (here I chose content type "Article") :
function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Find the content type of the node we are editing.
  $content_type = $form['#node']->type;
  if ($content_type == 'article') {
    if(isset($_GET['title'])){
      $form['title']['#default_value'] = $_GET['title'];
    }
  }
}

Comment: You should sanitize the string though.
Comment: Definitely, you need to perform more check than that, I just put the "required" one (isset). And there could also be some trouble with URL encoding for special characters, you should check that too.
Comment: Hi , just to be sure when creating a custom module, the name of the function has to be he same as the name of the module?
Comment: Yes, if your module name is "my_custom_module", then the function name should be "my_custom_module_form_node_form_alter"
Comment: Thanks , Do you think that i can change the 'node/add/article' by a variable defined trough a popup box? where I have for example the choice between 3 different node types.
Comment: I don't like popups so what I would do is redirecting to a custom page that you create, grab the URL argument "title" and build the links to your 3 content types adding the "title" argument to each link. Here is a link to create link in the proper drupal way and adding the title parameter: https://api.drupal.org/comment/13259#comment-13259
Answer: There's a module for that: Prepopulate.
Well, actually this module will only handle the link, prepopulating the fields you declare in the link. So you will not have to alter any form, but you will still have to prepare the correct link with drupal_goto().


O que significa byte*?

Question: Estou estudando criptografia e peguei um exemplo em AES.
No código tem esse byte* e até mesmo *variavel e não consegui entender o que significa.
Este é o bloco que utiliza isto, citado acima:
 byte* byteArray = (byte*)unmanagedBytes.ToPointer();
 byte* pEnd = byteArray;
 while (*pEnd++ != 0) { }
 int length = (int)((pEnd - byteArray) - 1);
 secureStringBytes = new byte[length];
 for (int i = 0; i < length; ++i)
 {
      secureStringBytes[i] = *(byteArray + i);
 }

Este bloco está quase no final deste link.
Answer: byte não tem muito segredo é um tipo de dado que tem 1 byte e os valores possíveis dele vão de 0 à 255, é como se fosse um int, só que tem uma capacidade de representação menor de números diferentes.
O * aí não é multiplicação, isso é o que se chama de ponteiro, portanto quando você usa um byte * em uma variável está dizendo que o tipo desta variável é um ponteiro para byte e por isso ele é muito diferente do próprio byte, desta forma cria-se uma indireção e assim acessa o dado em si, o byte, de forma indireta através dessa variável.
Neste caso específico é usado para fazer aritmética de ponteiros, então vai navegando por um conjunto de bytes um por um. Não é muito diferente de ter um byte[] (internamente esta forma usa aritmética de ponteiro, mas de uma forma específica), mas é uma forma muito mais simples e eficiente. Pode ver aquele operador de incremento, ele não está somando 1 no valor do byte e sim no endereço dele, ou seja, ele está indo para o próximo endereço disponível ali, como é um tipo byte ele vai para o próximo byte. Você pode ir somando ao endereço indefinidamente, pode até acessar algum byte indevidamente, o controle é seu, não é como código C# normal que há um controle, e este é o motivo de ser eficiente. Este caso dá para ver que é seguro sem ter que verificar em cada operação se está dentro da área do objeto.
Isto só é usado quando precisa de muita performance ou fazer algo que o jeito padrão do C# não permite, e note que isto só é possível em um contexto unsafe já que perde-se um pouco da segurança de acesso à memória. Não a toa foi usado em criptografia.
Este trecho mostra bem como é semelhante ao array:
*(byteArray + i)

Isto é exatamente o mesmo que fazer:
byteArray[i]

Coloquei no GitHub para referência futura.
Aquele código está pegando o endereço contido em byteArray, somando o valor de i e aí pegando o valor que está neste endereço (a tal da indireção), então o ponteiro (*) usado neste contexto é como se diz "acessar o valor contido neste endereço). O código do array mesmo tem verificações de segurança, por isso é mais lento.
Hoje C# tem formas diferentes de obter o mesmo resultado (uma delas), com mesma eficiência sem usar código unsafe e portanto ponteiros, mas nem todos cenários o ponteiro ainda é dispensável.
É extremamente raro precisar usar este tipo de coisa e quase todos programadores C# nunca usarão diretamente.
Answer: Resposta curta: * significa ponteiro, ou seja byte* significa ponteiro para byte.
O uso de ponteiros significa, de forma rasa, que você vai lidar com a memória.
Para entender mais a fundo é só pegar algum conteúdo sobre ponteiros em C#, por exemplo:
http://www.linhadecodigo.com.br/artigo/1659/usando-ponteiros-em-csharp.aspx

O que significa byte*?