text:
Q: AWS CDK: Dynamo Db Access for Fargate Service I (AWS noob) am playing around with the aws cdk.
I want to build a simple Spring service running in fargate with a dynamodb as a database.
It seems like my service cannot access the dynamo because of some missing permissions.
In the Cloudwatch Logs I see this error message:
com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException: User: arn:aws:sts::xxxxxxxxxx:assumed-role/MyCdkAppStack-TaskDefTaskRole1EDB4A67-xxxxxxxx/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx is not authorized to perform: dynamodb:UpdateItem on resource: arn:aws:dynamodb:eu-central-1:xxxxxxxxxxx:table/MyDynamoDbTable (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: AccessDeniedException; Request ID: XXXXX)

For permissions for the table, I thought it should suffice to grant the necessary permissions to the task role of the fargate service:
props.dependencies.dynamoDb.grantReadWriteData(taskDefinition.taskRole);
In the AWS console, it looks like the permissions should be there: When I go to the corresponding task, the corresponding role seems to have all permissions.
It is not working though, so obviously I am missing something or doing something wrong.
Any hints on how I can connect a fargate service with a dynamo db table in a cdk app?
Thanks, some tips would be greatly appreciated :)
Edit: Sorry for the delay...
Stack:
export class MyCdkAppStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props: MyCdkAppStackProps) {
    super(scope, id, props);

    const appId = 'myService';

    const table = new Table(this, 'MyDynamoDbTable', {
        tableName: 'MyDynamoDbTable',
        partitionKey: {name: 'Id', type: AttributeType.STRING},
        billingMode: BillingMode.PAY_PER_REQUEST,
        removalPolicy: RemovalPolicy.DESTROY
    });

    let logDriver = new AwsLogDriver({
        logRetention: RetentionDays.ONE_WEEK,
        streamPrefix: "test-stream-prefix",
    });

    const vpc = new Vpc(this, 'cdk-my-vpc', {maxAzs: 2});

    new cdk.CfnOutput(this, "MyVpc", {value: vpc.vpcId});

    const cluster = new Cluster(this, "MyCluster", {
        vpc: vpc,
        clusterName: appId
    });

    const appImage = ContainerImage.fromEcrRepository(props.dependencies.appRepo, 'latest');

    const applicationLoadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "FargateService", {
        cluster: cluster,
        taskImageOptions: {
            image: appImage,
            containerPort: 8080,
            logDriver: logDriver
        },
    });

    table.grantReadWriteData(applicationLoadBalancedFargateService.taskDefinition.taskRole);
}

}
Task Role Policy after cdk synth:
"FargateServiceTaskDefTaskRoleDefaultPolicy63F83D6F": {
  "Type": "AWS::IAM::Policy",
  "Properties": {
    "PolicyDocument": {
      "Statement": [
        {
          "Action": [
            "dynamodb:BatchGetItem",
            "dynamodb:GetRecords",
            "dynamodb:GetShardIterator",
            "dynamodb:Query",
            "dynamodb:GetItem",
            "dynamodb:Scan",
            "dynamodb:BatchWriteItem",
            "dynamodb:PutItem",
            "dynamodb:UpdateItem",
            "dynamodb:DeleteItem"
          ],
          "Effect": "Allow",
          "Resource": [
            {
              "Fn::GetAtt": [
                "MyDynamoDbTableC81ED735",
                "Arn"
              ]
            },
            {
              "Ref": "AWS::NoValue"
            }
          ]
        }
      ],
      "Version": "2012-10-17"
    },
    "PolicyName": "FargateServiceTaskDefTaskRoleDefaultPolicy63F83D6F",
    "Roles": [
      {
        "Ref": "FargateServiceTaskDefTaskRole8CDCF85E"
      }
    ]
  }

A: This should help
https://greenchapel.dev/2022/02/18/aws-cdk-fargate-schedular-write-to-dynamodb/
https://serverlessland.com/patterns/cdk-fargate-dynamodb
const dynamoGatewayEndpoint = vpc.addGatewayEndpoint('dynamoGatewayEndpoint', {
  service: GatewayVpcEndpointAwsService.DYNAMODB
});

// Allow PutItem action from the Fargate Task Definition only
dynamoGatewayEndpoint.addToPolicy(
  new PolicyStatement({
    effect: Effect.ALLOW,
    principals: [new AnyPrincipal()],
    actions: [
      'dynamodb:PutItem',
    ],
    resources: [
      `${dynamoTable.tableArn}`
    ],
    conditions: {
      'ArnEquals': {
        'aws:PrincipalArn': `${fargate.taskDefinition.taskRole.roleArn}`
      }
    }
  })
);

// Write permissions for Fargate
dynamoTable.grantWriteData(fargate.taskDefinition.taskRole);

// Outputs
new CfnOutput(this, 'DynamoDbTableName', { value: dynamoTable.tableName });

}
}


text:
Q: Error Code 1215: cannot add foreign key constraint? I am doing an assignment in SQL and I'm trying to add a foreign key on the total table referencing the donuts table.
My code:
CREATE TABLE DONUTS (
DonutID integer not null unique,
Donut_name varchar(35) not null,
Description varchar(35) not null,
Donut_Qty integer not null,
Donut_price decimal not null,
PRIMARY KEY(DonutID, Donut_Qty, Donut_price));

CREATE TABLE TOTAL (
LINE_TOTAL Decimal NOT NULL UNIQUE,
Donut_Qty integer NOT NULL,
Donut_price decimal NOT NULL,
PRIMARY KEY (LINE_TOTAL),
FOREIGN KEY (Donut_Qty) REFERENCES donuts(Donut_Qty),
FOREIGN KEY (Donut_price) REFERENCES donuts(Donut_price));

I'm getting this error:

Error Code 1215: cannot add foreign key constraint

I've checked that the DB engines are the same, and the character sets, and the data types.
What am I doing wrong?

A: CREATE TABLE DONUTS (
    DonutID integer not null unique,
    Donut_name varchar(35) not null,
    Description varchar(35) not null,
    Donut_Qty integer not null,
    Donut_price decimal not null,
    PRIMARY KEY(DonutID, Donut_Qty, Donut_price)
);

CREATE TABLE TOTAL (
    LINE_TOTAL Decimal NOT NULL UNIQUE,
    DonutID integer not null, Donut_Qty integer NOT NULL,
    Donut_price decimal NOT NULL, PRIMARY KEY (LINE_TOTAL),
    FOREIGN KEY (DonutID, Donut_Qty, Donut_price) REFERENCES DONUTS(DonutID, Donut_Qty, Donut_price)
);

Your composite primary key in the DONUTS table has three fields: DonutID, Donut_Qty, Donut_price. The three fields that make up the composite keys suppose to be referenced in the TOTAL table.

A:
Mysql requires an explicit unique key (or primary key) on any column
  referenced as a foreign key in another table.

please refer this link
You are providing non primary key as foreign key which is not going to work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sails 1.0 (Waterline ORM) - MySQL attribute Date I want to store 2 data as Date type but as answer json I always get :
"start": "2023-06-11T23:00:00.000Z", why this is happening?, into my MySQL database is saved like "2023-06-11".
That's my schema
module.exports = {

  attributes: {

    title: {
      type: 'string',
      required: true,
      columnType: 'varchar(50)'
    },
    start: {
      type: 'string',
      columnType: 'date',
      required: true
    },
    end: {
      type: 'string',
      columnType: 'date',
      allowNull: true
    }
  }
};

Thanks!

A: JSON has no standard for dates, so what you're getting in json is just the output of some default toString on your date.
On your server, waterline will treat the attribute as a date. But as soon as you send it to the client via json, it will be this string representation. Luckily, just passing this string into a Date contstructor will yield you the right javascript date object
var apiData = {
    title: 'hello',
    start: '2023-06-11T23:00:00.000Z'
};

var startDate = new Date(apiData.start); // this is a javascript Date object


text:
Q: How to remove old kernel initramfs+vmlinuz in /boot (Archlinux) When I re-install Archlinux, old kernels will leave initramfs and vmlinuz in /boot and exists in my grub config.
But I do not install them so I cannot boot from them.
I cannot delete them by sudo rm, and updating grub does not work.
This is Archlinux and I do not have things like apt-get purge, there is only Ubuntu answers I can find.


text:
Q: "During years 2017-2019" vs. "During the years 2017-2019"

*

*"During years 2017-2019, he appeared four times on the podcast."

  or

*"During the years 2017-2019, he appeared four times on the podcast"

Are both of them correct? If not, which of them and why?
I was not able to find anything on the Web/SE that would provide me with the answer.

A: "During years 2017-2019" and "During the years 2017-2019" both sound unnatural since "years" is discrete, not continuous, and you are describing a period rather than naming the specific years. (You could say "during the years 2017, 2018 and 2019").
It would be more natural to say "During the period from 2017 to 2019" or, more simply, "from 2017 to 2019".


text:
Q: Downgrade to python 3.6.5 with brew: Error /bin/sh: sphinx-build: command not found make: *** [build] Error 127 Please, I'm downgrading to Python 3.6.5 using brew, but I got this error:
Command:
brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb

Error:
mkdir -p build
Using existing Misc/NEWS file
PATH=./venv/bin:$PATH sphinx-build -b html -d build/doctrees -D latex_elements.papersize=  . build/html
/bin/sh: sphinx-build: command not found
make: *** [build] Error 127

Do not report this issue to Homebrew/brew or Homebrew/core!

These open issues may also help:
Python 3.7.2 install fails https://github.com/Homebrew/homebrew-core/issues/36753
pagmo: build with python binding https://github.com/Homebrew/homebrew-core/pull/36445
python@2: fix zlib with CLT on 10.14 https://github.com/Homebrew/homebrew-core/pull/34562

Can someone help me?
PS: Xcode is already installed, I run brew unlink python (to unlink 3.7), sphinx-build is on /usr/local/bin/sphinx-build.

A: The brew formula for 3.6.5 has some issues. Here is a open issue on github about this error.
I have decided to change to pyenv with pyenv-virtualenv in order to avoid using brew switch python 3.xx all time.
As I need to use many different installations of Python on the same machine, 2.7 and 3.4 for example and many virtual environments, just brew swicth and virtualenv is not working well.

A: See python.rb formula for 3.6.8
Step-by-step instructions, with transcript, in my comment in fork:
I had to leave in, that is not comment out the
depends_on sphinx-doc" => :build
to build from source as detailed in my fork comment:
gisthub dukechem fork of python.rb formula for 3.6.8


text:
Q: Why will this code build in MSVC but not Clang? How can I get this code to build using XCode/Clang as shipped with OS X 10.10.3?
// A template class for a property that calls a function on property_value_changed
template <typename T, typename V = void>
class PROPERTY_WITH_LISTENER_FUNCTION : public T
{
    class LISTENER_FUNCTION : public PROPERTY_LISTENER
    {
        std::function<void(V)> m_function;

    public:
        LISTENER_FUNCTION(std::function<void(V)> function)
            : m_function(std::move(function)) {}

        template <typename V2> void do_call(const PROPERTY &p)
        {
            m_function(p.get<V2>());
        }

        template <> void do_call<void>(const PROPERTY &)  // <=== Error here
        {
            m_function();
        }

        virtual void property_value_changed(const UTILITYDLL::PROPERTY &p)
        {
            if(m_function) do_call<V>(p);
        }
    };

    LISTENER_FUNCTION m_listener;

public:
    template <typename... ARGS>
    PROPERTY_WITH_LISTENER_FUNCTION(const String &name,
                                    std::function<void(V)> function,
                                    ARGS&&... args)
        : T(name, std::forward<ARGS>(args)...)
        , m_listener(std::move(function))
    {
        add_listener(m_listener);
    }

    virtual ~PROPERTY_WITH_LISTENER_FUNCTION()
    {
        remove_listener(m_listener);
    }
};

It builds fine in MSVC 2013, but with XCode/Clang I get the error
PropertySet.h:1171:9: error: cannot specialize a function 'do_call' within class scope
void do_call<void>(const PROPERTY &);
     ^

No amount of juggling seems to be able to persuade Clang to do what it's told.  Can anyone come up with a compiling version?


text:
Q: Hosting a database on a VM I need some help understanding how to connect my local machine to a separately hosted database on a different machine.
Context:
I have ssh'd into my host machine (hereafter referred to as VM) and installed MongoDB. The VM runs CentOS and I have no restrictions beyond that.
Goal
My goal is to interact with the VM remotely via my local client on my local machine (Mac), perhaps through some sort of API (direct connection works as well). I'm willing to create that API, but I need to actually establish some sort of contact before that can happen. How can I actually deliver requests from my local machine to the VM, and therefore to my database?
Edit #1:
I should add that this is not exclusive to MongoDB and its host machine. I have several other NoSQL databases (each on their own individual machine). I'm hoping that if I can find a way to make one work, the rest will follow the same pattern.

A: Answer:
I found out that the firewalls were preventing me from connecting to MongoDB on my remote server. So here is how I finally connected and verified:
Remote Server
Stop the firewall:
systemctl stop firewalld

Start up Mongo:
mongod

Local Client
Form connection using Mongo
mongo REMOTE_IP

or
mongo REMOTE_DOMAIN_NAME


text:
Q: how to find a way to find all values of column 1 which don't have any specific entries in column 3 I have data in which we have columns qid,docid, good, fair, bad Good, fair and bad are grades from different graders
and I need to find qid values for which there exists only values that are bad.
qid  docid good fair bad
2     3     2    3   0
2     5     1    0   4
3     2     0    0   4
3     4     0    0   3

In this case I want to find qid = 3 as the only row that has this qid has all rows with only "bad" results. I am unable to find an efficient way to do this operation

A: Use a boolean mask:
>>> df[df[['good', 'fair']].eq(0).all(1) & df['bad'].gt(0)]
   qid  docid  good  fair  bad
2    3      2     0     0    4
3    3      4     0     0    3

>>> df.loc[df[['good', 'fair']].eq(0).all(1) & df['bad'].gt(0), 'qid'] \
      .unique().tolist()
[3]

A: You can use an np.where() as below:
df['Check'] = np.where((df.qid == 3) & (df.bad > 0), True, False)
df[['qid', 'docid', 'good', 'fair', 'bad']].loc[df['Check'] == True]

A: You can use the df.groupby function to get a table with the sum of different grades occurences:
>> filtered_df = df.groupby(by=['qid']).sum().reset_index()

   qid  docid  good  fair  bad
0    2      8     3     3    4
1    3      6     0     0    7

Then you can use df.loc to find the rows with only bad grades:
>> filtered_df.loc[(filtered_df["good"] == 0) && (filtered_df["fair"] == 0)]

   qid  docid  good  fair  bad
1    3      6     0     0    7


text:
Q: Question about proof of completeness of $L^p$ In my notes we prove completeness of $L^p$ by showing that if $\sum\|f_k\|_p < \infty$ then $\sum f_k$ converges in $L^p$. (That's a lemma we prove a bit earlier, namely that $(V, \|\cdot\|)$ is Banach if and only if $\sum \|v_k\|< \infty$ implies $\sum v_k \to v \in V$.)
First we show that if $\sum\|f_k\|_p < \infty$ then $f(x) = \sum f_k(x)$ is in $\mathbb R$ $\mu$ almost everywhere. Once we have that, the notes do the following to show that $\sum_{k=1}^n f_k(x) \to f(x)$ in $\|\cdot\|_p$ (where $g(x) = \sum_{k=1}^\infty |f_k(x)|$):

My question: Do we really have to apply montone convergence yet again? I would do it like this, but maybe that's wrong so I'd appreciate your correction:
$$ \|f(x) - \sum_{k=1}^n f_k(x)\|_p = \| \sum_{k=1}^\infty f_k(x) - \sum_{k=1}^n f_k(x)\|_p = \|\sum_{k=n+1}^\infty f_k(x)\|_p \stackrel{\Delta-\text{ineq.}}{\leq}
 \sum_{k=n+1}^\infty \|f_k \|_p
$$
Since by assumption $\sum \|f_k \|_p < \infty$we have that $\|f_k\|_p$ must be a null sequence (that is, it tends to $0$) hence for $n$ large enough, $ \sum_{k=n+1}^\infty \|f_k \|_p < \varepsilon$ and we're done.


text:
Q: want to add data to the dashboard how to implement if  condition
,if the tasktype is 'to-do' the data should get added to the to-do column and vice versa for ongoing column

To Do

      {% for task in tasks %}
      {% if task.task_type == 'to-do' %}

{{task.title}}

Description

 {{task.description}}

          edit
          delete

      {% endif %}
      {% endfor %}

enter image description here


text:
Q: How to make a similar interface using wxWidgets? How to make a similar interface using wxWidgets  ?
I need to dynamically create text fields. I know how to do this with Delphi gitHub. But how to do it with C++ and wxWidgets?
here is my code. I do not understand what to do
Simple::Simple(const wxString& title)
: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(270, 450))
{
    wxBoxSizer *hbox = new wxBoxSizer(wxVERTICAL);

    for (int i = 0; i < 25; i++)
        {
            hbox->Add(new wxListBox(this, wxID_ANY, wxDefaultPosition, wxSize(250, 60)), wxSizerFlags(0).Border(wxALL, 5));
            auto itm = hbox->GetItem(i);
            itm->SetId(i);
        }
    SetSizer(hbox);
}

A: @Nindzzya,
Basically you create a wxFrame. You put an instance of wxScrolled<> in it. Then inside this wxScrolled<>() you put a vertical wxBoxSizer. And then finally add the appropriate controls inside that sizer.
Following your example:
for (auto i = 0; i < 25; i++)
    {
        textctrl[i] = new wxTextCtrl( this, wxID_ANY, wxDefaultPosition, wxSize( 250, 60 ), wxSizerFlags( 0 ).Border( wxALL, 5 ) )
        hbox->Add( textctrl[i] );
    }

MyFrame::Some_Func()
{
    for( auto i : { 0, 25 } )
    {
        textctrl[i]->GetValue();
    }
}

You don't even need an id or anything like this. And this question is about basic C++. It doesn't have anything to do with wxWidgets.


text:
Q: Why are there a lot of "" in the developer tools to see between my html code in Blazor? Why are there a lot of signs in the developer tools to see between my html code in Blazor?
And how can i get rid of it ?

A: As @yasseros suggested:
github.com/dotnet/aspnetcore/issues/21526

The reason is because the internal JS algorithm uses them to map the
component structure from the Blazor representation to the one in the
page.
Comments are needed to avoid introducing artificial elements to
delimit the start and end of components.
One example of this is if you have something like
   1   2   3
 child.razor
Title @ChildContent Body @ChildContent The renderer
needs to know where each child.razor starts and ends.


text:
Q: What does $dF(y)$ mean? What does $dF(y)$ mean?
Sorry for the silly question. To put it into context. I am trying to figure out how to do solve this problem but I'm not sure how and I think my understanding of notation might be stopping me. Also, if anyone knows the step to solve this I would also appreciate that.
$$ 0 = ( 1 - \tau ) \int _ { - \infty } ^ { \hat { x } } d F ( x ) - \tau \int _ { \hat { x } } ^ { \infty } d F ( x ) = F ( \hat { x } ) - \tau $$

A: Since this involves Probability Theory I assume that $F$ is a distribution funciton. There is a unique probability measure $\mu$ on the Borel sets of $\mathbb R$ such that $\mu (-\infty,x]=F(x)$ for all $x$ and the notation $\int h(x)dF(x)$ stands for $\int hd\mu$.

A: Kavi Rama Murthy is correct.  So when the integrand is $1$ as in the OP we simiplify
$$
\int _ { - \infty } ^ { \hat { x } } d F ( x ) = F(\hat(x))-F(-\infty) = F(\hat{x})
\\
\int _ { \hat { x } } ^ { \infty } d F ( x ) = F(+\infty) - F(\hat{x}) = 1-F(\hat{x})
$$
so that
$$
( 1 - \tau ) \int _ { - \infty } ^ { \hat { x } } d F ( x ) - \tau \int _ { \hat { x } } ^ { \infty } d F ( x ) = (1-\tau)F(\hat{x}) - \tau\;(1-F(\hat{x}))
=F(\hat{x}) - \tau
$$

Note: If $F$ is not continuous at the point $\hat{x}$, then one of those integrals will infolve a one-sided limit of $F$ at $\hat{x}$, and this answer will be wrong.

A: What is $F$ in your exercise? If $F$ is a cumulative probability distribution, then an expression of the form $\int_a^b g(x)dF(x)$ is a Riemann-Stieltjes integral (https://en.wikipedia.org/wiki/Riemann%E2%80%93Stieltjes_integral).
For instance, $\int_a^{b} dF(x) = F(b) - F(a)$.
In the particular case that $F$ is absolutely continuous and its density probability distribution is $f$, then $\int_a^b g(x)dF(x) = \int_a^b g(x)f(x)dx$.


text:
Q: Index class as list and as dictionary Is it good practice to give a class behavior both of a list and a dict?
This allows one to access items via both: instance[str] and instance[int].
For example:
class Population(object):
    def __init__(self, populationlist):
        self.population = populationlist

    def __getitem__(self, value):
        if isinstance(value, str):
            index = self.get_names().index(value)
            return self.population[ index ]
        elif isinstance(value, int:
            return self.population[value]

    def get_names(self):
        return [ ind.name for ind in self.population ]

class Individual(object):
    def __init__(self, name):
        self.name=name

my_pop = Population( [ Individual(name) for name in [ 'a', 'b', 'c', 'd' ] ] )

my_pop['c']
>> 'c'
my_pop[2]
>> 'c'

A: Obviously, you can create a class that handles all of this for you but it won't be optimized. What you should do is use Python's OrderedDict to have an efficient dictionary that has an order.

A: You ask if it's good practice and the answer is a clear: No.
There are some good practices mentioned in the Python module this:
>>> import this

There are four lines that somewhat apply here:

*

*Explicit is better than implicit.:
You implicitly convert a string index to a numeric index!

*Special cases aren't special enough to break the rules.
This is clearly a special case when you enter a string index. What makes it special?

*In the face of ambiguity, refuse the temptation to guess.
That's almost like the special case point. You're guessing that noone would enter an equivalent second item (return the first or second or last then?) and noone would use integers as names.

*There should be one-- and preferably only one --obvious way to do it.
I think this one is quite subjective but I interpret this as "one function should have one purpose that no other function fulfills". Your __getitem__ has two purposes. It wouldn't be a problem to have a method "find_by_name" and one method "find_by_index".

However to also include some constructive feedback: It almost looks like you want a tabular structure. If so you should consider pandas or some database, maybe sqllite?
Just to show how pandas solved this:
>>> import pandas as pd

>>> df = pd.DataFrame({'name': ['a', 'b', 'c', 'd']})
>>> print(df)
  name
0    a
1    b
2    c
3    d

>>> print(df[df['name'] == 'a'])  # index by name
  name
0    a

>>> print(df.iloc[[0]])           # index by index
  name
0    a


text:
Q: Gallery crashed after taking photo (intent) After taking the picture and clicking the "submit" button the Gallery app crashes. How is this possible and how can I fix it? The gallery is never used explicitly in my app.
I used the MediaStore.ACTION_IMAGE_CAPTURE intent to launch the camera.
To save the picture to the file system I used the code provided here: https://developer.android.com/training/camera/photobasics.html
Btw I am using a Motorola TC55 with Android 4.1 (API 16)
Code snippets:
 Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getContext().getPackageManager())    != null) {

        // Create the File where the photo should go
        File photoFile;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            return;
        }

        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(getContext(),
                    "com.example.android.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
        File imgFile = new File(imagePath);
        if(imgFile.exists()) {
            if (HttpManager.isNetworkAvailable(getContext())) {
// Send the picture to the webserver (start AsyncTask)
            } else {
// Save the call to process it later
            }
        }
    }
}

There are no logs available in the logcat, because my app isn't crashing.
The only lines added in the logcat after starting the action are these:
07-29 08:57:13.081 31473-31473/com.test.test W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection

                                                                                [ 07-29 08:57:13.081   180:  736 E/         ]
                                                                                android::status_t android::QCameraStream_preview::getBufferFromSurface(): idx = 3, fd = 82, size = 462848, offset = 0

                                                                                [ 07-29 08:57:13.091   180:  736 E/         ]
                                                                                android::status_t android::QCameraStream_preview::getBufferFromSurface(): idx = 4, fd = 88, size = 462848, offset = 0

                                                                                [ 07-29 08:57:13.091   180:  736 E/         ]
                                                                                android::status_t android::QCameraStream_preview::getBufferFromSurface(): idx = 5, fd = 94, size = 462848, offset = 0

Sometimes I just get this:
07-29 09:01:19.464 12604-12604/com.test.test W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection

A: Such problems occur when the input connection in the previous page(or class) has not been closed. Check whether you've closed the input connection in the previous class (by giving connection.close()).
This problem arises when you leave the activity and keep an HTTP connection open.

A: I fixed it by using the code from the sample project: android developer site
I think the problem was that Android 4.1 is not fully compatible with the FileProvider. And thereby there was a fault while saving the picture in the file (in the Gallery application). The sample code doesn't use it (yet).


text:
Q: bicep/arm template how to get display name of location In bicep or arm template, how to get display location name?
Eg, I have input location name 'westus', I want to get its displayName like 'West US' since I have to put location name in an alert condition like:
{ field: 'properties.impactedServices[*].ImpactedRegions[*].RegionName' containsAny: [ 'west us' ] }
By the way, ``listLocations('/subscriptions/${subscriptionId}/providers/Microsoft.Web/locations/${toLower(location)}', '2016-06-01').displayName
which seems not work.

A: I dont think thats possible. ie this list doesnt show that is supported. and list* operations are actually HTTP PUT requests, not HTTP GET.
So I'd expect you'd need to add that data to the template


text:
Q: Why am I getting a value error in imagegrab pil? So I am making an Tkinter painting application but I keep getting a Value:Error which is blocking me from proceeding and I don't know how to solve it.
here is my code
from tkinter import *
from tkinter import Scale
from tkinter import colorchooser, filedialog, messagebox
import PIL.ImageGrab as ImageGrab

class Paint():          # the class adds the screen for all the widgets to be added on
    def __init__(self,root):
        global color
        self.root = root
        self.root.title("Paint")
        self.root.geometry("800x520")
        self.root.configure(background='white')
        self.root.resizable(100,100)

        self.pen_color ="black"
        self.eraser_color = "white"

        # Adding the widgets
        self.color_frame = LabelFrame(self.root, text='Color Palette', font=("Lucida's Caligraphy",15),bd=10, relief=RIDGE, bg='pink')
        self.color_frame.place(x=0,y=0,width=145,height=190)

        colors = ["#ff00ff", "#ff0000", "#ffa600", "#ffff00", "#80ff80", "#00ff00", "#09ff90", "#0ff8c0", "#00d0ff", "#00ffff", "#ffffff", "#fff3d4", "#808080", "#404040", "#202020", "#000000"]
        i=j=0

        for color in colors: # this is the creation for the positioning of the colors
            Button(self.color_frame,bg=color,bd=2,relief=RIDGE,width=3,command=lambda col=color:self.select_color(col)).grid(row=i,column=j) # this is the creation for the color buttons
            i+=1
            if i==4:
                i=0
                j+=1

        self.eraser_button = Button(self.root,text='Eraser',bg='violet',bd=2,relief=GROOVE,width=3,command=self.eraser)     # this is the creation for the eraser button
        self.eraser_button.place(x=0, y=187, width=60, height=30)

        self.clear_button = Button(self.root,text='Clear',bg='light blue',bd=2,relief=GROOVE,width=3,command=lambda : self.canvas.delete("all"))     # this is the creation for the clear button
        self.clear_button.place(x=0, y=217, width=60, height=30)

        self.save_button = Button(self.root,text='Save',bg='light green',bd=2,relief=GROOVE,width=3,command=self.save_paint)        # this is the creation for the save button
        self.save_button.place(x=0, y=247, width=60, height=30)

        self.canvas_button = Button(self.root,text="Canvas",bg='light cyan', bd=4, width=8,relief=GROOVE,command=self.canvas_color)     # this is the creation for the canvas button
        self.canvas_button.place(x=0, y=277)

        self.pen_scale_frame = LabelFrame(self.root,text='size', bg='white', bd=5, font=('arial', 15), relief=RIDGE,)   # this is the creation for the box that contains the colors
        self.pen_scale_frame.place(x=0, y=310, width=70, height=200)

        self.pen_scale = Scale(self.pen_scale_frame, orient=VERTICAL,from_=100, to=0,length=150)    # this is the creation for the scale
        self.pen_scale.set(1)
        self.pen_scale.place(x=5,y=10)

        self.canvas = Canvas(self.root, bg='light cyan', bd=4, relief=GROOVE, width=1105, height=630)   # this is the creation for the canvas
        self.canvas.place(x=150, y=0)

        self.canvas.bind("<B1-Motion>",self.paint)      # this binds the mouse motion with the canvas

    def paint(self,event): # this is the function for the ink to be shown on the canvas
        x1,y1 = (event.x-0),(event.y-0)
        x2,y2 = (event.x+0), (event.y+0)

        self.canvas.create_oval(x1,y1,x2,y2,fill=self.pen_color,outline=self.pen_color,width=self.pen_scale.get())

    def select_color(self, col):    # this is the function for selecting colors for my pen
        self.pen_color = col

    def eraser(self):       # this is the function for copying the colors that my canvas has for my eraser
        self.pen_color = self.eraser_color

    def canvas_color(self):     # this is the function for selecting colors for my canvas
        color = colorchooser.askcolor()
        self.canvas.configure(background=color[1])
        self.eraser_color = color[1]
        self.pen_color = color[1]

    def save_paint(self):       # this is the function for screenshotting whatever is on the canvas
        global filename

        filename = filedialog.asksaveasfilename(initialdir='C:/',filetypes=[('All files','.*'), ('Picture Files','.png*')])
        print(filename)
        cx = self.root.winfo_rootx() + self.canvas.winfo_x()
        print(cx, self.root.winfo_rootx())
        cy = self.root.winfo_rooty() + self.canvas.winfo_y()
        print(cy)
        cx1 = cx + self.canvas.winfo_width()
        print(cx1)
        cy1 = cy + self.canvas.winfo_height()
        print(cy1)
        filename = filename + '.jpeg'
        ImageGrab.grab().crop((cx1, cy1, cx, cy)).save(filename)    # <-- The value:Error redirects me here
        messagebox.showinfo('paint sys','image is saved as '+ str(filename))

if __name__ == "__main__":
    root = Tk()
    p = Paint(root)
    root.mainloop()

the error
**ImageGrab.grab().crop((cx1, cy1, cx, cy)).save(filename) line 1171, in crop
raise ValueError("Coordinate 'right' is less than 'left'")
ValueError: Coordinate 'right' is less than 'left'
**
Whats wrong with my code?


text:
Q: rails polymorphic with includes based on type of class Let's say we have these models
class Message
  belongs_to :messageable, polymorphic: true
end

class Ticket
  has_many :messages, as: :messageable
  has_many :comments
end

class User
  has_many :messages, as: :messageable
  has_many :ratings
end

class Rating
  belongs_to :user
end

class Comment
  belongs_to :ticket
end

Now I want to load all messages (which have associated tickets or users), and eager load depending on the type of class, either comments for tickets and ratings for users
Of course Message.includes(:messageable).order("created_at desc") will only include the directly associated object, but the question would be how to include the different association types that derive from each model type (i.e. in this example, how to eager load comments for tickets and ratings for users)?
This is just a simple example, but what about even more complicated cases, where I'd like to include something else for the user, another association, and what if that association needs more includes?

A: The only way I can think of to do this is to duplicate the associations on each model with a common name:
class Ticket
  has_many :messages, as: :messageable
  has_many :comments
  has_many :messageable_includes, class_name: "Comment"
end

class User
  has_many :messages, as: :messageable
  has_many :ratings
  has_many :messageable_includes, class_name: "Rating"
end

Message.includes(:messageable => :messageable_includes) ...

I'm not sure I would use this strategy as a widespread solution, but if this is a complicated as your case gets, it may work for you.

A: I've used the following helper methods in my own project:
def polymorphic_association_includes(association, includes_association_name, includes_by_type)
  includes_by_type.each_pair do |includes_association_type, includes|
    polymorphic_association_includes_for_type(association, includes_association_name, includes_association_type, includes)
  end
end

def polymorphic_association_includes_for_type(association, includes_association_name, includes_association_type, includes)
  id_attr = "#{includes_association_name}_id"
  type_attr = "#{includes_association_name}_type"

  items = association.select {|item| item[type_attr] == includes_association_type.to_s }
  item_ids = items.map {|item| item[id_attr] }
  items_with_includes = includes_association_type.where(id: item_ids).includes(includes).index_by(&:id)

  items.each do |parent|
    parent.send("#{includes_association_name}=", items_with_includes[parent[id_attr]])
  end
end

These would allow you to say:
messages = Message.all
polymorhpic_association_includes messages, :messageable, {
  Ticket => :comments,
  User => :ratings
}

Not a particularly fluent interface but it works in general.

A: Place the includes on a default scope for each model:
class Ticket
  has_many :messages, as: :messageable
  has_many :comments
  default_scope -> { includes(:comments).order('id DESC') }
end

class User
  has_many :messages, as: :messageable
  has_many :ratings
  default_scope -> { includes(:ratings).order('id DESC') }
end

Then whenever you call Message.all each polymorphic association will include it's own resources.
Also if you need to call the class without the scope just use unscoped or create a different scope:
class Ticket
  has_many :messages, as: :messageable
  has_many :comments
  has_many :watchers
  default_scope -> { includes(:comments).order('id DESC') }
  scope :watched -> {includes(:watchers)}
end

Ticket.unscoped.all # without comments or watchers (or order)
Ticket.watched.all  # includes watchers only


text:
Q: Is a test set sampled after training examples have been removed by an active learning algorithm valid? In this case desire is to optionally label a final test set after training.  The training is to be done using an active learning approach which can be biased towards different characteristics (indecision, confidence, etc).
Would the test set in this scenario be useful at all?  For example, if the active learning algorithm was biased to select high confidence samples the remaining data would have a different mix of data than what was started with (less positives and less high confidence data).  Would totally invalidate the test set or can you still draw valid conclusions from it?


text:
Q: When doing Acceptance Testing and following BDD, do you assert database changes or just what the user sees? I am doing acceptance testing with Steak on a Ruby on Rails application. Imagine I want to test the functionality of a form.

*

*It should create an user if all the fields are correct.

*It should not create a user if any of the fields are incorrect.

In the first case, a message will inform that the user has been created: 'The user has been created'
In the second case error messages will indicate the errors.
I can base my tests on the information displayed. That is, the first test pass if the correct message is displayed.
Or I can base my tests on the changes on the database. That is, the first test pass if the database has a new user which contains the data entered.
Or I can assert for both conditions, database should change and the appropriate message should be displayed.
What is the conceptually adequate way of testing this kind of behaviour, according to Behaviour Driven Development?
What is the practical way of testing this kind of behaviour, according to being a Pragmatic Programmer?

A: Generally, keep to what the user sees.
However, sometimes there's more than one user of the information. Perhaps, once the data has reached the database, another application then uses that data (fairly typical for internal projects!)
If you can't automate with both applications together, then asserting the contents of the database, or perhaps verifying resources on a RESTful URL, can be a good way to go.
If you do this, it will probably change the nature of your scenarios. Rather than saying, Then the database should contain XYZ, try something like:
Given that Fred Brown lives at 25 Warrington Grove, Springfield
When Fred orders a deckchair
Then the warehouse should receive an order:
    Deckchair
    Quantity: 1
    To: Fred Brown
    25 Warrington Grove
    Springfield

So you're always looking at the capabilities of the system, rather than just the data - even if the warehouse doesn't really receive it in your scenario, you're showing why the data has to be in that particular place and form.
This way, you also leave yourself the option of using a real UI, or a RESTful URL, etc. later - the step is independent of the implementation you choose.

A: My BDD practices involve using Cucumber.  I try my hardest to keep it to what the user sees.  That is, any When and Then statements should reflect user input or user visuals.
In your case I would make sure that a success message appears afterwards, and then I would (if possible) look for data on the screen indicating the application is aware of the object.  For instance, if you added a comment to a blog post you should fill in the post, hit the 'accept' button, see a 'Message Posted' success message, and then also see your content on the page as a new post.
You should back up your user-driven BDD tests with unit and sometimes controller tests to make sure everything behind-the-scenes is functioning correctly as well.
I tend to use RSpec and verify that things get added to the database, methods are returning expected results etc.  But I also use Cucumber to make sure the user sees what the user is expecting to see (But I don't really let cucumber care about what's in the DB).
I hope this helps.  If you aren't using cucumber yet I highly recommend it for BDD testing in conjunction with RSpec.  You should check out the book (comes in electronic PDF form) - I started with that and it helped a ton with my testing practices:
http://www.pragprog.com/titles/achbd/the-rspec-book

A: I would agree with keeping with what the user see's, up to a point.
If there is some kind of layer that could potentially persist a value in memory, such that it might show up on the site as if it was in the db, when it's not actually been written out TO the db..  then it might be a good idea to back up your 'what the user's see's' with some checks at the db level.


text:
Q: CSS for displaying Message I have the ajax Loading Message which displays in the middle of the Page
#message {
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    margin-top: -10px;
    line-height: 20px;
    text-align: center;
}

I am just trying to make a fix to have a image around it so it looks separate and identifiable that something is loading


text:
Q: Difference between Locks, Mutex and Critical Sections There is an existing question regarding difference between Mutex and Critical section but it does not deal with Locks also.
So i want to know whether Critical sections can be used for thread synchronisation between processes.
Also what is meant by signalled states and non-signalled states

A: In Windows critical sections are (mostly) implemented in user mode, and a mutex will switch context to kernel mode (which is slow). If a thread terminates while owning a mutex, the mutex is said to be abandoned. The state of the mutex is set to signaled, and the next waiting thread gets ownership. In the same situation with a critical section all other threads will remain blocked. Critical sections cannot be named so you cannot use them to synchronize several processes.

A: CriticalSections are in process. Named mutexes can be used across processes
Lock is a general term and as such I wouldn't know which platform you mean. For example in C# a lock primitive is a Critical Section.

A: Critical Sections are not kernel objects. They are not identified with any Handle. They can be only used to synchronize the threads belonging to same process. They cannot be used for synchronization across the process.
CSingleLock ( I assume you are referring this as a lock, in this context) is a wrapper class using RAII concept. It helps you to acquire the thread synchronization object (in its constructor) and call Lock and Unlock  API in a easy way. ( hiding all internal details of which synchronization objects it is using).
CSingleLock when used with Critical sections, cannot be used across process. Where as Mutex can be used for this purpose.
When a thread acquires Mutex and no other threads can acquire the Mutex then the state of the Mutex is said to be in Non-Signeled state.
IF the Mutex is available and no threads have acquired then it is in Signeled state.

A: 1) Critical Section is the bridge between User and Interlocked-operations. It uses inetrlocked-exchanged operations to lock and unlock you threads. It works faster than mutexes.
2) Mutex is a kernal object. It works not fast but has some advantages. First of all, named mutexes can be used across processes. Secondly, if the thread is terminated then mutex locked by this thread is unlocked.


text:
Q: Where in Ubuntu SPI pins are configured? I'm running Ubuntu on a custom embedded system. The SPI bus master is spi-pxa2xx. I've tried my code on several other systems and it worked fine. But on this system all I see is CS activity while I'm trying to send data over SPI. CLK, MISO and MOSI are staying low. I wanted to make sure that the bus master actually is configured correctly and is using the right pins for the SPI. My question is: Where in the kernel is the  pins/GPIOs configurations for every bus, and specifically for SPI.
Thanks


text:
Q: symfony add unique values from array collection within foreach loop on prepersist I'd like to add 'markets' to my document which can be created within a form where you can select agencies which are assigned to these markets. So you don't specifically select the markets but they are automatically added by selecting the agencies.
The logic behind this is working but one thing I didn't yet achieve:
there are several agencies for one market, but I only want the markets to be displayed once. My foreach loop looks like that:
if(count($this->getAgencies()) > 0){
  foreach($this->getAgencies() as $agency) {
       $this->addMarket($agency->getMarket());
    }
  }
}

this is working well, as long as I select only one agency per market. As soon as I select several agencies for one market, it's not working anymore. to avoid this, I changed the code to:
$markets = $this->getMarkets();
if(count($this->getAgencies()) > 0){
  foreach($this->getAgencies() as $agency) {
    if(!$this->markets->contains($markets)) {
      $this->addMarket($agency->getMarket());
    }
  }
}

Since markets and agencies are both arraycollections, a simple "in_Array" or "unique_array" is not working. So I thought "contains" is the function I should use for arraycollections. But apparently it's not..
Any further ideas? :)

A: change condition part code, you should check if market for agency already exists in $this->markets collections:
if(!$this->markets->contains($agency->getMarket())) {
      $this->addMarket($agency->getMarket());
}


text:
Q: System.Reflection multiple assemblies error after update After updating .NET Framework NuGet packages that my solution references to last prerelease version. I've got a building error:

Multiple assemblies with equivalent identity have been imported:
  'C:\Projects\RP\packages\System.Reflection.4.1.0-beta-23516\lib\net46\System.Reflection.dll'
  and 'C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.6\Facades\System.Reflection.dll'.
  Remove one of the duplicate references.

I can't figure out how resolve this issue. If I remove System.Reflection using NuGet it throws reference error exception, it wants System.Reflection v.4.1.0.0.

Could not load file or assembly 'System.Reflection, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

How can I remove a duplicate?

A: The problem was solved by changing this line in app.config:
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />

to
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />

Managing .NET Framework packages in Visual Studio projects is messy.
Information about references exists in .csproj / .vbproj, app.config, packages.config.

A: You can also just grab the system.reflection 4.1.0.0 from Nuget rather than reverting back to 4.0.0.0.
Version 4.1.0.0 is in it's own Nuget Package, which is why it tends to be confusing.
I actually prefer this way, because if you run a nuget restore, any nuget packages that depend on System.Reflection 4.1.0.0, will revert any changes you made to your app.config.
Meaning, if you change your reference to 4.0.0.0, it'll revert back to 4.1.0.0 on a nuget restore.


text:
Q: Difference between OPL Interfaces and Concert Technology in IBM ILOG CMPLEX Optimization Studio I am new to IBM's CMPLEX Optimization Studio and I try to understand what is the best approach to take for realizing my goal. I am trying to implement a decision optimization solution, expressed as a Mix Integer Linear Program by creating a relevant representation for my problem and then interface it with the CMPLEX solver.
Initially, I started developing the model in the OPL language. However, as I intend to be dynamically calling the solver with the same model but with different data, from my C++ application, I realized that it makes more sense to build the model and call the solver through the CMPLEX C++ API, part of the Concert Technology (#reff1, #reff2). Of course, the interfaces the Concert Technology exposes for building your model are much more low level, in terms of how easy it is to express it, compared to building your model in OPL and running it directly. Then, I learn about the "OPL Interfaces" which also exposes a C++ API from which if understand it correctly, you can load your model from an OLP definition and use custom data sources, and invoke the solver.
So my question is how the OPL Interfaces and CMPLEX APIs (Concert Technology) for a specific language compare if both can be used for the same purpose, to build and execute the optimization model? I understand that the OPL Interfaces and the C++ API of OPL are based on the C++ Concert Technology. If the goal is to quickly test the model but with custom data input dynamically given by my C++ application, should I go for the OPL INterfaces, or there a reason why going for the CMPLEX C++ API in Concert Technology is better?
Software Version: IBM ILOG CMPLEX Optimization Studio 20.1.0

A: In contrast to Alex's answer (we both know each other well!), I would definitely recommend using the Concert library API calls directly from C++. I have used OPL on a number of projects over the last 20 years, and I have used the Concert API calls from C++, Java and C# on many projects too. For me at least, I find the finer-grained integration of my modelling variables and constraints directly into my C++ (or C# or Java) code to be a huge advantage.
If you are coming from a background used to modelling languages (AMPL, GAMS, MPL etc) then it may seem more complex or difficult when you first start to use the Concert API. However if you are coming from a standard coding background using C++, C# or Java then treating CPLEX as just a set of library objects and functions may seem more natural than having to learn another specialist programming language.
We have found that working entirely with the Concert APIs from C++ (or C# or Java) changes your perception of working with CPLEX. Software developers that we have worked with seem to be happier, because then CPLEX is just another piece of software that we can use like any other. We can have the CPLEX IloNumVars etc as member variables in our normal C++ classes, put them in dictionaries, lists or arrays; generally treat them just as normal C++ objects. This makes it easy to integrate your CPLEX modelling variables and constraints into your software.
If you want to use OPL then it definitely encourages (enforces?) a separation between your standard (C++) code and the mathematical model internals. You may find that to be an advantage (keeping the model separately in a different language) or not. Even using OPL, if your data structures (in the data, database or C++) change you will probably have to update the OPL structures and code as well, so we found that often leaves you with an extra set of things to keep updated or synchronised.
There really is no 'correct' choice - it really depends on your (and your team's) preferences. Whether you use OPL or the Concert APIs, these are just ways to get your model into CPLEX. There should be no difference in solving performance

A: I address this question in Optimization (aka prescriptive analytics) : Should we write the model in a modeling language or a general programming language ?
I tend to recommend OPL and then you may see all OPL objects as C++ objects through OPL C++ APIs. Unless you want to save time and memory and you are ready to spend much more human time building your model.
I made some survey at https://www.linkedin.com/pulse/which-aml-gpl-do-you-use-call-cplex-alex-fleischer/ and got


text:
Q: Labeling a vertical asymptote written upwards (only using pgfplots) I would like the code that instructs TikZ to plot the asymptotes to the graph for the rational function y=(x^{2})/(x^{2}-9). What is the code for plotting these lines as a dashed lines with arrowheads?  These should be a little shorter than the axes.
The labels x=-3 and x=3 are to be typeset on the vertical asymptotes. Preferably, they would be typeset towards the bottom arrowheads, going upwards. (How do I label the axes? y is to be typeset to the right and above the top arrowhead on the y-axis, and x is to be typeset to the right and below the right arrowhead on the x-axis.)
\documentclass[10pt]{amsart}
\usepackage{tikz}
\usetikzlibrary{calc,angles,positioning,intersections,quotes,decorations.markings}
\usepackage{tkz-euclide}
\usetkzobj{all}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}

\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}

\begin{document}

\begin{tikzpicture}
\begin{axis}[width=4in,axis equal image,
    axis lines=middle,
    xmin=-15,xmax=15,
    ymin=-5,ymax=5,
    restrict y to domain=-10:10,
    enlargelimits={abs=1cm},
    axis line style={latex-latex},
    ticklabel style={font=\tiny,fill=white},
    ytick={-2},xtick={-2}
]
\addplot[samples=250,domain=-15:15] {(x^2)/(x^2-9)};
\draw[dashed,latex-latex] ({{1,0}}|-{{axis description cs:1,1}})
                       -- ({{1,0}}|-{{axis description cs:1,0}});
\end{axis}
\end{tikzpicture}

\end{document}

A: For labeling the axes, look at the section about axis labels (section 4.9.3 in my version). You probably want something like xlabel=$x$ and ylabel=$y$ in your axis options.
For labeling the asymptotes, you can place a node[left] {-3} after the coordinates in the \draw[dashed] command:
\draw[dashed,latex-latex] ({{1,0}}|-{{axis description cs:1,1}})
                       -- ({{1,0}}|-{{axis description cs:1,0}})
                          node[left] {-3};

Finally, shorten > and shorten < are TikZ options, which shorten the end and the start of a line, respectively, by the specified length. Simply add them to the options of the \draw command.


text:
Q: Nutch .Net implementation We are building an enterprise search application and we use Lucene.net for indexing. We are looking to have a crawler.Is there a .Net implementation of Nutch - Web crawler? or is there any ongoing efforts for the same?

A: I don't experince with it, but you can give it a try - http://arachnode.net/
as it indicates, its data is stored in Lucene.Net indexes.

A: There was an effort for nutch.net for a while but it was abandoned.


text:
Q: What is the obstruction for a local set of models of a curve to come from a global model? If $X_{\mathbb{Q}}$ is a curve over $\mathbb{Q}$, we get a curve $X_{\mathbb{Q}_p}$ over $\mathbb{Q}_p$ for every prime $p$.
My question is about the reverse process. Say we are given curves $X_{\mathbb{Q} _ p}$ for every $p$ such that $X_ { \bar {\mathbb{Q}} _ p} \cong X_ {\bar{ \mathbb{Q}} _ q}$ for any two primes $p$ and $q$ (where the isomorphism is as schemes; alternatively, they are isomorphic when base-changed to an algebraically closed field that contains both $\mathbb{Q}_p$ and $\mathbb{Q} _ q$). Then is there a nice way to describe the obstruction for these models to come from a global curve $X_{\mathbb{Q}}$ over $\mathbb{Q}$?

A: Interesting question. I guess the answer will be very different depending on genus $0,1,>1$. I think I can say something about genus zero.
The condition over the algebraic closures is vacuous for genus zero. For any field $K$ of characteristic zero, a curve of genus zero is isomorphic to a conic $ax^2+by^2=z^2$. When $K=\mathbb{Q}_p$ we can associate the Hilbert symbol $(a,b)_p$ which is $1$ if the conic has a point in $K$ and $-1$ if not. What's the condition that a collection $(a,b)_p$ (I'll include $p=\infty$ as well) comes from a global conic? You need that $(a,b)_p=1$ for all but finitely many $p$ and that $\prod (a,b)_p =1$ (Hilbert reciprocity). That these conditions are necessary and sufficient are proved, e.g., in Serre's Cours d'Arithmétique.
I am worried however that the question in general may not make sense, since the isomorphisms between the algebraic closures of the various $p$-adic fields are not unique. Say, in genus one, you need to give $p$-adic $j$-invariants for each $p$ all agreeing up to these isomorphisms. Does this mean that these come from a global $j$? Then is a question of local/global Weil-Chatelet groups. I don't know what happens there.

A: You might be interested in Mazur's famous article On the passage from local to global in number theory.
Mazur conjectures that if a family of varieties $V_p$ over $\mathbf{Q}_p$ indexed by the places $p$ (including $p=\infty$) of $\mathbf{Q}$ comes from a variety $V$ over $\mathbf{Q}$, then there are only finitely many $V$ (up to $\mathbf{Q}$-isomorphism) with this property.
This is true for curves of genus $0$ (see Felipe's answer) and more generally for projective spaces or quadrics of any dimension. In these cases you have not only finiteness but uniqueness.  For twisted forms of projective spaces, there is a criterion for existence : almost all the local invariants must vanish, and their sum must vanish.
But it is open for curves of genus $1$, although he relates this conjecture to the conjectural finiteness of the Shafarevich-Tate group of elliptic curves over $\mathbf{Q}$.
For curves of genus $>1$, it is relatively easy to prove Mazur's conjecture (because the automorphism group in question is finite).
Counterexamples (?) Here is one approach to constructing counterexamples (as in your question, not to Mazur's conjecture!) in every genus $g>0$.
Start with a curve $C$ over $\mathbf{Q}$ of genus $g$, and take $X_p$ to be $C_p=C\times_{\mathbf{Q}}\mathbf{Q}_p$ for every odd $p$ (and $p=\infty$, if you wish), but take $X_2$ to be a twist of $C_2$ (in the sense that they become isomorphic over an algebraic closure of $\mathbf{Q}_2$) but such that the jacobian $\mathrm{Jac}(X_2)$ of $X_2$ is not isogenous to $\mathrm{Jac}(C_2)$; presumably this can be arranged.  If so, the family $(X_p)_p$ cannot come from a curve $X$ over $\mathbf{Q}$ : for any such $X$, $\mathrm{Jac}(X)$ will have to be isogenous to $\mathrm{Jac}(C)$, whereas they are not isogenous at the place $2$ by construction.

A: I agree with the previous opinions that this should fail for $g>0$. Here's an example.
Let $C$ be a universal (hyper)elliptic curve $y^2=\prod_i (x-t_i)$.
This is clearly defined over $K=\mathbb{Q}(t_1,\ldots)$, but it
wouldn't be defined over $\mathbb{Q}$. (Suppose it were, then by specialization any
(hyper)elliptic curve would be.)
After choosing embeddings $K\subset \mathbb{ Q}_p$ for each $p$,
we get a compatible family of $p$-adic curves which don't descend to the rationals.

A: I think the following interpretation of your question is false for cardinality reasons.  It occurred to me before I saw Donu's answer but seems to have a similar flavour.
I will say that two curves over a field are twists of each other if they become isomorphic over an algebraic closure.
Interpretation. Fix a curve $C$ over $\mathbf{Q}$.  For every place $v$ of $\mathbf{Q}$, let $X_v$ be an arbitrary (random) twist of $C_v$.  Does there exist a curve $D$ over $\mathbf{Q}$ such that $D_v$ is isomorphic to $X_v$ for every $v$ ?
In genus $0$, not every such family can come from a conic over $\mathbf{Q}$, as Felipe has remarked.
In genus $g>0$, if we start with a hyperelliptic curve $C$, then we get uncountably many families $(X_v)_v$ by taking random quadratic twists at each place $v$.  All these families satisfy your hypotheses, and some cannot come from the countably many genus-$g$ curves over $\mathbf{Q}$.
Examples.  Suppose we have an elliptic curve $E$ over $\mathbf{Q}$ which is the only curve in its isogeny class, and assume moreover that Ш$(E)$ is trivial.  It follow that if a genus-$1$ curve $C$ is such that its jacobian $J$ is isomorphic to $E$ almost everywhere locally, then $J$ is $\mathbf{Q}$-isogenous to $E$, and hence $\mathbf{Q}$-isomorphic to $E$, and hence $C$ is isomorphic to $E$ (because Ш$(E)$ is trivial).
Construct the family $(X_v)_v$ by taking $X_v=E_v$ for every place $v\neq2$ of $\mathbf{Q}$, and perversely take $X_2$ to be a quadratic twist of $E_2$, so that $X_2$ and $E_2$ are not $\mathbf{Q}_2$-isomorphic.
If there were a genus-$1$ curve $C$ such that $C_v$ is $\mathbf{Q}_v$-isomorphic to $X_v$ at every $v$, then $C$ would have to be $\mathbf{Q}$-isomorphic to $E$ (by the choice of $E$, as explained above), which is impossible because they are not  $\mathbf{Q}_2$-isomorphic.
It remains to find such an $E$.  I'm sure this can be done by looking at the tables made by Cremona and Stein.  Could someone please confirm this hunch ?


text:
Q: Changing the initial scene in spritekit Aim:
To load the scene in Instructions1.swift file as the first scene of the game.
What I did :
So I created 2 new files in my project : Instructions1.sks and Instructions1.swift
Then in GameViewController.swift , I changed the viewDidLoad as follows :
 override func viewDidLoad()
    {
        super.viewDidLoad()

        if let scene = GameScene.unarchiveFromFile("Instructions1") as? GameScene
        {
            // Configure the view.
            let skView = self.view as! SKView
            skView.showsFPS = true
            skView.showsNodeCount = true

            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true

            /* Set the scale mode to scale to fit the window */
            scene.scaleMode = .AspectFill

            skView.presentScene(scene)
        }
    }

However when I load the game, it goes straight to GameScene.swift. I also wrote 'Instructions1' under the Custom Class for  Instructions1.sks . Still no luck unfortunately!
Would appreciate any help!
Thanks!

A: You should change the name of the scene that you're loading up. Also using the init(fileNamed:) initializer is a go-to for me when loading a SKScene from a file.
Hopefully this helps!
override func viewDidLoad()
{
    super.viewDidLoad()

    if let scene = Instructions1(fileNamed:"Instructions1")
    {
        // Configure the view.
        let skView = self.view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true

        /* Sprite Kit applies additional optimizations to improve rendering performance */
        skView.ignoresSiblingOrder = true

        /* Set the scale mode to scale to fit the window */
        scene.scaleMode = .AspectFill

        skView.presentScene(scene)
    }
}


text:
Q: Is it cheating to use least squares to obtain a prior for Bayesian regression? Say that I have the model $Y=AX + E$ where $Y,X \in \mathbb{R}^{n\times m}$ and that $A$ is an unknown $n \times n$ matrix and E is a matrix of observation noise. When I place an uninformed prior on the parameters in $A$, NUTS sampler (specifically in PyMC) tends to throw an error that the gradients vanish. When I placed an informed prior (for example, a solution given by least squares), I get no such issue. So I am wondering if this style of prior is considered "cheating" in any way?

A: Note that "a solution given by least squares" in itself is not a probability distribution and can't therefore be used as prior. I assume you mean to center the prior around the LS estimator (maybe using more information connected to it such as a variance estimator for setting further properties of the prior).
The aim of a Bayesian analysis is to make posterior probability statements about the parameters or future observations. These statements are meant to properly reflect existing uncertainty. Information to be used in the prior should be prior information, information available before observing the data. Bayes' Theorem will then combine the prior information with the information in the data, and the new information in the data will normally reduce the uncertainty that was present in the prior, as with "prior information plus data" we know more than from the prior, or from the data alone.
If you use the data themselves for setting the prior (which is what you propose), the data will be used twice; information in the prior that is in fact from the data will be treated as if it were prior information before using the data, and then, computing the posterior from prior+data, the data will reduce the prior uncertainty. Except that the "prior uncertainty" here isn't additional information but just information in the data themselves; and then, computing the posterior, the data will be used to "reduce its own uncertainty", which isn't possible.
So using the data themselves to set the prior will normally lead to an underestimation of uncertainty or "overconfidence" (too low variation in the posterior), as the information in the data is used twice instead of using additional information from other sources, which is what the prior is meant to encode.


text:
Q: Nginx Different Certificate Based on Client IP or Existence of X-Forwarded-For Header? So I have Nginx Proxy Manager setup to proxy a bunch of servers.  It has two certificates on it.  One is the Cloudflare Origin and the other is a letsencrypt.   Mostly all of my sites are internal only, thus using the letsencrypt is good.  But for 2 of them I use the cloudflare proxy and thus need to use the origin certificate.
I'm trying to also allow direct access if I'm local, but currently the proxy is giving me back the origin certificate.  Is it possible to assign ssl settings in nginx based on the source ip or the existence of the header?
Something like this
if (header exists or source IP != 10.0.0.0/24) {
SSL Certa
} else {
SSL Certb
}


text:
Q: Backbone Collection mutator to reference in template Is there a way using Backbone.js/Marionette to use mutators similar to how they're used in a Model, but on a Collection? For example:
In MyCollection.js:
export default Backbone.Collection.extend({
    model: MyModel,
    ...
    mutators: {
        foo: function() {
            if (this.models.length)
                return this.models[0].get('foo');
            return "default value";
        }
    }
})

Then in MyModel.js:
export default Backbone.Model.extend({
    mutators: {
        foo: function() {
            return "bar";
        }
    }
})

And in template.ejs:

<%= myCollection.foo %>

    <% for (var myModel of myCollection) { %>
        <%= myModel.foo %>
    <% } %>

I seem to be getting TypeError: Cannot read property 'foo' of undefined errors, so I'm wondering if this is possible or if there is an alternate method? I would like to avoid moving MyCollection.foo logic into templates but that seems to be the easiest method.

A: First of all, mutators is not part of backbone or marionette. It seems you are using Backbone.Mutators plugin. And it's supposed to be used with models rather than collections.
There are many problems with your code. First of all the following code is not valid
foo: {
        if (this.models.length)
            return this.models[0].get('foo');
        return "default value";
    }

Second you are trying to access properties from the constructors of collection and model.
You should create their instances with data and access model instances from collection instance's models property.

<%= myCollection.foo %>

  <% for (var myModel of myCollection.models) { %>
      <%= myModel.get("foo") %>
  <% } %>

I doubt if they work with collection since I don't see any examples with collection in the documentation.
Please read the documentation of the plugin and framework you're using and try to understand what you're doing...

A: It appears Collections are not supported by the Backbone.Mutators plugin. It seems the easiest alternative is to just add an Object to the serializeData method of a Marionette.View, i.e:
serializeData: function() {
    return { models: this.collection.models, foo: this.collection.foo().toJSON() };
}

Here Mutators are not even necessary, foo is just a function in MyCollection.

A: You need to have views to handle templates and render.
Marionette has a CollectionView api which is probably what you are looking for,
https://marionettejs.com/docs/master/marionette.collectionview.html#rendering-collectionviews
Quote from documentation:

The CollectionView will loop through all of the models in the
  specified collection, render each of them using a specified childView,
  then append the results of the child view's el to the collection
  view's el. By default the CollectionView will maintain a sorted
  collection's order in the DOM. This behavior can be disabled by
  specifying {sort: false} on initialize.


text:
Q: Force a class to implement a specific constructor Let's say I have the following class:
public class SomeClass<TSource>
{

     private Model _model;

     // ...

     public void SomeMethod()
     {
         // ...
         TSource instance = Activator.CreateInstance(typeof(TSource), _model);
         // ...
     }
}

And then I have this class:
public class OtherClass
{
     public OtherClass(Model model)
     {
         // ...
     }
}

If I do the following, everything's fine:
SomeClass<OtherClass> someClass = // ....
someClass.SomeMethod();

But what if OtherClass has a parameterless constructor, or any constructor different than the stated?
Everything will compile just fine, but when creating the instance a runtime exception will be raised.
Is there a way to enforce the use of a certain constructor on every class that will be used as a generic argument to SomeClass<> ? (Like a generic constraint)


text:
Q: About closure when using jQuery hover method? My code:
function Demo (){
  this.name = 'abc';
  this.age = 20;
}

var demo = {
  init : function(){
    $('#test').hover(this.stop, this.start);
  },

  start: function(){
    //here is the error
    alert(this.name);
  }

  stop: function(){
    alert(this.age); // 'this' does not mean the Demo object, but $('#test') object.
  }
}

Demo.prototype = demo;
Demo.prototype.constructor = Demo;

(new Demo).init();

When the hover event of $('#test') is triggered, the stop method is called. However, 'this' in the method does not point to the demo object, but the $('#test') object. So, the alert is undefined. I need to have access to the attributes in the Demo object. And the stop and start method will be reused in other place, so I don not like to write the whole method code into hover's argument.
How should I solve this problem?

A: The this in the start and stop methods don't necessarily point to the same this as in the init.  This is because they are callback functions.  If you want to refer to the same object context then try the following:
var demo = {
  init : function(){
    $('#test').hover(this.stop.bind(this), this.start.bind(this));
  },

  start: function(){
    //here is the error
    alert(this.name);
  }

  stop: function(){
    alert(this.age); // 'this' does not mean the Demo object, but $('#test') object.
  }
}

Using bind will pass the this context through to the callbacks.
MDN docs for bind are here.

A: JQuery uses apply behind the scenes to call the event callbacks, that's why the context changes.
To mitigate this, you can do one of two things:
Use bind
var demo = {
  init : function(){
    $('#test').hover(this.stop.bind(this), this.start.bind(this));
  },

  start: function(){
    alert(this.name);
  }

  stop: function(){
    alert(this.age);
  }
}

call the method directly
var demo = {
  init : function(){
    // Closure here
    var self = this;
    $('#test').hover(function() {
        self.stop();
    }, function() {
        self.start();
    });
  },

  start: function(){
    alert(this.name);
  }

  stop: function(){
    alert(this.age);
  }
}

A: A None JSON implementation that will allow you to set the variable self
function Demo(){
  this.name = 'abc';
  this.age = 20;
}

Demo.prototype = new (function(){
    var self = this;

    this.init = function(){
      $('#test').hover(self.stop, self.start);
    }

    this.start = function(){
      //here is the error
      alert(self.name);
    }

    this.stop = function(){
      alert(self.age); // 'this' does not mean the Demo object, but $('#test') object.
    }
  })();

(new Demo()).init()

EDIT:
I have updated to show what i was meaning without the use of var demo = {...} the point i was trying to make was not to use the Object Literal aka JSON style so you could support a variable inside the prototype


text:
Q: Include empty responses in form I am trying using HTML, Jquery, and Node.js to develop an online test for my students. Currently, when I submit the form, the server gets a json object (using body-parser) that includes only the fields that were answered. However, I also need to be able to see which ones were not answer. For example, if my student answers questions 1, 2, 3 but not 4, the server shows the following:
{Q1: a, Q2:b, Q3:c}
I want to get:
{Q1: a, Q2:b, Q3:c, Q4:''}
I tried looking online, however most posts explain how to get rid of the empty responses and not how to include them.
This is what I have right now

      <form id="Form1" action="/Form1" method="POST">

                 1.
                A </labe> <input type="radio" name="Q1" value="A">
                B </labe> <input type="radio" name="Q1" value="B">
                 C </labe> <input type="radio" name="Q1" value="C">
                 D </labe> <input type="radio" name="Q1" value="D">

                 2.
                 A </labe> <input type="radio" name="Q2" value="A">
                 B </labe> <input type="radio" name="Q2" value="B">
                 C </labe> <input type="radio" name="Q2" value="C">
                 D </labe> <input type="radio" name="Q2" value="D">

                 3.
                 A </labe> <input type="radio" name="Q3" value="A">
                 B </labe> <input type="radio" name="Q3" value="B">
                 C </labe> <input type="radio" name="Q3" value="C">
                 D </labe> <input type="radio" name="Q3" value="D">

                 4.
                 A </labe> <input type="radio" name="Q4" value="A">
                 B </labe> <input type="radio" name="Q4" value="B">
                 C </labe> <input type="radio" name="Q4" value="C">
                 D </labe> <input type="radio" name="Q4" value="D">

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

      </form>

and in the server I have,
app.post('/Form1', urlencodedParser, function(request,response){ console.log(request.body); })

A: You could add a hidden radio button for each question that is marked as checked:
<input type="radio" name="Q4" value="" style="display: none;" checked>


text:
Q: QMessageBox without Icon Normally, when creating a QMessageBox, the window icon will look like this:

But I want to have a QMessageBox without the  window/title bar icon, like this:

I did some research and saw that I have to use QMessageBox::NoIcon. I tried, but it did not really work out.
So what can I do to remove the QMessageBox icon?

A: QMessageBox::NoIcon is not for the title bar icon: it's for the big icon in your message box.
In order to remove the title bar icon, you have to set specific flags:
QMessageBox msgBox(QMessageBox::Question,
        "This is the title",
        "This is the text",
        QMessageBox::Yes | QMessageBox::No, this);

// set the flags you want: here is the case when you want to keep the close button
msgBox.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);

msgBox.exec();


text:
Q: Notation in Zee's quantum field theory I am reading Anthony Zee's Quantum Field Theory in a Nutshell(1st edition). On page 123, he does an integration by integrating by parts:

$$\begin{align}\int&\frac{d\omega}{2\pi}\log\left[\frac{\omega^2-\omega^2_k+i\epsilon}{\omega^2-\omega^{\prime2}_k+i\epsilon}\right]\cr
=&-2\int\frac{d\omega}{2\pi}\omega\left[\frac{\omega}{\omega^2-\omega^{2}_k+i\epsilon}-(\omega_k\to\omega^\prime_k)\right]\cr
=&-i2\omega_k^2(\frac{1}{-2\omega_k})-(\omega_k\to\omega^\prime_k)\cr
=&+i(\omega_k-\omega_k^\prime).\end{align}\tag{II.5.4}$$

I don't know what $-(\omega_k\to\omega^\prime_k)$ is and therefore I don't understand the procedure of the integration. Can someone explain it?

A: More generally, notations such as
$$f(x)\pm (x \rightarrow y) $$
or
$$f(x)\pm (x \leftrightarrow y) $$
indicate a replacement rules, i.e. they mean
$$f(x)\pm f(y). $$


text:
Q: resolving a javascript and database table logic situation When I query a database table, I get back values "yes" or "no" for records that represent whether an item is present or not (the item is the column name).  I want to create a string that represents the products that are available by name (rather than what I am doing now "kitchen table =" + kitchenTable;
I am thinking this can be solved (poorly) by a series of if statements setting variables to either the product name or to "" and then include all variables in the string
var kt;
if (kitchenTable == yes) kt = "kitchen table";
else kt = "";
if (kitchenCabinet == yes) kc = "kitchen cabinet";
else ka = "";

output = kt + ', ' + kc;

There are about 50 items that can be presented to the user, is there a more efficient way of accomplishing this task??  One option is to change how values are entered into the datbase table such that instead of yes, its the item name but this seems like a poorer way to resolve the issue

A: Of course you don't give all the details about how do you make query so that is an imaginary mockup of a function simulating query
var available = [];

var result = query("kitchen table");
result === "yes" && ( available.push("kitchen table") );

......
var output = available.join();

A: What you want is actually built into javascript itself.
I would say using an object literal will really simply your life in this situation by organizing your code and turning it into a more readable format.
I would also recommend turning your server data into true and false as this is a standardized way to communicated a Boolean and allows for the method below to work as it does:
// From server response
var results = {
                    kitchenCabinet: true,
                    kitchenTable: true
}

// Use this for your storage of all related items
var kitchenProps = {
                  kitchenCabinet: 'kitchen cabinet',
                  kitchenTable: 'kitchen table'
 }

// Reuse this function for each time your need a new category (masterBathroomProps...)
function getItemDataIfExists(results, hashTable){
    'use strict';

    var output = 'Your total is: ';

    for (var item in results) {
        if (!results.hasOwnProperty(item)) return;
        if (results[item]) output += 'A '+hashTable[item]+' ';
    }

    return output;
}

getItemDataIfExists(results, kitchenProps);

Explanation:
You loop through a result set of an object containing keys names and true false values. In the loop, if the keyname's value is  true, then use that keyname to access the properties (in this case a string of your choice. The "key" here is that the key names in each object must line up.
Here is a live demo:
http://codepen.io/nicholasabrams/pen/JXXbYz?editors=0010


text:
Q: Zend_Gdata_Calendar_EventEntry answers in German My problem is that all responses of Zend_Gdata_Calendar_EventEntry are sent to my application in German, I guess because it takes the server language automatically. I would like to know how to force GData's language?
This is a part of my application's code:
//on récupère le nom du service
$this->gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;

//on s'authentifie
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $this->gcal);
$client->setConfig(array('language' => 'en'));

//on crée un nouvel objet calendar
$this->gcal = new Zend_Gdata_Calendar($client);

If I print my GCal object, the language is set in English. I don't understand why Google answers in German!

A: I think Google may be doing something that we can do in ZF:

There are three locales which have a slightly different behaviour:
'browser' - Zend_Locale should work with the information which is
  provided by the user's Web browser. It is published by PHP in the
  global variable $_SERVER['HTTP_ACCEPT_LANGUAGE'].
If a user provides more than one locale within his browser,
  Zend_Locale will use the first found locale. If the user does not
  provide a locale or the script is being called from the command line
  the automatic locale 'environment' will automatically be used and
  returned.
'environment' - Zend_Locale should work with the information which is
  provided by the host server. It is published by PHP via the internal
  function setlocale().
If a environment provides more than one locale, Zend_Locale will use
  the first found locale. If the host does not provide a locale the
  automatic locale 'browser' will automatically be used and returned.
'auto' - Zend_Locale should automatically detect any locale which can
  be worked with. It will first search for a users locale and then, if
  not successful, search for the host locale.
If no locale can be detected, it will throw an exception and tell you
  that the automatic detection has been failed.

your server may be setting $_SERVER['HTTP_ACCEPT_LANGUAGE'] to DE, I know it's not much but at least you can check and maybe change it in app.


text:
Q: which version of rails should I use for a new project I have been working with rails 2.3.5. I am gonna start a new project on rails. Should i continue using the earlier version or should i hop on to rails > 3 ? If so which is the more stable version?

A: It is better to use rails 3.0.x version as these days lot of new plugins(like active_reload) are targeted only for 3.x version.
3.1.x have lot of cool features(like asset pipeline, saas integration, coffescript integration, etc), but its still a release candidate and I faced some issues while using it. I guess we have to wait for the stable 3.1.x release.
I have been using 3.0.7 for a while and found it to be very stable.
3.0.10 is recently released and you can easily upgrade to it from 3.0.7 any time you want in the future.
If you are stuck to 2.x version you will be missing cool features like mentioned here: http://net.tutsplus.com/tutorials/ruby/5-awesome-new-rails-3-features/

A: For a new project, I would use Rails 3.1 or for a bit more stability, 3.0.7. There are some noticeable differences compared to 2.3, but it will be supported for longer and most development of new gems and documentation are being written for Rails 3.

A: You should definitely NOT use 2.3 and earlier.
The Rails framework is improving at a steady pace and if there is a downside to that is that it can be a pain to upgrade from version to version, especially as regards to major version changes which introduce tons of backward incompatibilities.
Why then would you want to put yourself in the hole at the get go.
Another issue is how ready and mature is the ecosystem (ruby, popular gem packages, etc.). This leads you to consider whether you should start with 3.0.10 or 3.1 release candidate.
It turns out the great majority of gems working with Rails 3.0 is also working fine with Rails 3.1.
The little downside is that 3.1 is still in release candidate status but it's all but ready for final release and that should come within a matter of days or maximum a couple weeks (as of today Aug. 25, '11).
I would strongly recommend you start all new apps with 3.1. That's what I'm doing.


text:
Q: Cron expression for every 20 minutes in between 12:00 AM to 12:59 AM, only on Saturday I like to schedule an Azure WebJob for the following scenario:

Every 20 minutes in between 12:00 AM to 12:59 AM, only on Saturday.

i.e., I expect the web job to be run on 3 occurrences: 12:00 AM, 12:20 AM, and 12:40 AM on Saturday.
So, will the Cron Expression: 0 */20 0,1 * * 6 satisfy the scenario?
If not, please someone suggest the correct expression for the same.

A: The right cron should be 0 */20 0 * * Sat, if you set it with 0 */20 0,1 * * 6, it will also run at 1:00, 1:20 and 1:40.
More details refer to this doc: NCRONTAB expressions.


text:
Q: Vim command equivalent to TextMate's 'Command+T'/'Go to File'? I have the directory of a Rails app open in Vim and would like to 'jump' to a particular file through a Vim command.
In TextMate I would type 'Command+T' and then the target destination file name.
Is there a similar command in Vim?
Thanks.

A: I switched from CommandT to CtrlP. It a bit nicer overall than CommandT and is written in pure vim so it's easy to install (CommandT has ruby dependencies). Check it out here: http://kien.github.com/ctrlp.vim/

A: There is actually a plugin that emulates this function called Command-T. I use it and I'm very satisfied with it.

A: There's :e, as well as many plugins that emulate TextMate more closely. Here's one.

A: I use LustyExplorer as a supercharged alternative (file navigation + buffer navigation + buffer search) to Command-T (which I didn't like).
Also, yesterday I saw a "new" plugin on vim.org called Quicksilver. You might give them a try.

A: You can use : to access the command-prompt and then use the e command
:e <file name>[enter]


text:
Q: how to split the list into chunks of know size, then find an item? I am new to c# I have a list of strings list and a number pageSize, a pageNumber and a rowNumber. I want to split this list by the page size and create a list of list, then return the element at the given pageNumber and rowNumber. If the page number and row number is above the possible index level, return null. Both pageNumber and rowNumber are zero-based indexes.
Example:
list = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
pageSize = 3
pageNumber = 2
rowNumber = 1
Result:List = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
Result = 8.

But this code is throwing an OutOfRange exception:
public static int? GetItemInThePagedDataList(IEnumerable<int> list, int pageSize, int pageNumber, int rowNumber)
{
    var lists = list.Chop(pageSize);
    if (pageNumber >= lists.Count() || rowNumber >= lists.First().Count())
    {
        throw new ArgumentOutOfRangeException();
    }
    return lists.ElementAt(pageNumber).ElementAt(rowNumber);
}

A: Don't need to split list. Write a function like this and return element at index.
public static int? GetItemInThePagedDataList(IEnumerable list, int pageSize, int pageNumber, int rowNumber)
{
    int index = (pageSize * pageNumber) + rowNumber;
    return list.ElementAt(index);
}

A: This is a variant of Kemal's solution. This implementation will return null if the page number and row number are above the possible index level. I have also implemented it twice (once for IEnumerable, once for IList) so that performance is dramatically improved for List scenarios.
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static int? GetItemInThePagedDataList(IEnumerable<int> list, int pageSize, int pageNumber, int rowNumber)
    {
        var index = (pageSize * pageNumber) + rowNumber;
        var nullableList = list.Select(z => (int?) z);
        return index < 0 ? null : nullableList.ElementAtOrDefault(index);
    }

    public static int? GetItemInThePagedDataList(IList<int> list, int pageSize, int pageNumber, int rowNumber)
    {
        var index = (pageSize * pageNumber) + rowNumber;
        return (index >= list.Count || index < 0) ? (int?)null : list[index];
    }

    static void Main(string[] args)
    {
        var list = new List<int> {1, 2, 3, 4};
        IEnumerable<int> items = list;

        Console.WriteLine(GetItemInThePagedDataList(list, 2, 1, 1));
        Console.WriteLine(GetItemInThePagedDataList(items, 2, 1, 1));
        Console.WriteLine(GetItemInThePagedDataList(list, 2, 4, 1));
        Console.WriteLine(GetItemInThePagedDataList(items, 2, 4, 1));
        Console.WriteLine(GetItemInThePagedDataList(list, 2, -1, 1));
        Console.WriteLine(GetItemInThePagedDataList(items, 2, -1, 1));
    }
}

A: As mentioned you don't need to create the pages first. But I found this question because I had a similar question where I did have a need to chunk my list into smaller pieces. I'm going to go ahead and answer your exact question with my example so anyone else that finds this question and does need to literally chunk their list up will have a workable solution.
var pageSize = 250
var pages = list
    .Select((x, i) => new {Item = x, Index = i})
    .GroupBy(x => x.Index / pageSize)
    .Select(x => x.Select(y => y.Item));

The above example will split your list into a list of pages each with size 250.
So to answer the question given a list of lists already, you can take the above and do something like
return pages.ToList()[pageNumber].Skip(rowNumber).FirstOrDefault();


text:
Q: How do iterate the result of mysqli_fetch_array()? in the following code, the result contain several product and each have several column:
$db = connect_db();
$sql = "SELECT * FROM Products";
$result = $db->query($sql);
$ary = $result->fetch_array(MYSQLI_ASSOC);
foreach($ary as $key => $element){
  echo "key is $key, element is $element \n";
}

But the output only iterate each column of single product:
key is id, element is 1
key is productCode, element is S10_1678
key is productName, element is 1969 Harley Davidson Ultimate Chopper
key is productLineId, element is 5
key is productScale, element is 1:10
key is productVendor, element is Min Lin Diecast
key is productDescription, element is This replica features working kickstand, front suspension, gear-shift lever, footbrake lever, drive chain, wheels and steering. All parts are particularly delicate due to their precise scale and require special care and attention.
key is quantityInStock, element is 7933
key is buyPrice, element is 48.81
key is MSRP, element is 95.7

how can I get the 2-dimensional array that $array[0]['MSRP'] evaluate 95.7

A: $ary = $result->fetch_array(MYSQLI_ASSOC) only gets one record at a time which was the first record in your case, You will need to use a while
while($ary = $result->fetch_array(MYSQLI_ASSOC)) //fetching one record at a time until end of record
{

    foreach($ary as $key => $element){
      echo "key is $key, element is $element \n";
    }

}

A: I believe this will work:
while ($ary = $result->fetch_array(MYSQL_ASSOC){
  foreach($ary as $key => $element){
    echo "key is $key, element is $element \n";
  }
}

This means that while there are more records, it'll go ahead and put them in the array and print them...
This is based on the old mysql_fetch_assoc() and mysql_fetch_array().
Good luck.
if you want to achieve what you wanted, you'll simply need to do the following:
 while ($ary = $result->fetch_array(MYSQL_ASSOC){
      foreach($ary){
        $array[] = $ary;
      }
    }

now $array has the entire result set, and thus $array[0]['MSRP'] - will return the value you desire.

A: You need to iterate the mysql_fetch command,not the results of that command.
Eg example:
$db = connect_db();
$sql = "SELECT * FROM Products";
$result = $db->query($sql);

while($entry = mysql_fetch_assoc($result))
{
  // $entry is an array you with the data of this DB-entry, eg
  echo $entry['MSRP'];
}


text:
Q: Repeat a certain character from a list? (Python) I was wondering if there was a way to repeat certain characters from a list.
For instance:
characters = ['t' 'a' 'c' 'o']
print(characters)

That would print ['taco'].
How would I get it to print ['tacooo']?

A: If you want to repeat character n times in n index look at this example:
characters = ['t','a','c','o']
print(''.join(characters[0:3])+characters[3]*3)

Just multiply n with a single index or to this for multiple then join the items. Then concatenate with +.

A: I think you can try this way to solve your problem.
characters = ['t', 'a', 'c', 'o']

result = ""

n=3

for i in range(len(characters)):
  if(characters[i] != 'o'):
    result = result+characters[i]
  else:
    result = result + (characters[i]*n)

print([result]);


text:
Q: Javascript recursive search I'm having some trouble with a recursive search. I want to return the block the ID was found in.
This is my data:
{
"rows": [{
    "columns": [{
        "id": "iE1YMSahu",
        "rows": [{
            "columns": [{
                "id": "VJBjVrfP"
            }, {
                "id": "NJb1234A",
                "rows": [{
                    "columns": [{
                        "id": "VJBjVXXX"
                    }, {
                        "id": "NJb1234B"
                    }]
                }]
            }]
        }]
    }, {
        "id": "EJnASD-v",
        "rows": [{
            "columns": [{
                "id": "VJBjVYYY"
            }]
        }]
    }]
}]
}

It should be returning
    {
        "id": "EJnASD-v",
        "rows": [{
            "columns": [{
                "id": "VJBjVYYY"
            }]
        }]
    }

But instead it's returning false. Here's my code:
function findColumnWithId(obj, id){
    for(var i = 0; i < obj['rows'].length; i++){
        for(var j = 0; j < obj['rows'][i]['columns'].length; j++){
            if(obj['rows'][i]['columns'][j].id == id)
                return obj;

            if(obj['rows'][i]['columns'][j].hasOwnProperty('rows')){
                var result = findColumnWithId(obj['rows'][i]['columns'][j], id);

                if(typeof result !== false)
                    return result;
            }
        }
    }

    return false;
}

findColumnWithId(data, 'VJBjVYYY');

I'm really not sure what's going on. It doesn't seem to be iterating over the last part of the Json data. This code actually does work in 5 out of my 6 use cases, which makes it even more strange.
Any help would be appreciated.

A: Removing 'typeof' in this if statement fixes my code.
if(typeof result !== false)


text:
Q: Problems with referencing to tables A1, A2 etc in appendix(with IEEEtran class) I'm trying to refer to some tables in the appendix of my paper,
the following command have been used to number the tables as A1, A2 etc.:
\setcounter{table}{0}
\renewcommand{\thetable}{A\arabic{table}}

but when I use the \ref command for cross reference, It only shows table A, not Table A1 as I wanted, will someone help figure out why the reference goes wrong?
I'm using the IEEETran class, and whit the following code:
\appendix
\setcounter{table}{0}
\renewcommand{\thetable}{A\arabic{table}}

some text here and refer to Table \ref{tab:app-flexible}.

\begin{table}[!htbp]
\centering
\begin{threeparttable}
\label{tab:app-flexible}
\caption{Parameters balabala}
\begin{tabular}{cccc}
\toprule
table contents...
\bottomrule
\end{tabular}
\end{threeparttable}
\end{table}


text:
Q: Joins in Hibernate and its use What is join in HQL and where shall it be used?
Have gone through tutorial.Majorly three of them used as follows:
Inner Join
Left Outer Join
Right Outer Join

Read few tutorials yet unable to understand.

A: Join in HQL is same like the SQL joins. In SQL join is used to join two tables to return matching data. In HQL join is between Parent entity and the child entity (Usually on a ForeignKey of a parent primary key).
Person table
person_id | name | dob

Address table
address_id | address_line1 | state | zip | person_id

A SQL Join looks like
Select * from person p join address a on p.person_id = a.person_id and p.person_id = 10

This will return data like following if a person has more than one address
person_id | name | dob | address_id  | address_line1 | state | zip
----------------------------------------------------------------------
10          Jack  10/25  22            223 elk blvd    AZ      54444
10          Jack  10/25  244            223 NY blvd     TX      54344

A HQL join looks like
from Person p join p.address

and it returns Person entity with a list of addresses in it.
Person{
    List address = [ Address{ (this is Object)  }, Address{(This is object)}]

}


text:
Q: Not performed .bashrc I created the file $HOME/.bashrc (because it was not there), added some commands, and it does not run, that is not making all the settings that I made there.
If you just type these commands in the console it works.
(Hosting is not mine)

A: The problem is, bash won't read .bashrc if it is invoked as a login shell. (sometimes there's a system-wide workaround which hides this difference).
Add the following command in $HOME/.bash_profile:
. "$HOME/.bashrc"

A: Belongs on superuser, but since it's a fairly easy thing:
BASH config files aren't automatically loaded when they're created/modified - you'll have to re-open your BASH session for them to be loaded, or run source ~/.bashrc to load the contents manually.


text:
Q: How to configure Angular UI bootstrap directives globally How can I configure the bootstrap datepicker using uibDatepickerConfig globally? The documentation just says the following:

All settings can be provided as attributes in the uib-datepicker or globally configured through the uibDatepickerConfig.

In the source code, they are defined as constants:
.constant('uibDatepickerConfig', {
    formatDay: 'dd',
    formatMonth: 'MMMM',
    formatYear: 'yyyy',
    formatDayHeader: 'EEE',
    formatDayTitle: 'MMMM yyyy',
    formatMonthTitle: 'yyyy',
    datepickerMode: 'day',
    minMode: 'day',
    maxMode: 'year',
    showWeeks: true,
    startingDay: 0,
    yearRange: 20,
    minDate: null,
    maxDate: null,
    shortcutPropagation: false
})

The exact same issue was already discussed in this post but the solution seems to be outdated.

A: //where app is the module that depends on 'ui.bootstrap'
// probably your main app module

//for DatePicker options
app.config(['uibDatepickerConfig', function (uibDatepickerConfig) {
    uibDatepickerConfig.showWeeks = false;
}]);

//for DatePickerPopup options
app.config(['uibDatepickerPopupConfig', function (uibDatepickerPopupConfig) {
    uibDatepickerPopupConfig.closeText= 'Close';
    uibDatepickerPopupConfig.placement = 'auto bottom';
}]);