text:
Q: Energy-momentum tensor of Bosonic Ghost Action in String Theory When quantizing bosonic string theory by means of the path integral, one inverts the Faddeev-Popov determinant by going to Grassmann variables, yielding:
$$
S_{\mathrm{ghosts}} = \frac{-i}{2\pi}\int\sqrt{\hat{g}}b_{\alpha\beta}\hat{\nabla^{\alpha}}c^{\beta}d^2\tau,
$$
where the $-i/2\pi$ just comes from convention/Wick rotated or not. My first problem is the notion of the 'fudicial' metric $\hat{g}$. I find its role in the path integral procedure a bit confusing. What is its relation to the 'normal' metric $g$? Why is it introduced? Related to this confusion is that fact in my lecture notes it is said that the energy momentum tensor is given by:
$$
T_{\alpha\beta} :=\frac{-1}{\sqrt{\hat{g}}}\frac{\delta S_g}{\delta\hat{g}^{\alpha\beta}} = \frac{i}{4\pi}\left( b_{\alpha\gamma}\hat{\nabla}_{\beta}c^{\gamma} + b_{\beta\gamma}\hat{\nabla}_{\alpha}c^{\gamma} - c^{\gamma}\nabla_{\gamma}b_{\alpha\beta} - g_{\alpha\beta}b_{\gamma\delta}\nabla^{\gamma}c^{\delta} \right),
$$
I have trouble deriving this. Varying the $\sqrt{\hat{g}}$ in the action yields the last term I would say:
$$
\delta\sqrt{\hat{g}} = -\frac{1}{2}\sqrt{\hat{g}}\hat{g}_{\alpha\beta}\delta \hat{g}^{\alpha\beta}
$$
 However, this term does not have a 'hat' on the covariant derivative, which I find strange. The first and second term follow easily when writing the action with all indices low (except for a factor of 1/2), but I really don't see where the third term comes from and it also misses a hat on the covariant derivative. It looks like there has been done a partial integration, but I don't see why. I guess I am missing the point of the fiducial metric here. Explanation greatly appreciated!
EDIT: In the discussion below I mentioned that $b_{\alpha\beta}$ is traceless: $b_{\alpha\beta}g^{\alpha\beta} = 0$, I forgot to place that here. It is a consequence of the path integral procedure.

A: Here's part of my answer to the derivation of the EM tensor for the ghost action. It does not match the expression you gave, but I may have made a mistake. Can you check my work?
We start with the action
\begin{equation}
\begin{split}
S_{gh} &= - \frac{i}{2\pi} \int d^2 \sigma \sqrt{g} g^{\alpha\mu} b_{\alpha\beta} \nabla_\mu c^\beta \\
\end{split}
\end{equation}
Let us now vary the action w.r.t. metric. We get
\begin{equation}
\begin{split}
\delta S_{gh} &= - \frac{i}{2\pi} \int d^2 \sigma \left( \delta \sqrt{g} \right) g^{\alpha\mu} b_{\alpha\beta} \nabla_\mu c^\beta  \\
&~~~~~~~~~~~~~~~~~- \frac{i}{2\pi} \int d^2 \sigma \sqrt{g} \left( \delta g^{\alpha\mu} \right) b_{\alpha\beta} \nabla_\mu c^\beta  \\
&~~~~~~~~~~~~~~~~~- \frac{i}{2\pi} \int d^2 \sigma \sqrt{g} g^{\alpha\mu} b_{\alpha\beta} \delta \left( \nabla_\mu c^\beta \right) \\
&= - \frac{i}{4\pi} \int d^2 \sigma  \sqrt{g} \left[ b_{\alpha\mu} \nabla_\beta c^\mu + b_{\beta\mu} \nabla_\alpha c^\mu   - g_{\alpha\beta}   b_{\rho\sigma} \nabla^\rho c^\sigma \right]  \delta  g^{\alpha\beta}   \\
&~~~~~~~~~~~~~~~~~ - \frac{i}{2\pi} \int d^2 \sigma \sqrt{g} g^{\alpha\mu} b_{\alpha\beta} c^\lambda    \delta \Gamma^\beta_{\mu\lambda} \\
\end{split}
\end{equation}
We now use
\begin{equation}
\begin{split}
\delta \Gamma^\beta_{\mu\lambda} = \frac{1}{2} g^{\beta\rho} \left[ \nabla_\lambda \delta g_{\rho \mu} + \nabla_\mu \delta g_{\rho \lambda} - \nabla_\rho \delta g_{\mu\lambda}\right]
\end{split}
\end{equation}
Note that in particular, it is a tensor. The last term then becomes
\begin{equation}
\begin{split}
I &=   - \frac{i}{2\pi} \int d^2 \sigma \sqrt{g} g^{\alpha\mu} b_{\alpha\beta} c^\lambda    \delta \Gamma^\beta_{\mu\lambda}  \\
&=   - \frac{i}{4\pi} \int d^2 \sigma \sqrt{g}  b^{\mu\rho} c^\lambda \left[ \nabla_\lambda \delta g_{\rho \mu} + \nabla_\mu \delta g_{\rho \lambda} - \nabla_\rho \delta g_{\mu\lambda}\right]\\
&=   - \frac{i}{4\pi} \int d^2 \sigma \sqrt{g}  b^{\mu\rho} c^\lambda   \nabla_\lambda \delta g_{\rho \mu}  \\
&= - \frac{i}{4\pi} \int d^2 \sigma \sqrt{g}     \nabla_\lambda \left( b_{\alpha\beta} c^\lambda \right)  \delta g^{\alpha\beta}
\end{split}
\end{equation}
We then have
\begin{equation}
\begin{split}
\delta S_{gh}  &= - \frac{i}{4\pi} \int d^2 \sigma  \sqrt{g} \left[ b_{\alpha\mu} \nabla_\beta c^\mu + b_{\beta\mu} \nabla_\alpha c^\mu   - g_{\alpha\beta}   b_{\rho\sigma} \nabla^\rho c^\sigma +   \nabla_\lambda \left( b_{\alpha\beta} c^\lambda \right)  \right]  \delta  g^{\alpha\beta}
\end{split}
\end{equation}


text:
Q: getPathValue() function for deep objects with arrays and with packed JSON For background, please refer to this question:
Access deep object member of embeded JSON
The solutions offered there worked very well with the packed JSON contained in key values.
However, they don't handle the situation where JSON has arrays.
The original function I referenced in the other question DID handle arrays, but it would not handle the packed JSON.
This is the original function:
function getPathValue(obj, path) {
    return new Function('_', 'return _.' + path)(obj);
}

and this is the answer from the first question:
function getValue(object, path) {
    return path
        .split('.')
        .reduce((o, k) => (typeof o === 'string' ? JSON.parse(o) : o)[k],
object);
}

Again, both work well, but neither offers the whole package.
I need a solution that will do both and it must work in IE11's ES5.
Here is a sample API returned JSON string:
{"id":"0001","type":"donut","name":"Cake","ppu":0.55,"batters":{"batter":[{"id":"1001","type":"Regular"},{"id":"1002","type":"Chocolate"}]},"data":"{\"domain\":\"cooking.com\",\"id\":53819390}"}

I'd like to be able to query values with a path string, for example:
value = getPathValue(obj, 'batters.batter[2].id');

or
value = getPathValue(obj, 'type');

or
value = getPathValue(obj, 'data.domain');

A: You could replace the brackets and take the remaining values as keys. Inside of the reducing, you could use a default object for not given objects.

function getValue(object, path) {
    return path
        .replace(/\[/g, '.')
        .replace(/\]/g, '')
        .split('.')
        .reduce(function (o, k) {
            return (typeof o === 'string' ? JSON.parse(o) : (o || {}))[k];
        }, object);
}
var object = {"id":"0001","type":"donut","name":"Cake","ppu":0.55,"batters":{"batter":[{"id":"1001","type":"Regular"},{"id":"1002","type":"Chocolate"}]},"data":"{\"domain\":\"cooking.com\",\"id\":53819390}"},
    path = 'batters.batter[1].id';

console.log(getValue(object, path));

A: The following would do the job using a Regex on each value :

const data = {
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters": {
        "batter": [
            {
                "id": "1001",
                "type": "Regular"
            },
            {
                "id": "1002",
                "type": "Chocolate"
            }
        ]
    },
    "data": "{\"domain\":\"cooking.com\",\"id\":53819390}"
}

function getValue(object, path) {
    return path
        .split('.')
        .reduce(function (o, k) {
            const indexSearch = (new RegExp(/\[([0-9]*)\]/)).exec(k)
            const index = indexSearch ? indexSearch[1] : null
            k = k.replace(/\[[0-9]*\]/, '')
            const sub = (typeof o === 'string' ? JSON.parse(o) : o)[k]
            return index ? sub[index] : sub;
        }, object);
}

console.log(getValue(data, 'batters.batter[1]'))
console.log(getValue(data, 'data.domain'))
console.log(getValue(data, 'batters.batter[1].id'))

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to covert Symfony1.4 Doctrine:Query to Normal Mysql Query i have searched a lot about how to convert symfony doctrine query into normal mysql query for debugging purpose.
like i have in codeIgniter
$this->db->last_query();

it convert active records to mysql normal query for debugging purpose.
so my question is it possible to covert doctrine to normal query for debugging purpose in symfony 1.4 or symfony2, and what are the keywords.
my doctrine query is
$q_fixed = Doctrine_Query::CREATE()
                ->select('u.name')
                ->from("fields u")
                ->where("u.field_type_id=?", "1")
                ->leftJoin("u.FieldType t")
                ->leftJoin("u.FieldCategory c")
                ->groupBy("u.id");

how to convert it to normal mysql query?
your help will be appreciated.
Thank You

A: In symfony2 you can use getSql() on your queried object ,but for the bound parameters you will have ? in query instead of provided parameters,it will not give you the full query with the provided parameters
$query = $this->createQueryBuilder('u');
$query->select('u.name')
            ->from("fields u")
            ->where("u.field_type_id=?", "1")
            ->leftJoin("u.FieldType t")
            ->leftJoin("u.FieldCategory c")
            ->groupBy("u.id");
echo $query->getQuery()->getSql();

A: Just run the dev version of the controller and copy it from the debugging toolbar.
$configuration = ProjectConfiguration::getApplicationConfiguration('myapp', 'dev', true);

A: In Symfony 1.4 you can use getSqlQuery() method of Doctrine_Query object. It will return sql query converted from dql. Note that it may include placeholders instead of actual values of parameters, you will need to replace the ?'s with the correct values when you execute it.


text:
Q: How to get the value of a float in a string in C, using only, printf, scanf, while, if, and for I just begin to learn C and here is my program whose task is to get a value of float number inside a string. The program will stop when meet character '$'. It find where the floating point is located and then using its location as reference to get the value. There's no problem in compiling but when running, , it return 0.000 for any input value
I can't find what's wrong in this program so
here is my code
#include "stdio.h"
float power( int x, int y);
int main()
{
    int i=0, e=0;
    float x=0;
    char str[100];
    scanf("%s", str[0]);
    for (i=0; i<100; i++){
        if (str[i]='.'){
            for (e=0; e<i; e++){
                x += str[e]*power((i-e-1),10);
            }
        }
        break;
    }
    i++;
    while (str[i]!='$'){
        x += str[i]*power((e-i),10); // str[e] == '.'
        i++;
    }
    printf("%f", x);
    return 0;
}

float power( int x, int y) //simple power for int base
{
    int i, temp;
    temp=y
    if (x>=0){
    for(i=0; i<x; i++){
    }
        y=y*temp;
    }
    else{
            for(i=0; i>x; i--){
                y=1/temp;
            }
    }
    return y;
}

A: The problem is here
scanf("%s", str[0]);

maybe you mean
scanf("%s", &str[0]);

or even better
scanf("%99s", str);

and do not ignore the return value, if it happens to be EOF then what happens next will be undefined.
To convert the string to a floating point number use strtof(), this way
char *endptr;
float value;

value = strtof(str, &endptr);
if ((*endptr != '\n') && (*endptr != '\0'))
    printf("Cannot convert `%s' to float\n", str);
else
    printf("%f\n", value);

but you could also and it's the preferred approach
float value;

if (scanf("%f", &value) != 1)
    printf("Cannot convert `%s' to float\n", str);
else
    printf("%f\n", value);


text:
Q: simple linq-to-sql query exception I am playing with Linq-To-Sql for the first time on the phone. I have created a simple class, but anything other than a basic select query, i.e. 'from p in db.Icons select p' throws an exception.
        var q = from p in db.Icons
                where p.Name == "testa"
                select p;
        // ^ Throws 'The member Icon.Name has no supported translation to SQL'

I also have 2 more questions in addition to the cause of the exception that are inside the source code I pasted below:
[Column]
private bool _isFavourite = false; // Does this actually set a default value?
                                   // Should I use Nullable<T> for value types?
                                   // i.e. should this be 'bool?' instead.

-
public Table<Icon> Icons
{
    get // Is this getter necessary? Wouldn't 'Table<Icon> Icons' suffice?
    {
        return this.GetTable<Icon>();
    }
}

source:
    //Icon.cs
    [Table]
    public class Icon : INotifyPropertyChanged, INotifyPropertyChanging
    {
        private const string IdPropertyName = "Id";
        private const string NamePropertyName = "Name";
        private const string IsFavouritePropertyName = "IsFavourite";
        private const string IconUrlPropertyName = "IconUrl";

        [Column(IsPrimaryKey=true, IsDbGenerated=true)]
        private int _id;
        [Column]
        private string _name;
        [Column]
        private bool _isFavourite = false; // Does this actually set a default value?
                                           // Should I use Nullable<T> for value types?
                                           // i.e. should this be 'bool?' instead.
        [Column]
        private string _iconUrl;

        public int Id
        {
            get
            {
                return _id;
            }

            set
            {
                RaisePropertyChanging(IdPropertyName);
                _id = value;
                RaisePropertyChanged(IdPropertyName);
            }
        }

        public string Name
        {
            get
            {
                return _name;
            }

            set
            {
                RaisePropertyChanging(NamePropertyName);
                _name = value;
                RaisePropertyChanged(NamePropertyName);
            }
        }

        public bool IsFavourite
        {
            get
            {
                return _isFavourite;
            }

            set
            {
                RaisePropertyChanging(IsFavouritePropertyName);
                _isFavourite = value;
                RaisePropertyChanged(IsFavouritePropertyName);
            }
        }

        public string IconUrl
        {
            get
            {
                return _iconUrl;
            }

            set
            {
                RaisePropertyChanging(IconUrlPropertyName);
                _iconUrl = value;
                RaisePropertyChanged(IconUrlPropertyName);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangingEventHandler PropertyChanging;
        public void RaisePropertyChanging(string propertyName)
        {
            PropertyChangingEventHandler handler = PropertyChanging;
            if (handler != null)
            {
                handler(this, new PropertyChangingEventArgs(propertyName));
            }
        }

    }

-
//IconsManagerContext.cs
public class IconsManagerContext : DataContext
{

    public Table<Icon> Icons
    {
        get // Is this getter necessary? Wouldn't 'Table<Icon> Icons' suffice?
        {
            return this.GetTable<Icon>();
        }
    }

    private const string DbConnectionString = @"DataSource=isostore:/IconsManager.sdf";
    public IconsManagerContext()
        : this(DbConnectionString)
    {

    }

    public IconsManagerContext(string connectionString)
        : base(connectionString)
    {
        if (!DatabaseExists())
        {
            CreateDatabase();
            Icons.InsertAllOnSubmit<Icon>(new List<Icon>()
            {
             new Icon() {
                 IconUrl="/Images/testa.jpg",
                 Name="Testa",
                 IsFavourite=true
             },
             new Icon() {
                 IconUrl="/Images/testb.jpg",
                 Name="Testb",
             }
            this.SubmitChanges();
        }
    }
}

-
//MainPage.xaml
 public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        using (var db = new IconsManagerContext())
        {
            var q = from p in db.Icons
                    where p.Name == "testa"
                    select p;
            // ^ Throws 'The member Icon.Name has no supported translation to SQL'

            IconsListBox.ItemsSource = q;
        };
    }
}

A: You don't have a property Named Name and marked as [Column] so you shouldn't be surprised to get an exception. Mark your properties with [Column] instead of fields and it should work.
You should read that WP7 SQL CE series: http://windowsphonegeek.com/tips/Windows-Phone-Mango-Local-Database(SQL-CE)-Introduction


text:
Q: How do I get write access to the underlying vector entries of a range-v3 view and assign values of another view to it? Having a matrix stored in a vector of row-major order, I want to get write access to a column-view (to the corresponding vector entries).
Is it possible to somehow dereference a range-v3 column-view and directly assign the values of another view to it?
So far, I found a workaround using zip:view but I am not 100% satisfied with the solution.
wandbox
std::vector<int> mat_as_vec = rv::ints(1, 12 + 1);
auto col_0 = mat_as_vec | rv::drop(0) | rv::stride(3);
auto col_1 = mat_as_vec | rv::drop(1) | rv::stride(3);
auto col_2 = mat_as_vec | rv::drop(2) | rv::stride(3);

//What I want to write is
auto new_col_0 = rv::zip_with([](auto c1, auto c2) {
    return 10 * c1 + c2;
    }, col_1, col_2);
//and then just dereference the view of col_0 and assign the new_col_0 to it
//*col_0 = new_col_0;

//Workaround:
for ( auto [c0, c1, c2] : rs::zip_view(col_0, col_1, col_2) ){
    c0 = 10 * c1 + c2;
}


text:
Q: redux toolkit createAsuncThunk thunkApi return types I'm trying to delete a todo while using thunkApi.fulfillwithValue and thunkApi.rejectWithValue but I cant seem to get the types right.
import { createAsyncThunk } from '@reduxjs/toolkit';
interface DeleteTodoError {
  message: string;
}
interface DeleteTodoSuccess {
  message: string;
}
export const deleteTodos = createAsyncThunk<DeleteTodoError | DeleteTodoSuccess, number>(
  'todos/delete',
  async (todoId: number, thunkApi) => {
    try {
      const response = await fetch(`${process.env.baseUrl}/todos/${todoId}`, {
        method: 'delete',
      });
      if (response.status === 200) {
        return thunkApi.fulfillWithValue({
          message: 'todo deleted successfully',
        });
      }
    } catch (error) {
      return thunkApi.rejectWithValue({
        message: 'failed to delete todo',
      });
    }
  }
);

A: The rejected type is defined in the third generic argument.
You can find the docs on that here
export const deleteTodos = createAsyncThunk<
DeleteTodoSuccess,
number,
{
  rejectValue: DeleteTodoError
}
>(


text:
Q: Any advantage of having a second index with included columns on a primary key? I'm reviewing our database and noticed that on a particular table we have the following indexes:
Table:
Col1    INT IDENTITY(1,1) Primary Key
Col2    INT
...
about 15 more columns
....
ColN   VARCHAR(50)
....
another 10 more columns

In addition to the standard primary key clustered index on Col1, we also have the following index:
create nonclustered index [iTable-Col1] ON [dbo].[Table1]
(
    Col1
)
include ( ColN )

We regularly search by Col1 and want to only retrieve ColN. This index does get used as it is the smallest index that contains all of the data required to satisfy the query.
My question is, does this index add any benefit to SQL Server? Would we be better off dropping it and just doing a search on the clustered index?
My only thought is that this index is much smaller than the clustered index (25mb vs 300mb) which may make searching and/or caching faster.
Server is SQL Server 2012 if that makes any difference.

A: Most of the time, this type of index is only useful for index scans against those columns.
The index tree structure above the leaf level will usually be very similar in terms of tree levels, so if that's the case, there's little or no performance difference in navigating the tree for seek operations (that don't also scan). If you want to learn the basics of index internals, I have a video here that will help you.
Anyways, back to the scans. The reasons why this index would be useful are much less about the index itself, and more about why not to scan the clustered index (or keep those data pages in memory). If the other columns make the table relatively wide (based on the sizes you gave, I would say they do, although it's unclear how large this table is in the context of the entire database), the narrow index may be of benefit in some cases. Frequent scans (or seeks on many different key values) will tend to keep the entire index in memory, so the larger the index, the less memory space there will be for other objects, and of course this will incur more I/O if the buffer pool is cold.
Although it's somewhat of a rare use case (I've done it once or maybe twice that I can remember), the biggest benefit of this type of index is it will greatly help queries that want to use a merge join to join this table. (Note: optimize the query first if an index scan isn't appropriate!) In the query plan, a scan of the clustered index, or a scan and sort of a nonclustered index before a merge join can give an indication of when this might be a good idea. But again, this is rare. The query should be executed frequently enough, or the base table expensive enough to keep stuck in memory (i.e., you don't need it there all the time), to justify the extra storage and maintenance for the index.
If you're unsure how this index is being used right now, check the DMV sys.dm_db_index_usage_stats. Bear in mind that the counts are reset on server restart, so if you're considering dropping the index, make sure it isn't useful during the entire business cycle.

A: Let SQL Server answer your question, if the index is useful the Query Optimizer will use it, otherwise it won't.


text:
Q: How to cluster standard errors (by country) using SPSS? I'm trying to obtain robust standard errors as my regression residuals seem to be correlated... My sample data has 8 countries and I would like to cluster the standard errors by these 8 countries using SPSS...
I have read that you can use STATA to do it but I only have SPSS installed in my laptop.. help.. does anyone know any short cuts or macros written for this?
Thank you!!!


text:
Q: EF with a Linked Server? Is it possible to use Entity Framework with a linked server?
I was hoping to do database first, but the UI asks you to "Select or enter a database name."  I'm wondering if that may not be possible.
If it's not, I could settle for code first, though my googling has yet to show me any explicit evidence that it works there either.
Probably a dumb question but I don't want to spend too much time only to find out it can't be done yet.


text:
Q: Cognos filter linked to checkbox Is it possible to link between filter and promptcheck box
I want when check box is yes to procced with
[BUSINESS VIEW].[All Business View].[NEXTSTAGE] in ?NEXTSTAGE?
else
[BUSINESS VIEW].[All Business View].[NEXTSTAGE] include 'Arrival announced'
is that possible? i did read if and case statment aren't well in filters and was wondering if we can add it on check box parameter
Thanks!!

A: Lets say your checkbox feeds into a Parameter called 'pArrivalChoice'.  You set it to return 'Yes' when they pick yes, and 'No' when they pick 'No'.
( ?pArrivalChoice? = 'Yes' AND
  [BUSINESS VIEW].[All Business View].[NEXTSTAGE] in ?NEXTSTAGE? )
   or ( ?pArrivalChoice? = 'No' AND
         [BUSINESS VIEW].[All Business View].[NEXTSTAGE] include 'Arrival announced' )

If you want a single check box for yes, and unchecked returns No, then you are going to have to do some scripting of the controls on the prompt page using an HTML item.


text:
Q: When using the target option in terraform, why does it sometimes return other resources alongside the one targeted? I was creating a cloudwatch alarm in my ELB stack like so:
module "elb_sg" {
  source                   = "git@github.com:terraform-aws-modules/terraform-aws-security-group.git"
  name                     = "${local.name}-elb-sg"
  description              = "Allow internet inbound traffic"
  vpc_id                   = "${data.terraform_remote_state.vpc.vpc_id}"
  ingress_with_cidr_blocks = "${data.null_data_source.elb_sg_rules.*.inputs}"
  tags                     = "${local.tags}"

  # Open egress for all
  egress_with_cidr_blocks = "${local.open_egress}"
}

#  ELB
module "elb" {
  source                      = "git@github.com:terraform-aws-modules/terraform-aws-elb.git"
  name                        = "${local.name}"
  subnets                     = ["${split(",",local.elb_subnets)}"]
  internal                    = "${var.internal}"
  security_groups             = "${local.elb_security_group_ids}"
  cross_zone_load_balancing   = "${var.cross_zone_load_balancing}"
  idle_timeout                = "${var.idle_timeout}"
  connection_draining         = "${var.connection_draining}"
  connection_draining_timeout = "${var.connection_draining_timeout}"
  listener                    = ["${var.listener}"]
  access_logs                 = ["${var.access_logs}"]
  health_check                = ["${var.health_check}"]
  tags                        = "${local.tags}"
}

# Cloudwatch alarms
data "aws_elb" "classic_lb" {
  count = "${module.elb.this_elb_name != "" ? 1 : 0}"
  name  = "${module.elb.this_elb_name}"
}

resource "aws_cloudwatch_metric_alarm" "low_healthy_host_count_alarm" {
    count                = "${var.create_alarm ? 1 : 0}"
    # alarm_name         = "${module.elb.this_elb_name}-HealthyHostCount"
    alarm_name           = "${data.aws_elb.classic_lb.name}-HealthyHostCount"
    dimensions {
      # LoadBalancerName = "${module.elb.this_elb_name}"
      LoadBalancerName   = "${data.aws_elb.classic_lb.name}"
    }
    ...
}

However, I tried to use data source as well as direct module access like ${module.elb.this_elb_name} for getting the ELB name as it exists on AWS (and not on my local as sometimes AWS can truncate long names). But both times when targeting just the alarm like terraform plan -target=aws_cloudwatch_metric_alarm.low_healthy_host_count_alarm, I get other resources targeted too, which I don't want.
Terraform will perform the following actions:

  + aws_cloudwatch_metric_alarm.low_healthy_host_count_alarm
      id:                                    <computed>
      actions_enabled:                       "true"
      ...

  ~ module.elb_sg.aws_security_group.this
      ...

  ~ module.elb.module.elb.aws_elb.this
      access_logs.#:                         "0" => "1"
      access_logs.0.bucket:                  "" => "test-logs"
      access_logs.0.enabled:                 "" => "true"
      access_logs.0.interval:                "" => "60"
      ...

Plan: 1 to add, 2 to change, 0 to destroy.

The problem goes away when I use a hardcoded name or a local.name for the elb in dimension and alarm_name in my cloudwatch alarm.
Can someone explain exactly what causes this behavior? Thanks.

A: The -target option is a request for Terraform to plan operations only for the selected resource instance(s) and everything they depend on. If there are changes pending for something your target resource depends on then there is no way to skip updating them, because that would cause an inconsistent result.
Using a constant value or a local value that doesn't depend on anything else itself will allow limiting the scope of the operation further because in that case the resource doesn't depend on anything that has externally-visible side-effects, and thus the changes that are included for dependency reasons will not be visible explicitly in the plan.
-target should be used only for specific exceptional situations where a Terraform error message suggests that you do so or when you are repairing an earlier error. It's not intended as a mechanism to avoid applying changes you've already made to your configuration.

A: As per this official doc, when we specify a module path, the "target" applies to all resources in the specified module and all of the descendent modules of the specified module.
This is why when use a hardcoded value for the elb, we dont get dependencies be targeted.
But we are using the module path, docs for which also mention, " If a module path is specified without a resource spec, the address applies to every resource within the module. "


text:
Q: Azerothcore Autobalance damage calculation I have a problem with the damage calculation for rogue. In dungeons the rogue gets too little damage and deals too much. Autobalance is used on the server. I know the problem is related to autobalance module. But I don't know why. All other classes works fine. Maybe someone has had similar problems before?
More Detials:
Hi, Ok I will try to add more details. I'm sorry for my bad english. As example, If I go to Ragefire Chasm as a lvl 25 rogue the creature are also lvl 25 with autobalance. But they makes only 1 dmg to me and not the normal dmg for that level. But I'm make to much damage. Maybe the creature scalled not normal or an other bug is exist. With other classes, hunter, pala, witcher etc. I get the normal damage. If I disable autobalance, the damage ist normal for rogue. So I think it is an issue with autobalance module. What do you need for other information? If I know what for information you need, so I will provide them.


text:
Q: jquery/2.2.0 - TypeError: $.initElementData is not a function I'm running an A/B test and have written some jQuery which works in the preview panel - but when i push it live - I don't see the changes and I'm seeing an error:

TypeError: $.initElementData is not a function
...his,c);return}}c.unshift("Generic
  Events");this.genericHandler.apply(this,c)}})
jquery.... > eval (line 1, col 9180) TypeError: $.ui is undefined
$.extend($.ui.autocomplete.prototype, {

I've tried googling this - and it appears to speak to old version of jQuery - but I'm using the latest?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

Please see my code below:

</head>
<script>
jQuery.fn.extend({
    live: function (event, callback) {
       if (this.selector) {
            jQuery(document).on(event, this.selector, callback);
        }
    }
});
  //Online Only
  //Available Online    Not Available in Stores
 $('div.result-sold').each(function() {

 if($(this).find('li:contains("Available Online")').length>0 &&
    $(this).find('li:contains("Available Online")').next('li:contains("Not Available In Stores")').length>0){

        $(this).find('li:contains(Not Available In Stores)').remove();
      $(this).find('li:contains("Available Online")').text('Online Only');

       }
  });

  //In Stores Only
  //Not Available Online    Available in Stores

   $('div.result-sold').each(function() {

 if($(this).find('li:contains("Not Available Online")').length>0 &&
    $(this).find('li:contains("Not Available Online")').next('li:contains("Available In Stores")').length>0){

        $(this).find('li:contains(Not Available Online)').remove();
      $(this).find('li:contains("Available In Stores")').text('In Stores Only');

       }
  });

 /* Temp sold out online :: Not available in stores */
  $('div.result-sold').each(function() {

  if($(this).find('li:contains("Temporarily Sold Out Online")').length>0 ||
    $(this).find('li:contains("Temporarily Sold Out Online")').next().text()==="Available In Stores") {

      $(this).find('li:contains("Available In Stores")').remove();
      $(this).find('li:contains("Not Available In Stores")').remove();

     }
});

   /* sold out online :: available in stores */
  $('div.result-sold').each(function() {

  if($(this).find('li:contains("Sold Out Online")').length>0 ||
    $(this).find('li:contains("Sold Out Online")').next().text()==="Available In Stores"){

      $(this).find('li:contains("Available In Stores")').remove();

     }
});

</script>

A: Where is this script tag located in your page? I'm assuming it's in the head right? if it is, then it will load jQuery in it's entirety before executing your code.  It seems as if jQuery is not fully loaded before this code is executed. If you move your script to just before the body tag, do you get the same result?


text:
Q: Major issues with multiple external displays after upgrading from macOS 10.12.3 to 10.12.4 Upon updating from macOS 10.12.3 to 10.12.4 the following issues immediately began occurring consistently anytime the MacBook tries to initiate displaying on external monitors that are in power-save mode (i.e. on, but waiting for a signal and thus with the screen off). This includes when the MacBook boots up or wakes.

*

*MacBook outputs intermittent signal to external monitors via Thunderbolt interface leading to race condition like situation where the external monitor wakes from power-save mode upon receiving a signal from the MacBook, but goes back into power-save mode due to not detecting a signal (or at least a consistent one) by the time it has finished waking. This process repeats cyclicly for some time until both external monitors happen to get in sync with the MacBook (or they don't, see below).

*The MacBook enters an unresponsive state after being in the above cycle for some time without the external monitors getting in sync with the MacBook. This requires a forced shut down which can lead to loss of data and unsaved work.

Please see my answer below for further details.

A: The following paragraph is meant as a high level summary of the issue that is occurring, and I attempt to explain the relevant parts in more detail in the subsequent paragraphs.
Immediately after upgrading from macOS 10.12.3 to 10.12.4 I noticed that when my MacBook Pro (Late 2013) boots up or wakes while plugged into my two external displays via Mini DisplayPort, my MacBook has extreme difficulty getting them both working at the same time. The MacBook's screen will turn on and off as it tries to get in sync with the external displays (to start displaying on them as normal). Meanwhile, the displays seem to cycle between receiving a signal and receiving no signal as suggested by the fact that the displays will wake, but then display "No Signal" and go back into power-save mode. Eventually, after many cycles of this, one or both displays may "get in sync" with the MacBook and function normally from there on out. But sometimes it goes through many such cycles without getting in sync. When the displays and the MacBook fail to get in sync after many cycles and continue to cycle as described, I may unplug one or both external monitors and try to get them to sync up individually, which is usually easier than trying both at once. This makes sense because, as I explain below, this problem is effectively a race condition and appears to be compounded with every additional external display in use. Finally, the more serious case is when the cycle I've described ends in the MacBook entering an unresponsive state and requiring a forced shutdown which can lead to loss of data or unsaved work. Furthermore, this whole issue presents itself every time I boot up or wake the MacBook.
To be clear, the displays wake from power-save mode upon receiving a signal from my MacBook (e.g. when it boots or wakes from sleep). But after receiving that initial signal waking the display from power-save mode, the display shows "No Signal" and goes back into power-save mode. Meanwhile, the display on my MacBook goes from normal to a blank screen for a couple seconds and back to normal as it seemingly switches between outputting to the external display and not outputting. This is the cycle that continuously repeats until either each respective monitor gets in sync with the MacBook and works as normal, or the MacBook enters an unresponsive state as described below. In the case where the monitors do eventually get in sync, it appears to occur the moment the monitor waking happens to coincide with the MacBook outputting a consistent signal to that respective monitor. So, it's effectively a race condition. The reason I say the MacBook cycles between outputting to the monitor and not outputting to it is because, while it's in this cycle, I'll observe windows I had open on the external monitor prior to the MacBook sleeping toggle between being displayed on the MacBook's display and not being displayed at all (presumably they're being output to the external display).
As I mentioned above, there is an even more troublesome situation I've now encountered multiple times where, upon waking from sleep, the MacBook will enter the cycle of trying to get in sync with the monitors for a while and then enter an unresponsive state, showing a blank screen. Plugging in and unplugging the monitors from the MacBook or power cycling the monitors seems to have no effect in this situation. Even if the MacBook is recognizing one of the monitors while in this unresponsive state, that monitor is also just rendering a blank screen (but is not going into sleep mode therefore is receiving a signal). My only option has been to force shut down my MacBook after this has happened by pressing the power button and leaving it pressed.
I have two Acer S241HL displays each connected via Mini DisplayPort. I had never had this issue before and it started immediately after I upgraded from 10.12.3 to 10.12.4. In the past, my MacBook's screen might turn on/off once or twice when booting up (and maybe waking?) before all displays were on and rendering properly. But that was always quick and never an issue. This is a much greater extreme and a major inconvenience as I have to wait and sometimes mess with the monitors every time my MacBook wakes or boots up. Even more serious is that it is now dangerous for me to wake my MacBook if I have monitors plugged in due to the risk of it entering an unresponsive state, thus requiring a forced shut down. This can easily cause problems including loss of data and unsaved work.
I've contacted Apple Support to escalate this issue to engineering. They should be aware of this thread, so if you experience this same issue, please comment with details of your setup such as which video out port(s) you're using and what kinds of cables/adapters, as well as any other pertinent information.

A: Let Apple Know
If you have a reproducible test case (preferably after isolating for extraneous variables like sleep / wake / third party extensions and on a cleanly installed OS), the best way to alert engineering at Apple is via their Bug Reporter. You can use an Apple ID to log in and provide a detailed bug report.
If you lack access there, Apple Support can escalate issues to engineering. The least direct manner is the general Feedback page.

A: It may be actually worth resetting the NVRAM and SMC (in that order) to see if this resolves your issues. Before doing so, unplug all external devices (including monitors, keyboard, etc).
Resetting NVRAM on your model MacBook Pro
Your Mac use Non-Volatile Random-Access Memory (NVRAM) to store a whole range of settings. Here's how to reset this:

*

*Shut down your Mac. Yes, a full shut down, not just logging out.

*Press the power button and then press the commandoptionpr keys. You have to make sure you press these keys before the gray screen appears or it won't work.

*Hold those keys down until your Mac reboots again and you here the startup chime.

*Let go of the keys and let your Mac reboot normally.

Note: When you log back in you may need to readjust some of your system preferences (e.g. speaker volume, screen resolution, startup disk selection, time zone information, etc).
Now proceed to reset the SMC.
Resetting the SMC on your model MacBook Pro
The System Management Controller (SMC) impacts a whole range of power management functions. Here's how to reset this:

*

*Shut down your Mac

*Keep the MagSafe adapter (power cable) plugged in.

*Press at the same time shiftoptioncontrol (on the left side of the built-in keyboard) and the power button

*Let go

*Turn your computer back on with the power button.

Let us know how you go.

A: We've had lots of issues with third party sync and displays since 10.11 so it might not at all be related to the update (or that the update enables new features that are exposing faulty cables more readily).
Our help desk now has several sets of known good cables and known good displays we take and systematically test along side our normal "known good clean OS install" drive on external bootable media.
Our triage process is:

*

*Reseat all cables, boot to safe mode and verify that the display itself works.

*Collect data on the timing of the issue - does it happen every single time, or on occasion?

*Perform a test - 5 sleeps and 5 wakes or three reboots and record the results.

At this point, we'll know if it's really something related to the OS or if it's an occasional problem.
If you don't have an IT help desk - you might need to do some of these in another order. If you're convinced it's the update, install a clean OS (same version) on external drive and test that for a few hours. That sort of detail usually gets Apple Engineering involved if you can reproduce the issue with a clean install.
Don't overlook cables as well - we're replacing a whole lot more cables than we did in past years. It's too soon to tell if we just bought lesser quality cables or if the new hardware and drivers are just more picky. The good news is cables are relatively cheap and you can mark the suspect ones for reuse later if it turns out to be software and not the cables.

A: I am seeing something like this with an Acer monitor (H233H) on a direct HDMI connection from a late 2013 MacBook Pro on 10.14.6.
I'm not getting the crashes, but I do see a race condition here, to me it looks like:

*

*The monitor starts up, and pokes the HDMI connection

*The MacBook sees this and starts up dual screen mode

*...

*The MacBook still hasn't returned anything on the HDMI interface, so the monitor gives up and shows "no signal"

*The MacBook finishes switching modes, and starts sending a signal

*But the monitor isn't listening any more

*Power cycling the monitor will break the HDMI connection and return the MacBook to single-screen mode (ie. goto step 1)

I've found that sometimes the monitor can restart fast enough to avoid triggering this last step, but apart from that I haven't figured out any way around this.


text:
Q: jQuery Change click behavior in Edit Mode I have a simple media gallery with images that click through to other pages. I also have an "Edit" mode that allows the user to change the media gallery name, description and delete photos etc. While in "Edit" mode, I'd like to disable the default click action on the photos, and make it so that you can "select" multiple images when clicking on them. Then, buy clicking "Cancel"  or "OK", the regular default image click HREFs are restored. I have the following code that kind of works in parts, but I am getting strange behavior. Any ideas on what I am doing wrong here or a better way to achieve this?
$(".editAlbumButton").click(function() {
    $("#editTools").show();
    $(".mediaClick").preventDefault();
    $(".mediaClick").toggle(function() {
        $(this).addClass('mediaSelectHighlight');
        }, function() {
        $(this).removeClass('mediaSelectHighlight');
    });
});

$(".cancelButton").click(function() {
    $(".mediaClick").removeClass('mediaSelectHighlight');
    $("#editTools").hide();
    $(".mediaClick"). ??? (); // I don't know how to "Restore" default click action here ?
});

A: Try binding and unbinding the events, depending on which mode is active.
$(".editAlbumButton").click(function() {
    $(".mediaclick").unbind("click", /*hanlder*/);
}
...
$(".cancelButton").click(function() {
   $(".mediaclick").bind("click", /*handler*/);
}

A: Why do not you use a flag for example editable.
var editable=false;
$(".editAlbumButton").click(function() {
    $("#editTools").show();
    editable=true;
    $(".mediaClick").toggle(function() {
        $(this).addClass('mediaSelectHighlight');
        }, function() {
        $(this).removeClass('mediaSelectHighlight');
    });
});
$(".cancelButton").click(function() {
    $(".mediaClick").removeClass('mediaSelectHighlight');
    $("#editTools").hide();
    editable=false;
});
$(".mediaClick").click(function() {
    if(editable){
        $(this).preventDefault();
        return;
    }
});


text:
Q: Google Maps in Xamarin for Android fails to center on location         var _locator = CrossGeolocator.Current;
        var mapPosition = await _locator.GetPositionAsync();

        var mapSpan = MapSpan.FromCenterAndRadius(
            new Xamarin.Forms.Maps.Position(mapPosition.Latitude, mapPosition.Longitude),
            Distance.FromMiles(2)
            );

        Map.MoveToRegion(mapSpan);

Using Xamarin.Forms.Maps.Postion() the correct lat and lon coordinates are calculated.

However, when I add it to MapSpan, the coordinates change to somewhere in the middle of the Atlantic ocean.  Not sure what is causing this?

UPDATE:
So the problem is definitely in the Android project.  For some reason, GoogleMaps is not recognizing the location passed by the Map Renderer in the shared project.  OnMapReady is just using the default lat/lon.

SUCCESS!!!
        async Task<Plugin.Geolocator.Abstractions.Position> GetPositionAsync()
    {
        var _locator = CrossGeolocator.Current;
        Plugin.Geolocator.Abstractions.Position myPosition = await _locator.GetPositionAsync();
        return myPosition;
    }

    public void OnMapReady(GoogleMap googleMap)
    {
        Plugin.Geolocator.Abstractions.Position myPosition = Task.Run(GetPositionAsync).Result;

        map = googleMap;
        map.MoveCamera(
            CameraUpdateFactory.NewLatLng(
                new LatLng(myPosition.Latitude, myPosition.Longitude)));
        map.AnimateCamera(
            CameraUpdateFactory.ZoomTo(10));

A: The MapSpan properties LatitudeDegree and LongitudeDegrees refer to the degrees of latitude and longitude that are spanned (i.e. the number of degrees of the map that are shown within its view.)
If you are looking for the lat/lng of the center of the map in your span, refer to the Center properties which is a Maps.Postion object.
Re: https://developer.xamarin.com/api/type/Xamarin.Forms.Maps.MapSpan/
Example:
var mapPosition = new Position(38.29, -77.45);
var mapSpan = MapSpan.FromCenterAndRadius(mapPosition, Distance.FromMiles(2));
map.MoveToRegion(mapSpan);


text:
Q: Is there a built-in perl function that determines length of numeric variable? I am parsing a text file with the following format that needs to be distinguished.
cat       dog      [numeric, 00-23]
pickle    fence    [numeric, 0-5]
tack      glue     [numeric,1-53]
dent      paint    [numeric01-15]

If the minimum of the range is a single digit, then I need to process it a certain way. If the minimum of the range is double-digit (including 00,01,02,etc), I need to process it another way.
if($line =~ /\[numeric.*(\d+)\-(\d+)/i){
       $rangemin=$1;
       $rangemax=$2;
       #find # of digits in $rangemin
       #length() doesn't work
       #I'm trying to find a function that finds number of digits so length of `00` or `01` or `02` or etc. returns `2`
}

How do I find the # of digits of $rangemin?

A: Your regular expression grabs the leading 0 because .* is very greedy.
use warnings;
use strict;

while (my $line = <DATA>) {
    if ($line =~ /\[numeric[\D]*(\d+)\-(\d+)/i){
        my $rangemin = $1;
        my $len = length $rangemin;
        print "rangemin=$rangemin len=$len\n";
    }
}

__DATA__
cat       dog      [numeric, 00-23]
pickle    fence    [numeric, 0-5]
tack      glue     [numeric,1-53]
dent      paint    [numeric01-15]

Output:
rangemin=00 len=2
rangemin=0 len=1
rangemin=1 len=1
rangemin=01 len=2

A: You can use the length built-in, just like you would for a string; Perl implicitly converts arguments based on the operator/builtin that they are being passed to:
#!perl

use strict;
use warnings;

my $number = 5;
print length($number), "\n";

You can also use a base-10 logarithm to determine how long a number is:
#!perl

use strict;
use warnings;

my $number = 12345;
my $length = $number > 0
    ? int(log($number)/log(10)) + 1
    : $number == 0
          ? 0
          : int(log(abs($number))/log(10)) + 2;
print $length, "\n";
# 5

**EDIT: as @Keith Thompson points out, log is not defined for numbers <= 0. Use abs to prevent this condition.


text:
Q: How do I retrieve json data from a javascript variable I am trying to understand and use json.  Most examples leave out just enough to leave me hanging, or go into jQuery or ajax which I want to do eventually, but right now, just want to understand the basics of json.  This PHP code seems to be working, but the javascript is not....
<!DOCTYPE html>
<html>
<head>
<title>Connecting MySQL Server</title>
<meta charset="utf-8">
<meta name="author" content="Charlie R Chisholm">
<?php

    $mysqli = new mysqli(dbhost,dbuser,dbpass,dbc);
    if ($mysqli->connect_error) {
        die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
        }

    $query = $mysqli->query("select * from codeTable where tableCode='TABLE' order by Description");
    $json = array();
    if($query->num_rows){
        while($tblArray[] = $query->fetch_object()){
        $json['codeTable'][]=$tblArray;
        }
    }
    mysql_close($mysqli);
    echo json_encode($json);
?>
<script language="JavaScript">
    var tbl = <? echo json_encode($json) ?>;

            // How would I get the Description data in the second row (for example)
            // the line below is certainly not right

    alert(tbl["codeTable"][1].Description);

</script>

</head>

<body>
</body>
</html>

and I get this result...
{"codeTable":[[{"codeID":"4","tableCode":"TABLE","Description":"Document Type","Code":"DOCTP","groupCode":"","t1":null,"t2":null,"t3":null,"createDate":"2014-03-28 18:52:06","chaDate":null}],[{"codeID":"4","tableCode":"TABLE","Description":"Document Type","Code":"DOCTP","groupCode":"","t1":null,"t2":null,"t3":null,"createDate":"2014-03-28 18:52:06","chaDate":null},{"codeID":"8","tableCode":"TABLE","Description":"Images","Code":"IMAGE","groupCode":"","t1":"Upload Doc Name","t2":null,"t3":null,"createDate":"2014-03-28 18:57:15","chaDate":null}],[{"codeID":"4","tableCode":"TABLE","Description":"Document Type","Code":"DOCTP","groupCode":"","t1":null,"t2":null,"t3":null,"createDate":"2014-03-28 18:52:06","chaDate":null},{"codeID":"8","tableCode":"TABLE","Description":"Images","Code":"IMAGE","groupCode":"","t1":"Upload Doc Name","t2":null,"t3":null,"createDate":"2014-03-28 18:57:15","chaDate":null},{"codeID":"1","tableCode":"TABLE","Description":"Note Type","Code":"NTYPE","groupCode":"GENRL","t1":"","t2":"","t3":"","createDate":"2014-03-11 18:26:27","chaDate":"0000-00-00 00:00:00"}],[{"codeID":"4","tableCode":"TABLE","Description":"Document Type","Code":"DOCTP","groupCode":"","t1":null,"t2":null,"t3":null,"createDate":"2014-03-28 18:52:06","chaDate":null},{"codeID":"8","tableCode":"TABLE","Description":"Images","Code":"IMAGE","groupCode":"","t1":"Upload Doc Name","t2":null,"t3":null,"createDate":"2014-03-28 18:57:15","chaDate":null},{"codeID":"1","tableCode":"TABLE","Description":"Note Type","Code":"NTYPE","groupCode":"GENRL","t1":"","t2":"","t3":"","createDate":"2014-03-11 18:26:27","chaDate":"0000-00-00 00:00:00"},{"codeID":"5","tableCode":"TABLE","Description":"Projects","Code":"PRJCT","groupCode":"","t1":null,"t2":null,"t3":null,"createDate":"2014-03-28 18:53:14","chaDate":null}]]}

...but from here, I know not where I go.  I tried to retrieve information from the tbl variable with several different notation styles, but I seem to get "undefined" or "[object]" or "[object][object]" rather than the data.  Can someone help me understand the syntax I need to be able to retrieve values from the json?  (the alert box is just an example of not knowing what I am doing)

A: tbl["codeTable"][1] is an array, not an object. It doesn't have a Description property.
You need to pick one of the items in the array.
tbl["codeTable"][1][0]
This is an object which does have a Description property.
tbl["codeTable"][1][0].Description

Alternatively, just don't create the array with one item in it in the first place.
while($tblArray[] = $query->fetch_object()){
    $json['codeTable'][]=$tblArray;
}

Should be:
while($myObject = $query->fetch_object()){
    $json['codeTable'][] = $myObject;
}

A: var tbl = <? echo json_encode($json) ?>;
var content = $.parseJSON(tbl);
$.each(content, function(key, value) {
   alert(key + ": " + value);
});


text:
Q: How long does a ban or suspension on an SE site last? I've tried to make some searches about ban and suspension but the data I found doesn't seem to correspond to my experience. I also cannot find a FAQ on the help section.
Can you explain me how these mechanics work?
I've just found the feature request for a review ban duration to be extended automatically at every new suspension in an exponential way. But it's speaking of 2, 7, 30 days.
I've heard from a moderator that the suspension duration is 7, 30, 365 days. Is that correct? Can a moderator change the duration of a suspension?

A: A timed suspension is a timed restriction of activities on a site. The date when it concludes is shown on the user profile page of the suspended user. Moderators can choose the length of suspensions at their discretion, but usually the first suspension will last 7 days, the second 30 days, and the third 365 days.
More information:

*

*A Day in the Penalty Box

*My account has been temporarily suspended; what does that mean?
A post ban (question ban or answer ban) is algorithmically determined, and lasts as long as there is poor content associated with the account. The only way to get yourself out of a post ban is to improve your existing content. It's also been suggested that posting good, well-received answers will help get you out of a question ban, and vice versa. The details of the algorithm are known only to the Stack Exchange team.
More information:

*

*Help Center: Question bans

*Help Center: Answer bans

*What can I do when getting "We are no longer accepting questions/answers from this account"?
A review ban is a timed suspension from one or more review queues. It can be triggered by failing too many review audits. The time of the ban is determined by an algorithm. A ban can also be set manually by a moderator if your review history is problematic. You'll be alerted to when the ban will be lifted when you attempt to use the review queue(s) where you have a review ban.

*

*The time of automatic review bans should be increased with every new ban


text:
Q: Execute commands to running process I'm currently trying to use processes in java to run a jar file. I'm able to run and read the content printed by the process. What I'm trying to achieve, is to write a command to the process. The jar file I'm running asks for user input and I am trying to allow the user to enter that input. This is my current code which isn't working:
public class Main {

public static void main(String[] args) {

    String command = "java -jar game.jar";

    Process process = executeCommand(command);

    CompletableFuture.runAsync(() -> {

        Scanner scanner = new Scanner(System.in);

        while (true) {

            String input = scanner.nextLine();

            if (input == null) {
                continue;
            }

            executeCommand(process, input);

        }

    });

    readOutput(process);

}

public static Process executeCommand(String command) {

    try {
        Process process = Runtime.getRuntime().exec(command);

        return process;
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }

}

public static List<String> readOutput(Process process) {

    List<String> output = new ArrayList<>();

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        while((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
            output.add(line);
        }

        process.waitFor();

        return output;

    } catch (IOException ex) {
        ex.printStackTrace();
        return output;
    } catch (InterruptedException ex) {
        ex.printStackTrace();
        return output;
    }

}

public static void executeCommand(Process process, String command) {

    try {

        OutputStream out = process.getOutputStream();

        out.write(command.getBytes());

    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

}

A: I was able to fix the problem by adding out.flush()
public static void executeCommand(Process process, String command) {

    try {

        OutputStream out = process.getOutputStream();

        out.write(command.getBytes());
        out.flush();

    } catch (IOException ex) {
        ex.printStackTrace();
    }

}


text:
Q: Java Android reading full file quickly I have the following code snippet to read the full contents of a text file into a string.  It works, only problem is... it's really slow (the file is about 1500 lines long).
            InputStream is = this.getResources().openRawResource(R.raw.comp_rules_glossary);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String previousLine = "start";

            while ((readLine = br.readLine()) != null)
            {
                rules = rules + readLine + eol;
                if (previousLine.equals(""))
                {
                    content = content + readLine + eol;
                }
                previousLine = readLine;
            }

            is.close();
            br.close();

At the moment, I'm reading the full file in one line at a time, then appending it to the string.  Is there a faster way to do this?  I'm looking for a quick way to get the entire file into a string.

A: Use StringBuilder to build large Strings.
StringBuilder sb_rules = new StringBuilder();
StringBuilder sb_content = new StringBuilder();
while ((readLine = br.readLine()) != null)
{
    sb_rules.append(readLine);
    sb_rules.append(eol);
    if (previousLine.equals(""))
    {
        sb_content.append(readLine);
        sb_content.append(eol);
    }
    previousLine = readLine;
}
content = sb_rules.toString();
content = sb_content.toString();

Why StringBuilder when there is String?

String does not allow appending. Each method you invoke on a String creates a new object and returns it. This is because String is immutable - it cannot change its internal state.

A: I see that you already seem to have a working solution based on Kevin's comment, but it might be helpful to understand why your old code was slow.
The problem is that when you concatenate strings directly with the + operator or with the concat() method, it is actually creating a new string with the result of the concatenation. This involves copying the entire contents of both strings that you are concatenating. So as you read in the file and build up the contents string, every time you add to it, you are creating yet another copy of everything that you have so far in contents.
The solution, which I assume is what you're doing now, is to use a StringBuffer class, which is a dynamic buffer that allows you to modify its contents (i.e. append new data to the end), without always having to allocate a new String object and copy everything to it.
The main thing that you have to keep in mind is that Strings in java are immutable. Any time you call a method on a java String that changes it in some way, it is actually creating a new copy of the string with the result of the modification.

A: Assuming Apache Commons works fine on Android, could you use something like this?
InputStream is = this.getResources().openRawResource(R.raw.comp_rules_glossary);
String text = IOUtils.toString(is, "UTF-8");

(or you could use Guava and its CharStreams helper, but it's usually more verbose)
Unless there's a reason you want to avoid 3rd party libs?


text:
Q: DataFrame.quantile() function didn't work when use apply function I made a function to get the middle part of a DataFrame, but the quantile function didn't work well. So I can't get the part of dataframe I want.
I'm using pandas 0.23.4
Here is the func body.
def func(df,key_name,tail):
    df_new = df[df[key_name]>df[key_name].quantile(tail)]
    return df_new

but it works good when I try it in this way
func(clean_video,'all_vv',0.1)

when I apply it like
clean_video.apply(func,axis = 1,args = ('all_vv',0.1))

I got the Error below.
AttributeError: ("'int' object has no attribute 'quantile'", 'occurred at index 0')

Thanks for all help.


text:
Q: Ace editor monospace fonts issues with cursor spacing I've seen a few issues with the cursor being improperly spaced in the ace editor. The problem has to do with the font-spacing and apparently the solution is to only use monospaced fonts.
Here's another SO question about the issue.
ace editor cursor behaves incorrectly
My problem may have something to do with using a Bootstrap theme, but I'm not entirely sure.
When I open chrome dev tools and look at the font used in the ace editor, it says that my Bootstrap template is using the fonts
input, textarea, input[type="submit"]:focus, div {
  outline: 0 none;
  font-family: 'Open Sans', sans-serif;
}

If I add to my css
.ace-editor {
  font-family: monospace !important;
}

I still have a problem with the cursor spacing being wrong, and strangely, the font which is being used looks exactly the same as the 'Open Sans' defined in Bootstrap.
Opening in Chrome dev tools, says that the computed property is 'monospace', so something is supposed to be working, but it isn't. Here is where it get really weird.
If I remove the font entries for both .ace-editor and input, textarea..., I get a perfectly good looking font that works.
Going to the computed properties, is shows the font-family to once again be 'Open Sans'.
So the question I'm trying to answer, is how can I either figure out what font is ACTUALLY being used when I cancel out the textarea entry from Bootstrap? Or why is this not accepting the monospace font when it is specified.
I'm somewhat assuming that 'Open Sans' may be monospaced, but whatever, it's still causing massive headaches.

A: The issue is caused by div included in bootstrap rule.
It is too broad and breaks character width measurements for ace.
You can add
.ace_editor div {
    font: inherit!important
}

as a workaround. Would be good to also report an issue to the creator of your bootstrap template.


text:
Q: Requiring json file with raw-loader causes a syntax error When I do require("!!raw-loader!themes/builtin_themes/default/layout.json"), I get the following error:
Module parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = "{\...'
File was processed with these loaders:
* ../node_modules/raw-loader/index.js
You may need an additional loader to handle the result of these loaders.
SyntaxError: Unexpected token m in JSON at position 0 while parsing near 'module.exports = "{\...'
     at JSON.parse (<anonymous>)
     at parseJson (/Users/frederikcreemers/dev/project/node_modules/json-parse-better-errors/index.js:7:17)
     at JsonParser.parse (/Users/frederikcreemers/dev/project/node_modules/webpack/lib/JsonParser.js:16:16)
     at /Users/frederikcreemers/dev/project/node_modules/webpack/lib/NormalModule.js:482:32
     at /Users/frederikcreemers/dev/project/node_modules/webpack/lib/NormalModule.js:358:12
[w-renderer]     at /Users/frederikcreemers/dev/project/node_modules/loader-runner/lib/LoaderRunner.js:373:3
     at iterateNormalLoaders (/Users/frederikcreemers/dev/project/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
     at iterateNormalLoaders (/Users/frederikcreemers/dev/project/node_modules/loader-runner/lib/LoaderRunner.js:221:10)
     at /Users/frederikcreemers/dev/project/node_modules/loader-runner/lib/LoaderRunner.js:236:3
     at runSyncOrAsync (/Users/frederikcreemers/dev/project/node_modules/loader-runner/lib/LoaderRunner.js:130:11)
     at iterateNormalLoaders (/Users/frederikcreemers/dev/project/node_modules/loader-runner/lib/LoaderRunner.js:232:2)
     at Array.<anonymous> (/Users/frederikcreemers/dev/project/node_modules/loader-runner/lib/LoaderRunner.js:205:4)
     at Storage.finished (/Users/frederikcreemers/dev/project/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:43:16)
     at /Users/frederikcreemers/dev/project/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:79:9
     at /Users/frederikcreemers/dev/project/node_modules/graceful-fs/graceful-fs.js:90:16
     at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:61:3)

We do have the json loader configured like this:
{
test: /\.json$/,
  use: [{
    loader: "json-loader",
    options: { context: "." }
  }]
}

but my understanding was that the "!!" in front would disable any configured loaders.
If possible, I'd like to leave the webpack configuration alone and just change the require statement to make this work.

A: Change the format of imported file like this
raw-loader!./my-json-file.txt

Use txt or any other postfix - that worked for me


text:
Q: Vowpal Wabbit not predicting binary values, maybe overtraining? I am trying to use Vowpal Wabbit to do a binary classification, i.e. given feature values vw will classify it either 1 or 0. This is how I have the training data formatted.
1 'name | feature1:0 feature2:1 feature3:48 feature4:4881 ...
-1 'name2 | feature1:1 feature2:0 feature3:5 feature4:2565 ...
etc

I have about 30,000 1 data points, and about 3,000 0 data points. I have 100 1 and 100 0 data points that I'm using to test on, after I create the model. These test data points are classified by default as 1. Here is how I format the prediction set:
1 'name | feature1:0 feature2:1 feature3:48 feature4:4881 ...

From my understanding of the VW documentation, I need to use either the logistic or hinge loss_function for binary classifications. This is how I've been creating the model:
vw -d ../training_set.txt --loss_function logistic/hinge -f model

And this is how I try the predictions:
vw -d ../test_set.txt --loss_function logistic/hinge -i model -t -p /dev/stdout

However, this is where I'm running into problems. If I use the hinge loss function, all the predictions are -1. When I use the logistic loss function, I get arbitrary values between 5 and 11. There is a general trend for data points that should be 0 to be lower values, 5-7, and for data points that should be 1 to be from 6-11. What am I doing wrong? I've looked around the documentation and checked a bunch of articles about VW to see if I can identify what my problem is, but I can't figure it out. Ideally I would get a 0,1 value, or a value between 0 and 1 which corresponds to how strong VW thinks the result is. Any help would be appreciated!

A: *

*If the output should be just -1 and +1 labels, use the --binary option (when testing).

*If the output should be a real number between 0 and 1, use --loss_function=logistic --link=logistic. The loss_function=logistic is needed when training, so the number can be interpreted as probability.

*If the output should be a real number between -1 and 1, use --link=glf1.

If your training data is unbalanced, e.g. 10 times more positive examples than negative, but your test data is balanced (and you want to get the best loss on this test data), set the importance weight of the positive examples to 0.1 (because there are 10 times more positive examples).

A: Independently of your tool and/or specific algorithm you can use "learning curves" ,and train/cross validation/test splitting to diagnose your algorithm and determine whats your problem .  After diagnosing your problem you can apply adjustments to your algorithm, for example if you find you have over-fitting you can apply some actions like:

*

*Add regularization

*Get more training data

*Reduce the complexity of your model

*Eliminate redundant features.

You can reference Andrew Ng. "Advice for machine learning" videos on YouTube to more details on this subject.


text:
Q: Where can I buy the four hard drive screws for my MacBook Pro 2011 15" (pic) I'm trying to find four replacement mounting screws for the 2.5" hard drive in my MacBook Pro 2011 15".
Here's a pic of the four screws  (one attached to hard drive).
I tried Googling and can't find anything. Are these screws available online?

A: MacRecycling offers these screws as well. They seem to be quite pricey though!

A: You can find them, and most any other Apple repair parts, at ifixit

A: I'm not sure why the tutorials are suggesting T5's. Historically the proper Torx is a T8.
Regardless, they're meant only as pegs to stabilize the drive inside the body. You don't need these explicitly. So long as you have something with compatible threading and reach, it will function the same.

A: I used to use a service called "The PowerBook Guy" which has morphed into Keane Mac Repair: http://www.keanesf.com/. Another resource for parts and fixing stuff.

A: In a pinch, I discovered that the lowly Q-Tip offers the perfect solution.  The shaft is the exact same diameter.  Just nip off the cotton, then insert the shaft fully into each hole, and cut with wire cutters allowing about 1/8" to stick out.  Works just great!


text:
Q: How can I remove Previous View Controller from navigation controller ios? I want to remove Previous view controller from navigation stack.
For example
-> A is root view.now navigate to B - b navigate to c - c navigate to c - c navigate to c
-->  now i want to remove all c view controller & pop to B
B is not Fix view controller.
Another example
A - > b -> c > g  > c > f > c > c  > c > c
Remove all c View controller from navigation & need following output
A - > b -> c > g  > c > f
Please help me

A: Identify the controller from navigation stack. And pop to that controller
  NSArray *viewControllers = [[self navigationController] viewControllers];
  int count = [viewControllers count];

  for (int i= count-2; i >= 0 ; i--) {

        id obj=[viewControllers objectAtIndex:i];

        if(![obj isKindOfClass:[C class]]){
           [[self navigationController] popToViewController:obj animated:YES];
            return;
        }
   }

A: You can use popToViewController (https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621871-poptoviewcontroller).
example:
In Objective C
[self.navigationController popToViewController:self.navigationController.viewControllers[your_VC_index] animated: true];
// in first eg your_VC_index will be 1 and another example it will be 5

In Swift 3
self.navigationController.popToViewController( self.navigationController.viewControllers[your_VC_index], animated: true)

A: reverse iterate over navigation stack and get the index of first non matching viewController and then popToViewController
if let controllers = self.navigationController?.viewControllers {
   var count = controllers.count - 1
   for viewcontroller in controllers.reversed() {
       if viewcontroller is CViewController {
          count -= 1
       } else {
          break
       }
    }

    let vc = controllers[count]
    self.navigationController?.popToViewController(vc, animated: true)
 }

A: Write a method something like the following,
- (void)removeAllLastCObjectsFromNavigationController {
    //fetch viewcontroller array. for your case which will be A - > b -> c > g > c > f > c > c > c > c
    NSArray *viewControllers = yourNavigationController.viewControllers;
    NSMutableArray *mutableArray = [NSMutableArray arrayWithArray: viewControllers];

    while(1) {
        id viewController = mutableArray.lastObject;
        if ([viewController isKindOfClass:[YourCClassName class]]) {
            //Now continue removing the objects from the array if that is C type object.
            [mutableArray removeLastObject];
        } else {
            //If found any other class than C stop removing viewcontroller
            break;
        }
    }
    //Now mutableArray contains A - > b -> c > g > c > f
    yourNavigationController.viewControllers = mutableArray;
}

A: Because the childViewControllers of navigationController is a stack,
So use this function, you can pop to f viewController and the " c > c > c > c" was destroyed.
for (UIViewController *tempVC in self.navigationController.childViewControllers) {
    if ([tempVC isKindOfClass:[fViewController class]]) {
        fViewController *f = (fViewController *)tempVC;
        [self.navigationController popToViewController:f animated:YES];
    }
}

However, if you don't want to pop to f, just want to get the new childViewControllers of navigationController. you can use next functions:
for (UIViewController *tempVC in self.navigationController.childViewControllers) {
    if ([tempVC isKindOfClass:[ScanViewController class]]) {
        NSUInteger findex = [self.navigationController.childViewControllers indexOfObject:tempVC];
        NSMutableArray *viewArray = [NSMutableArray arrayWithArray:self.navigationController.childViewControllers];
        [viewArray removeObjectsInRange:NSMakeRange(findex, viewArray.count - 1)];
    }
}

The viewArray is the new childViewControllers.And if you have new demand, can edit this function then use it.


text:
Q: Find where android library is hosted Since jcenter will be shut down in May, I'm wondering is there any automated way (gradle task or plugin) to iterate through all android libraries that I use and printing on which repository that library is hosted (jcenter, mavencentral, google).
I already tried with task like this, but it just printing library name (you can get library group or version also).
 task printConfigurations {
        doLast {
            project.configurations.each { config ->
                config.allDependencies.each { d ->
                    println(d.name)
                }
            }
        }

A: You could remove jCenter from your repositories configuration and rebuild the project.
Any now unresolved dependencies were apparently hosted on jCenter.
If it builds fine, it's fine.


text:
Q: jQuery ajax double get with for I'm new with jQuery and I want to know best practices about it... I did something but I feel that this is not the way to go because it does a bunch on query
Here is my code :
$.ajax({
    type: 'GET',
    dataType: 'json',
    url: 'api/items/' + idfinal,
    success: function (data) {
        $('#item-all').empty();
        $('#builder').addClass('hidden');
        if ($('#btnsuc').length === 0) {
            $('#page').append('
<button class="btn-success" id="btnsuc">Retour</button>

');
        }
        else {
            $('#item-searcher').removeClass('hidden');
        }
        for (var i = 0; i < data.length; i++) {
            $('#item-all').append('
'+data[i].nom_equipement + '
');
            idItemActuel = data[i].id_equipement;
            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: 'api/stats/' + idItemActuel,
                success: function (statsItem){
                    for(var x =0; x < statsItem.length; x++){
                        $('#myitem'+statsItem[x].id_equipement).append(statsItem[x].poids_equipement_stats + ' ' + statsItem[x].nom_stats + '
');
                    }
                }
            })
        }
    },
});

I first take data on a particular type, then I extract data from associative entity with the ID I got.
With more data, my ajax will probably take a lot of time to reach all asked elements... What is the best way to go?

A: Your approach is fine. A few things that I would change:

*

*For performance reasons, you should never edit the DOM in a loop. Build your HTML, and then inject it when you're done.

*Put your success callbacks in functions to clean up the code a bit.

EDIT - HTML building example
// Create variable to hold HTML to append to body
let htmlToAppend = "";

for (var i = 0; i < data.length; i++) {
    // Loop through data and build HTML
    htmlToAppend += '
' + data[i].nom_equipement + '
';

  // other code...
}

// Append HTML to container
$('#item-all').append(htmlToAppend);


text:
Q: AWS application load balancer 404 I'm following tutorial to create an application load balancer and the listener path is as follow:
LB -> path -> server1
or   -> path -> server2
The problem:
I can get to server1 via the LB url ok but when I tried to go to server2 i received 404 page.
If i delete & reconfigure the LB & swap the server around then I can get to server2 but will get 404 if i tried to go to server1.
I can get to both server just fine directly.
Thanks for your help

A: I think you're getting 404 because when you access {YourALB}/server1/something the path is passed on to {IntASG}/server1/something instead of {IntASG}/something. If you can check the IntASG access logs you will probably see it there.
IIRC there is a way to remove the routing part of the path before forwarding it on to the backend. Check the ALB docs, it will be described there.
https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#rule-condition-types
Hope that helps :)


text:
Q: Vue.js Error export was not found when using import { } In vue.js. I have the following auth.js, at the bottom of the js file it has "export default". In my Registration.vue file how do I access "actions"?
This is what I have tried:
Registration.vue
import {actions} from 'src/util/auth';
export default {
  components: {
    actions
  },
  data(){
  },
  methods: {
    submitReg() {
      console.log(actions)
    }
  }
}

error: export 'actions' was not found in 'src/util/auth'

This is the auth.js file full code here https://gist.github.com/toricls/5c38d2930a36262f0674c1ffa8d5134a:
import Amplify, { Auth } from 'aws-amplify';

const state = {
  user: null,
};

const actions = {
  async getCurrentUserInfo({ commit }) {
    // This is returning null - why?
    // const user = await Auth.currentUserInfo();
    const user = await Auth.currentAuthenticatedUser();

    const attributes = await Auth.userAttributes(user);
    console.log(attributes);

    commit(types.AUTHENTICATE, {
      username: user.username,
      ...extractAttributes(attributes),
    });
  },

  async signIn({ commit }, { username, password }) {
    const user = await Auth.signIn(username, password);
    const attributes = await Auth.userAttributes(user);

    commit(types.AUTHENTICATE, {
      username: user.username,
      ...extractAttributes(attributes),
    });
  },

  async signOut() {
    await Auth.signOut();
  },

  async signUp(_, { username, password, firstName, lastName }) {
    const data = await Auth.signUp({
      username,
      password,
      attributes: {
        given_name: firstName,
        family_name: lastName,
      },
    });
    console.log(data);
  },
};

const mutations = {
  [types.AUTHENTICATE](state, payload) {
    state.user = payload;
  },
  [types.SIGNOUT](state) {
    state.user = null;
  },
};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
};

A: There are two kinds of exports in es6 modules: named and default.  When you see the braces { } in an import, that's the named import syntax.  It's not the same as destructuring though it looks like it.  You can't destructure inside an import statement. Change your code to:
import myExport from 'src/util/auth';
const { actions } = myExport;

Here are some examples of using both kinds of exports:
Default export examples
export default { a: 1, b: 2 } // Default object export

export default "Some string" // Default string export

Import these like:
import myExport from 'mymodule';  // no braces

Named export examples
export const myExport = { a: 1, b: 2 } // named object export

export const myExport = "Some string"  // named string export

Import these like (note the braces):
import { myExport } from 'mymodule'   // braces

A: I would imagine that this error is happening because it isn't finding the auth.js file. 'src/util/auth' is a relative path (by default in webpack) from the component file but I'm assuming (given the folder naming) that your component file isn't at the top level.
Either input the correct relative path or setup an absolute path alias within your webpack setup. This is a decent article explaining how to do this.


text:
Q: Fibonacci Sequence and changing the rule I wrote a loop to compute the first 10 numbers of the Fibonacci sequence. F(0)=0 ; F(1)=1 ; Rule: F(i)=F(i-2)+F(i-1)
x <- c(0,1)
while (length(x) < 10) {
  position <- length(x)
  new <- x[position] + x[position-1]
  x <- c(x,new)
}
print(x)

Now I wanted to change the rule to: F(i)=F(i-1)-F(i-2)
x <- c(0,1)
while (length(x) < 10) {
  position <- length(x)
  new <- x[position-1] - x[position]
  x <- c(x,new)
}
print(x)

But the (small) change in the code doesn´t deliver the correct sequence.
Is there a smarter way to this?

A: If you want the rule to be F(i)=F(i-1)-F(i-2), then it should be
new <- x[position] - x[position-1]

On another note, if you are going to do this for just a small size vector then it makes no difference, but if you plan to go for a larger number then you should allocate the memory for the object beforehand, with a vector of NAs, Os or whatever you prefer. Otherwise, if you make your vector grow with each iteration, your code could become really slow.
Something like this:
len <- 10
x <- rep(NA, len)
x[1] <- 0
x[2] <- 1
for (i in 3:len) {
  x[i] <- x[i-1] - x[i-2]
}

A: I will do a full parametric function:
 fibonacci <- function(len, x,func){

      while (length(x) < len) {
        position <- length(x)
        new <- func(x,position)
        x <- c(x,new)
      }
      x
    }

    fibo1 <- function(x,position){x[position] + x[position-1]}
    fibo2 <- function(x,position){x[position] - x[position-1]}
    fibo3 <- function(x,position){x[position-1] - x[position]}
    start <- c(0,1)
    fibonacci(10,start,fibo1)
    fibonacci(10,start,fibo2)
    fibonacci(10,start,fibo3)

Or using @mgiormenti best code:
fibonacci <- function(len, x,func){

        for (i in (length(x)+1):len) {
          x[i] <- func(x,i-1)
        }

    x
}

fibo1 <- function(x,position){x[position] + x[position-1]}
fibo2 <- function(x,position){x[position] - x[position-1]}
fibo3 <- function(x,position){x[position-1] - x[position]}
start <- c(0,1)
fibonacci(10,start,fibo1)
fibonacci(10,start,fibo2)
fibonacci(10,start,fibo3)


text:
Q: PERL Scope in foreach loops I have a perl scope question.
use strict;
use warnings;

our @cycles = (0,1,2,3,4);

foreach my $cycle (@cycles){
    my $nextcycle = 0;
    foreach $nextcycle (@cycles){
        if ($cycle+1 == $nextcycle){
            print "found cycle+1, $nextcycle\n";
            last;
        }
    }
    print "current=$cycle, nextcycle=$nextcycle\n";
}

The output I get:

found cycle+1, 1
current=0, nextcycle=0
found cycle+1, 2
current=1, nextcycle=0
found cycle+1, 3
current=2, nextcycle=0
found cycle+1, 4
current=3, nextcycle=0
current=4, nextcycle=0

I expected this:

found cycle+1, 1
current=0, nextcycle=1
found cycle+1, 2
current=1, nextcycle=2
found cycle+1, 3
current=2, nextcycle=3
found cycle+1, 4
current=3, nextcycle=4
current=4, nextcycle=0

I further modified the loop to look like this and got what I wanted:
use strict;
use warnings;

our @cycles = (0,1,2,3,4);

foreach my $cycle (@cycles){
    my $nextcycle = 0;
    foreach my $tempcycle (@cycles){
        if ($cycle+1 == $tempcycle){
            $nextcycle = $tempcycle;
            print "found cycle+1, $nextcycle\n";
            last;
        }
    }
    print "current=$cycle, nextcycle=$nextcycle\n";
}

I want to know why the first loop didn't work!

A: From the Perl manual on the foreach construct:

The foreach loop iterates over a
  normal list value and sets the
  variable VAR to be each element of the
  list in turn. If the variable is
  preceded with the keyword my, then it
  is lexically scoped, and is therefore
  visible only within the loop.
  Otherwise, the variable is implicitly
  local to the loop and regains its
  former value upon exiting the loop.

A: The scope of the variable in foreach my ... is the foreach loop itself.  From perldoc perlsyn:

There is one minor difference: if variables are declared with my in
  the initialization section of the for, the lexical scope of those
  variables is exactly the for loop (the body of the loop and the
  control sections).


text:
Q: what is the integral of the given radicals $$
\int(225-u)^{1/2}\cdot u^{1/2}\, \mathrm du
$$
I don't think it is allowed to combine both because of the minus sign, that's why I'm at a loss on how to integrate this. Please help.

A: First complete the square:
$$
\int \sqrt{225 -u}\;\sqrt{u}\;du = \int \sqrt{225u -u^2}\;du = \int \sqrt{\left(\frac{225}{2}\right)^2 - \left(u^2 - 225u + \left(\frac{225}{2}\right)^2\right)} \; du
$$
$$
= \int\sqrt{\left(\frac{225}{2}\right)^2 - \left(u - \frac{225}{2}\right)^2} \; du = \frac{225}{2} \int\sqrt{1 - \left(\text{something}\right)^2} \; du
$$
Then let $\sin\theta = \text{something}$ and differentiate in order to figure out what goes in place of $du$.
A general idea is that where you have a quadratic polynomial with a first-degree term (in this case the polynomial is $225u - u^2$) you can reduce it to a quadratic polynomial with no first-degree term by completing the square.  That's what completing the square is for.

A: Sorry for the incomplete answer. This is a Chebyshev integral of the kind
$$
\int\limits x^m(ax^n+b)^p\,dx
$$
and there is a theorem that you can express it in elementary functions iff $p\in \mathbb Z$ or $\frac{m+1}{n}\in\mathbb Z$ or $p+\frac{m+1}{n}\in \mathbb Z$. In each case there are substitutions which allow you to express it through the elementary functions.
In your case $m=0.5,n=1$ and $p=0.5$, so $p+\frac{m+1}{n} = 2\in\mathbb Z$ and there is a solution. Unfortunately, I couldn't find substitutions - whenever I will find it, I will put it here.


text:
Q: get the nearest highest value from a list oracle sql I have a column in the database in the following format: yymmddhh24miss
Sample Data:
140203101241
140202101141
140102101240
143001101244
142801101245
142701131347
142601121542
142101131744
...

I need to get the nearest high value from the list. Ex: If I pass 142701131333, then it should return 142701131347 from the above list.
Any help appreciated!

A: SELECT data
FROM
(
   SELECT data
   FROM tbl
   WHERE data > '142701131333'
   ORDER BY data
) a
WHERE rownum = 1

A: SQL> with t (x) as (
  2  select 140203101241 from dual union all
  3  select 140202101141 from dual union all
  4  select 140102101240 from dual union all
  5  select 143001101244 from dual union all
  6  select 142801101245 from dual union all
  7  select 142701131347 from dual union all
  8  select 142601121542 from dual union all
  9  select 142101131744 from dual
 10  )
 11  select min(x) minx from t where x > 142701131333
 12  /

             MINX
-----------------
     142701131347

A: SELECT MIN(sample_data)
FROM tableName
WHERE sample_data > 142701131333


text:
Q: Save data in firestore using user uid as document id and be able to retrieve and update it I'm trying to save data in firestore using user uid as document id and be able to retrieve and update it as well
try {
  await createUserWithEmailAndPassword(
    auth,
    email,
    password
  ).then((userCredential) => {
    updateProfile(auth.currentUser, { displayName: username });
    toast.success('Account successfully created');

    auth.addDoc.collection("users").doc(userCredential.user.uid).set({
      username: username,
      email: email,
    })

A: used setDoc
   setDoc(doc(db, "users", userCredential.user.uid), {
              username: username,
              email: email,

              })


text:
Q: netcdf doesn't work in Node.js program I'm trying to encode a NetCDF file in Node.js program, by using the netcdf(https://www.npmjs.com/package/netcdf) library.
Now, once I run a program, I get an error below.
C:\app [master +2 ~1 -0 !]> npm start

> spaceapps@1.0.0 start C:\app
> node server.js

C:\app\node_modules\text-encoding\lib\encoding.js:979
      throw TypeError('Called as a function. Did you forget \'new\'?');
      ^

TypeError: Called as a function. Did you forget 'new'?
    at TypeError (native)
    at Object.TextDecoder (C:\app\node_modules\text-encoding\lib\encoding.js:979:13)
    at Object.<anonymous> (C:\app\node_modules\netcdf\util\readbinary.js:4:40)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (C:\app\node_modules\netcdf\util\type.js:4:14)

npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files (x86)\\Nodist\\v\\nodev5.9.1\\node.exe" "C:\\Program Files (x86)\\Nodist\\bin\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v5.9.1
npm ERR! npm  v3.8.7
npm ERR! code ELIFECYCLE
npm ERR! spaceapps@1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the spaceapps@1.0.0 start script 'node server.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the spaceapps package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs spaceapps
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls spaceapps
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\app\npm-debug.log
C:\app [master +3 ~1 -0 !]>

It seems there is an error in a library.
I appreciate if someone tells me a solution for it.

A: As the developer said, He has no plans in the short or medium term to continue development, so you could consider use netcdfjs, that it's a javascript library that allows to read NetCDF v3 files. Because it's a NodeJS package you can run it server side, and for regular size files you can read it online, here you have an example.


text:
Q: How to deal with nested transactions in EF7? I know that EF7 doesn't support TransactionScope anymore.
I also know how to do an explicit BeginTransaction().
What I'm struggling with now is situations where a code path may create a nested transaction.
TransactionScope handled this situation very cleanly; the explicit BeginTransaction() does not.
Are there any recommended practices for dealing with the possibility of nested transactions?


text:
Q: If $p$ is a prime and both roots of $x^{2} +px−444p=0$ are integers what is $p$
If p is a prime and both roots of $x^{2}+px−444p=0$ are integers, what
  is $p$

I got that for the roots to be integers the discriminant must be a perfect square. Thus, $p(p + 1776)$ must be a perfect square.
However, at this point I am stuck and do not know how to proceed other than trying values for $p$ and checking what works.

A: HINT:
We have $\displaystyle q^2=p(p+1776)$ where $q$ is some integer
As $p$ is prime, $\displaystyle  p$ must divde $q,q=pr$(say)
$\displaystyle\implies 1776p=p^2(r^2-1)\iff \frac{1776}p=r^2-1$ which is an integer
Check for the prime factors of $1776$

A: Factor it as $(x-a)(x-b)$. Then, $ab=-444p$, so one of $a,b$ is a multiple of $p$. But since $a+b =-p$, they are both multiples of $p$.So $p$ is a divisor of $444$(because $-444p$ would be a multiple of $p^2$)

A: $ x^2\!+px = 444p\,\Rightarrow \,p\mid x^2\,\Rightarrow\,p\mid x\,\Rightarrow\ p^2\mid 444p\,\Rightarrow\, p\mid 444\,\Rightarrow\, X^2\! + X = 444/p,\ X = x/p,\, $ which has roots $\,m,n\,$ with $\ \color{#C00}{m+n} = -1,\,\ mn = -444/p = \color{#c00}{- 4\cdot 3}\cdot 37/p,\ $ so $\ \color{#c00}{m,n},p \, =\, \ldots$

A: By Eisenstein's criterion, the polynomial $x^2 + px - 444p$ is irreducible unless $p^2|444p$.
If both roots of the polynomial are integers, it is not irreducible and hence
$$p^2|444p \;\;\iff\;\; p | 444 \;\;\implies\;\; p = 2, 3 \text{ or } 37$$
So we have only 3 primes to check.


text:
Q: Find a recurrence relation for a word problem My question is as follows:
Find a recurrence relation for the number of n-digit ternary $(0,1,2)$ in which no $1$ appears any where to the right of a $2$
If we introduce an auxiliary variable: let $b_n$ be the number of ternary sequences of length $n$ that do not contain a $2$. If a sequence of length $n$ contains a $2$, you can append a $0$ or a $2$; if it does not contain a $2$, you can append a $0$, a $1$, or a $2$. In particular, you can always append a $0$ or a $2$, and if it does not contain a $2$, you can also append a $1$. Thus,
$$a_{n+1}=2a_n+b_n\;.$$
Clearly $b_{n+1}=2b_n$, and in fact it's not hard to see that $b_n=2^n$: you're just counting binary strings of length $n$. Thus, $$a_{n+1}=2a_n+2^n\;.$$
Is this the correct recurrence relation?

A: This is how I would lay out the answer to be super clear:
You can reason that a valid sequence $a_n$ either contains at least one 2 ($c_{n-1}$ of these) and terminates with a 0 or 2, or contains no 2 ($b_{n-1}$ of these) and terminates in a 1,2 or 3. Hence:
$$a_n=2c_{n-1}+3b_{n-1}\, .$$
Of course, a sequence $a_{n-1}$ either has at least one 2 or none:
$$a_{n-1}=c_{n-1}+b_{n-1}\, ,$$
thus
$$a_n=2a_{n-1}+b_{n-1}\, .$$
But $b_{n-1}$ is just a binary sequence length $n-1$, hence $b_{n-1}=2^{n-1}$ and therefore:
$$a_n=2a_{n-1}+2^{n-1}\, .$$
Iterating:
$$a_n=2(2a_{n-2}+2^{n-2})+2^{n-1}=2^2a_{n-2}+2\cdot 2^{n-1}$$
$$a_n=2^2(2a_{n-3}+2^{n-3})+2\cdot 2^{n-1}=2^3a_{n-3}+3\cdot 2^{n-1}$$
$$\vdots$$
$$a_n=2^na_0+n2^{n-1}\, .$$
Using $a_0=1$ we have:
$$a_n=(n+2)2^{n-1}\, .$$

Alternatively you can reason that the sequence $a_n$ either has no 2 in $2^n$ ways or has it's first 2 in position $k$ (for $k=1,2,\ldots,n$ ) with $2^{k-1}$ binary sequences length $k-1$ of 0s and 1s to the left and $2^{n-k}$ binary sequences length $n-k$ of 0s and 2s to the right. So summing over these possibilities:
$$a_n=2^n+\sum_{k=1}^{n}2^{k-1}2^{n-k}=2^n+\sum_{k=1}^{n}2^{n-1}=2^n+n2^{n-1}\, ,$$
giving the same as before.


text:
Q: Use PHP Gettext without having to install locales I've been looking at options for internationalizing an open source project:

*

*Gettext, which everyone seems to recommend, apparently needs locales to be "installed on your system" to be used. See this note on the PHP manual, which reflects exactly my situation. This SO question also asks about the same problem. This isn't suitable for an open source project because I can't trust that the end users have the appropriate locales installed on their system. Besides, it's very very weird that you have to install locales just to use strings that you've translated (IMO).

*Zend_Translate is also recommended in favour of gettext sometimes, but I'm not using the Zend framework so I don't think it's an option for me. Some people have said you can split it from the Zend framework, but I'd have no clue how. If anyone can tell me what files I need (I've downloaded a tarball of the Zend framework) to pick out, I would be open to using Zend_Translate.

*Arrays. That's what I'm doing now, but it's not ideal because:

*

*It will be using up lots of memory to define every translation, when most won't be used by the current page.

*I am having problems with finding myself duplicating the keys in the array, which has already become 1000 lines of code long and I've barely added anything yet...

*It means non-programmers can't really translate, whereas POedit is the standard that everyone expects to use.

Can I somehow read .mo files without Gettext or Zend_Translate, or must I use Gettext? If so, how can I make all locales work, like in the question I linked to above?
EDIT: I'm now willing to use Zend_Translate. I just need to work out what files I need (it would be great if they could be combined into one file) - I don't want the entire Zend Framework in my project.

Update: I was interested to see how big open source projects handle i18n:

*

*Moodle uses arrays.

*Drupal seems to use arrays, with a database fallback. They also run setlocale('C') to get a generic locale and circumvent the entire setlocale mess.

*Wordpress uses heaps of their own functions for i18n, although underneath does use gettext.

So none of those three random projects use Zend_Translate, nor gettext directly, as far as I can see.
Maybe it's a good idea to use the C locale, store the name of the language in the text domain name, and go from there.

So here's as far as I've got with that:
$lang = 'de'; //debug
setlocale( LC_ALL, 'C' );
bindtextdomain( 'default', PATH . "/locale/$lang" );
bind_textdomain_codeset( 'default', 'UTF-8' );
textdomain( 'default' );

var_dump( file_exists( PATH . "/locale/$lang/C/LC_MESSAGES/default.mo" ) ); //bool(true)

But I still just get the English string, even though I've used poedit, msgfmt etc. to make the appropriate files. I've also tried restarting Apache.

A: Here is the solution:
$lang = 'de'; //debug
setlocale( LC_ALL, 'C.UTF-8' );
bindtextdomain( 'default', PATH . "/locale/$lang" );
bind_textdomain_codeset( 'default', 'UTF-8' );
textdomain( 'default' );

The only difference between that and the example I posted at the bottom of my answer is that it uses C.UTF-8 not just C.
I'll be doing more testing of this, and if it works cross-platform, and will update this answer if I find out anything else.

A: Try gettext-php.  It is a drop-in replacment for gettext written in PHP.  It was originally done for WordPress, I think, because WP needs to run on shared hosts which are not always configured for every locale. This seems to me to be your issue as well.
It has a bit of performance hit, but it has not been an issue for me at all.

A: For anyone still having some problem with this, you can try the code below, which i get from here:
http://php.net/manual/en/function.gettext.php#58310
It solved me on freebsd server, having no extra locale install (fr_FR and my_MY)
This code is also useful when you have some problem with the gettext cache.
<?php
function initialize_i18n($locale) {
  $locales_root="/app/php/locale"; // change This to where you locale folder at
  putenv('LANG='.$locale);
  setlocale(LC_ALL,"");
  setlocale(LC_MESSAGES,$locale);
  setlocale(LC_CTYPE,$locale);
  $domains = glob($locales_root.'/'.$locale.'/LC_MESSAGES/*.mo');
  $current = basename($domains[0],'.mo');
  $timestamp = preg_replace('{messages-}i','',$current);
  bindtextdomain($current,$locales_root);
  textdomain($current);
}
?>