Ubuntu 10.10 apt-get

Question: Alright, I've been having this issue for a while now, and I've done a ton of googling for it but nothing has helped fix my issue yet. I've tried a bunch of things, some of them including, making sure my time is correctly set, and even trying different sources but nothing has worked.
Now, basically I'm trying to do ANYTHING with apt-get. Updates, installs, everything is extremely slow, it all hangs on [Waiting for Headers]. So I ran
sudo strace apt-get update

Now, this works for some mirrors, but others the script hangs and loops on this type of output
select(8, [5 6 7], [], NULL, {0, 500000}) = 0 (Timeout)
gettimeofday({1303320316, 668899}, NULL) = 0
rt_sigprocmask(SIG_BLOCK, [WINCH], [], 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
99% [Waiting for headers]) = 26aders]", 26
select(8, [5 6 7], [], NULL, {0, 500000}) = 0 (Timeout)
gettimeofday({1303320317, 170040}, NULL) = 0
rt_sigprocmask(SIG_BLOCK, [WINCH], [], 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
99% [Waiting for headers]) = 26aders]", 26
select(8, [5 6 7], [], NULL, {0, 500000}) = 0 (Timeout)
gettimeofday({1303320317, 671178}, NULL) = 0
rt_sigprocmask(SIG_BLOCK, [WINCH], [], 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
99% [Waiting for headers]) = 26aders]", 26
select(8, [5 6 7], [], NULL, {0, 500000}) = 0 (Timeout)
gettimeofday({1303320318, 172636}, NULL) = 0
rt_sigprocmask(SIG_BLOCK, [WINCH], [], 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
99% [Waiting for headers]) = 26aders]", 26

Any help on this would be appreciated.
EDIT: As requested, I've uploaded a copy of my tcpdump while I was attempting to run the apt-get update. Here is the link http://pastebin.com/NvbgNxxV
EDIT: Here is a pcap file of my tcpdump output. It appears there are some files that apt-get is trying to get like files in the directory ubuntu/dists/maverick-updates/main/i18n/ .. no idea where i18n comes from, but I couldn't retrieve them from browsing the repos either.
http://www.easy-share.com/1914849692/tcpdump-out.pcap
Comment: Your strace is nearly worthless for debugging.  A packet capture (tcpdump/wireshark) would be far more useful.  If I was to gaze into a magic 8-ball for your answer I think it would tell me that the delays are being caused by your system trying to reach an IPv6 address but failing.
Comment: Do you have any third party sources.list entries or repositories configured?  You may want to post a tcpdump which at least contains only the protocols that matter, yours is very noisy and I lost interest pretty quickly.  Try `tcpdump tcp port 80`.  Also if you could output a pcap file instead of text (with the -w option) and upload it somewhere, we can load the file into wireshark and follow tcp streams easily, etc.  `tcpdump -s 1500 -w myfile.pcap tcp port 80` should do the trick.
Comment: Alright, I've updated my question with a link to the tcpdump output. If IPv6 is the issue, how would I go about fixing that?
Comment: If IPv6 is the issue, then http://www.webupd8.org/2010/05/how-to-disable-ipv6-in-ubuntu-1004.html
Comment: Interesting, well I've updated my post with the pcap file. I've tried to examine it in wireshark and .. well you can read my up date.
Answer: It looks like you request too many files that don't exist and archive.ubuntu.com throws you in a black hole for your single HTTP session:
GET /ubuntu/dists/maverick/Release.gpg HTTP/1.1
HTTP/1.1 200 OK
GET /ubuntu/dists/maverick/main/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick/main/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick/multiverse/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick/multiverse/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick/restricted/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick/restricted/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick/universe/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick/universe/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-security/Release.gpg HTTP/1.1
HTTP/1.1 200 OK
GET /ubuntu/dists/maverick-security/main/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-security/main/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-security/multiverse/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-security/multiverse/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-security/restricted/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-security/restricted/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-updates/Release.gpg HTTP/1.1
HTTP/1.1 200 OK
GET /ubuntu/dists/maverick-updates/main/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-updates/main/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-updates/multiverse/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-updates/multiverse/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-updates/restricted/i18n/Translation-en.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick-updates/restricted/i18n/Translation-en_US.bz2 HTTP/1.1
HTTP/1.1 404 Not Found
GET /ubuntu/dists/maverick/Release HTTP/1.1

Now I'm not sure why there are no Translation files for en_US but I did find someone who said they resolved a similar issue by setting LANG to C prior to running apt.  Try this:
LANG=C apt-get update

Comment: Thanks for looking into this for me, unfortunately that did not seem to resolve my issue. Now, I will say that I disabled IPv6 and apt-get update is running a lot smoother, but I'm still having the same issues with installing new things. Also, it seems very sporadic. Sometimes I guess it finds a repo that works well, and things download right away, other times it hangs forever.

Ubuntu 10.10 apt-get


Yii2: dynamic model attributes

Question: I have table Lang:
  id | lang_name

Table2: Messages:
  id | message_code

Table3: Dictionary
  id | message_id | lang_id | translation

I want to bring to the gridview with languages. Format:
message_code | en_translation | ..._translation  |..._translation
As the number of languages is not known, i pass value of columns in array to gridview.
There is one problem: I need to pass the value of the language id to relation model. I do not know how.
    $searchModel = new langmessages_search();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    $columns=array();
    $columns[]=array('label'=>'message_code','attribute'=>'message_code');
    $languages=Lang::find()->all();
    foreach($languages as $language){
        $columns[]=array('label'=>$language->name,'attribute'=>'text');
        //'attribute'=>'text' ---> need to dynamically create the attribute or pass lang_id
    }

I hope you can help.
Comment: have you tried using this: https://github.com/2amigos/yii2-translateable-behavior , I also use it and it looks a lot easier than your solution
Comment: I use it here: https://github.com/infoweb-internet-solutions/yii2-cms
Comment: is your problem the same as this? http://stackoverflow.com/questions/35117307/yii2-activedataprovider-custom-template
Answer: public function actionSearch($name, $email)
{
    $model = DynamicModel::validateData(compact('name', 'email'), [
        [['name', 'email'], 'string', 'max' => 128],
        ['email', 'email'],
    ]);
    if ($model->hasErrors()) {
        // validation fails
    } else {
        // validation succeeds
    }
}

The above example shows how to validate $name and $email with the help of DynamicModel. The validateData() method creates an instance of DynamicModel, defines the attributes using the given data (name and email in this example), and then calls yii\base\Model::validate().
You can check the validation result by hasErrors(), like you do with a normal model. You may also access the dynamic attributes defined through the model instance, e.g., $model->name and $model->email.
Alternatively, you may use the following more "classic" syntax to perform ad-hoc data validation:
$model = new DynamicModel(compact('name', 'email'));
$model->addRule(['name', 'email'], 'string', ['max' => 128])
    ->addRule('email', 'email')
    ->validate();

http://www.yiiframework.com/doc-2.0/yii-base-dynamicmodel.html
Answer: Your search model could look like this:
class LangMessagesSearch extends Model
{

    public $id;
    public $messageCode;

    private $languages = [];

    public function __get($name)
    {
        if (isset($this->languages[$name])) {
            return $this->languages[$name];
        }

        return null;
    }

    public function __set($name, $value)
    {
        return $this->languages[$name] = $value;
    }

    public function getLanguageAttributes()
    {
        $languagesList = Lang::find()->all();

        $attributes = [];
        foreach ($languagesList as $lang) {
            $attributes[] = [
                'attribute' => $lang,
                'format' => 'raw',
                'headerOptions' => [
                    'title' => $lang,
                ],
                'content' => function($model, $key, $index) use ($lang) {
                    // you can do here something with $lang if you need so
                    $content = $model->{$lang};
                    return $content;
                }
            ];
        }

        return $attributes;
    }

    public function search($params)
    {
        // assume that getRecords() implemented here
        $records = $this->getRecords($params);

        $allModels = [];
        foreach ($records as $k => $v) {
            $model = new self;
            $model->id  = $records->id;
            $model->messageCode = $records->messageCode;

            $allModels[] = $model;
        }

        return $this->wrapIntoDataProvider($allModels);
    }

    private function wrapIntoDataProvider($data)
    {
        $provider = new \app\components\ArrayDataProvider(
            [
                'allModels' => $data,
                'pagination' => [
                    'pageSize' => 30,
                ],
            ]
        );

        return $provider;
    }
}

Finally display grid in the view:
// take just first model in the list
$_model = $dataProvider->allModels[0];

$attributes = array_merge(
    [['class' => 'yii\grid\SerialColumn']],
    [
        'id',
        'messageCode'
    ],
    $_model->getLanguageAttributes()
);

echo \yii\grid\GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => $attributes
]);

Yii2: dynamic model attributes


Why doesn't deepcopy of a Pandas DataFrame affect memory usage?

Question: I have this code:
import resource
from copy import deepcopy

import pandas as pd
import random

n=100000
df = pd.DataFrame({'x': [random.randint(1, 1000) for i in range(n)],
                   'y': [random.randint(1, 1000) for i in range(n)],
                   'z': [random.randint(1, 1000) for i in range(n)]
                   })
df2=deepcopy(df)
print 'memory peak: {kb} kb'.format(kb=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)

I expect to see different memory peak usages for this code with the line df2=deepcopy(df)
 and without it. But the memory shows exactly the same result.
Isn't deepcopy supposed to clone the object and therefore increase memory usage?
Answer: When calling copy.deepcopy on an object foo, its __dict__ is looked up for a __deepcopy__ method, that is called in turn.
In the case of a DataFrame instance, it extends the NDFrame class, whose __deepcopy__ method delegates the operation to NDFrame.copy.
Here's the implementation of NDFrame.__deepcopy__:
def __deepcopy__(self, memo=None):
    """
    Parameters
    ----------
    memo, default None
        Standard signature. Unused
    """
    if memo is None:
        memo = {}
    return self.copy(deep=True)

You can read NDFrame.copy's docstring here, but here's the main excerpt:
def copy(self, deep=True):
    """
    Make a copy of this object's indices and data.
    When ``deep=True`` (default), a new object will be created with a
    copy of the calling object's data and indices. Modifications to
    the data or indices of the copy will not be reflected in the
    original object (see notes below).
    (...)
    Notes
    -----
    When ``deep=True``, data is copied but actual Python objects
    will not be copied recursively, only the reference to the object.
    This is in contrast to `copy.deepcopy` in the Standard Library,
    which recursively copies object data (see examples below).

In your example, the data is Python lists, that are therefore not actually copied.
Comment: @9769953 I got it, it's some sort of copy on write. I cannot explain the exact mechanism, but the result of `deepcopy` is a shallow copy (which is necessary, because it's fast and it does not increase memory), and then, writing to that copy does increase the consumed memory. It's not visible with only one writing, and I cannot explain the pattern of this augmentation, but that's definitely something like that.
Comment: @InyoungKim As I understand it, the index is a deepcopy, but the data is not.
Comment: So the df2 is a shallow copy of df?
Comment: Looking at the bottom examples in the [Dataframe.copy() documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.copy.html), it appears that the data *is* copied, just not recursively. The list/array for each column is copied, but if an item (cell) inside the dataframe is a Python object, it is not further (recursively) copied (and I assume that integers, as here, are always copied). See the last example, using a Series with a nested list. So I would actually expect the two dataframes from the question here to be fully independent.
Comment: @9769953 Yeah, actually I'm trying to wrap my head around that... I still don't get why the RAM is not doubled (which I confirmed using different tools, so I don't think there's any error here). Plus, the deepcopy is super fast, which is definitely wrong. I admit the list *do* look uncorrelated, but there cannot be deep copied without the memory doubling and in no time
Comment: My current best guess is overallocation by Python for its lists. Substracting some base memory for the Python runtime, there is very little increase seen when df is copied to df2. Doing this, however, with NumPy arrays (because `numpy.random.randint` is also a lot faster ;-), does show a noticeable increase (albeit it not twice) after the copy.
Comment: it would be good if your explanation in last comment will appear in the answer


Can we prove $0<d(p,x)+d(F,x)$ for some $d$ when $p$ is outside the closed set $F$?

Question: Suppose

$D$ is a collection of metrics on a set $X$.
$\mathcal T$ is the (smallest) topology generated by metrics in $D$ .
$F\subseteq X$ is closed in $(X,\mathcal T)$.
$p\in X\setminus F$.

Is there any $d\in D$ so that the (so-called) function
$$h:X\to [0,1]$$
$$h(x)=\frac{d(p,x)}{d(p,x)+d(F,x)}$$
is well-defined?
Answer: If $x \neq p$ then $d(p,x)+d(F,x) \geq d(p,x) \neq 0$ for all $d \in D$, so it is equivalent to show that $d(p,F) \neq 0$ for some $d \in D$.
A basis for the topology $\mathcal{T}$ is $\left\{ \bigcap\limits_{d \in M} B_d(x_d,\epsilon) \mid M \subset D \ \text{finite}, x_d \in X, \epsilon >0 \right\}$. So, if $d(F,p)=0$ for every $d \in D$, every neighborhood of $p$ intersects $F$, hence $p \in F$ since $F$ is closed for $\mathcal{T}$.
Comment: I tried to modify your proof so that it works for pseudometrics too: If $d(p,x) \neq 0$ then $d(p,x)+d(F,x) \geq d(p,x) > 0$ for all $d \in D$, so it is equivalent to show that for each $q\in \{x\mid d(x,p)=0\}$, $d(q,F) \neq 0$ for some $d \in D$.

A basis for the topology $\mathcal{T}$ is $\left\{ \bigcap\limits_{d \in M} B_d(x_d,\epsilon) \mid M \subset D \ \text{finite}, x_d \in X, \epsilon >0 \right\}$. So, if $d(F,q)=0$ for every $d \in D$, every neighborhood of $p$ which is also a neighborhood of $q$ intersects $F$, hence $p \in F$ since $F$ is closed for $\mathcal{T}$. A contradiction.
Comment: thanks. It seems your proof doesn't work for pseudometrics because you used $d(p,x)\ne 0$.


variable_get with prefix

Question: It's there a chance to retrieve all key/value, stored in variable table, that have a prefix, using variable_get()?
e.g: variable_get("prefix_*")
Or I have to use db_select('variable')?
Answer: I'm afraid not, variable_get() is a very simple function that just returns an item in the global $conf array, there's no method for searching built in.
You could write your own variable_select() function though, and you wouldn't have to go into the database as the entire variable table is loaded into $conf at the start of the page build. It might go something like this:
function variable_select($prefix) {
  $found = array();

  global $conf;
  foreach ($conf as $key => $value) {
    if (strpos($key, $prefix) === 0) {
      $found[$key] = $value;
    }
  }

  return empty($found) ? FALSE : $found;
}

I'm sure that could be improved but it's a start. It's worth noting that this method might match elements from the settings.php file that aren't actually variables in the database as such.
For example, if your prefix is data, it's likely you'll see the $conf['databases'] variable from settings.php in your results. There wouldn't be a way around that without going directly into the db I don't think.
Comment: nice! This is great!

variable_get with prefix


ERR_SSL_VERSION_OR_CIPHER_MISMATCH on Ubuntu

Question: I'm running wordpress on a Digitalocean VPS with cloudflare installed. My ssl was working perfectly till a few days ago when a buch of clients informed me they received the following error when visiting the site (on chrome, it works on mozilla):

ERR_SSL_VERSION_OR_CIPHER_MISMATCH
A secure connection cannot be established because this site uses an
  unsupported protocol.

I've disabled sslv3 and sslv2  to no avail, and making changes to my cloudflare dash doesn't affect anything.
I've analyzed the site via ssl labs and everything is seemingly okay https://www.ssllabs.com/ssltest/analyze.html?d=saharacluster.com .
This error is very cryptic, you can see in the report that one simulated connection recreates the same error (via anndroid) however chrome seems to connect fine.
This has me very worried and I've disabled ssl on the site temporarily.
Answer: This is really hard to tackle here, but this could be some sort of anti-virus or firewall setting and/or a setting in the Chrome browser. CloudFlare hasn't really made any recent changes to our SSL that should cause a sudden uptick in SSL questions or concerns.
Comment: Its very frustrating but thanks :-) PS//I'm in a remote place sorry for the late reply


An isoperimetric problem

Question: How can I find a triangle which encloses the largest area with given (total) length using caculus of variation? I know the direct method but I can't find one using variational method.
Answer: Let the sides be of length
$$ (2x,2y,2L) $$
where $L$ is a constant and $x,y$ are variables.
Semi-perimeter constraint function is
$$ p=(x+y+L) $$
Square of largest area objective function is
$$ q=A^2=(-L+x+y)(L+x+y)(L-x+y)(L+x-y) $$
Apply Euler-Lagrange equation and simplify algebraically using symmetry in variables ($x,y),$
Area square $q$
$$-L^4 + 2 L^2 x^2 - x^4 + 2 L^2 y^2 + 2 x^2 y^2 - y^4$$
resulting in relation between partial derivatives
$$\dfrac{p_x}{p_y} =\dfrac{q_x}{q_y} \text{ i.e.,}$$
$$\frac{\frac{\partial p}{ \partial x}}{\frac{\partial p}{ \partial y}}=
\frac{\frac{\partial q}{ \partial x}}{\frac{\partial q}{ \partial y}}$$
$$\dfrac{4L^2-4x^3+4xy^2}{4L^2y+4x^2y-4y^3}=1$$
Simplifying, $(x-y)$ is found to be a factor. So
$$ x=y=L,$$
i.e., maximum area is enclosed for an equilateral triangle.

An isoperimetric problem


Automatically manage a git branch that depends on another local branch?

Question: Suppose I've got two local git branches I'm working on.
Branch 1 is branched off of "master", and branch 2 is branched off of branch 1 (and depends on it).
Both are works in progress, I'm not ready to push either of them yet.
While working on branch 2, I see a change I want to make, so I switch back to branch 1 and refactor it a bit, adding a new commit.
Now I want to go back to branch 2 and rebase it.
If I run git rebase branch_1 branch_2, I get a ton of conflicts, because branch_2's history currently includes the old branch_1 commits before the refactoring, and the new refactoring in branch_1 conflicts.
Let's assume for the moment that there are no actual conflicts. If I were to create a new branch 2b, and cherry-pick all of the commits unique to branch 2 in order, they'd patch cleanly.
Is there an easy way to rebase all of the commits unique to branch_2 onto the new branch_1?
Comment: Note: in simple cases, `git rebase branch_1 branch_2` will work - so assume that I amended a commit or did an interactive rebase to branch_1, that guarantees there will be a conflict.
Comment: Your rebase tries to rebase all the commits listed by `git log branch_1..branch_2`. Are those the same commits you are trying to cherry-pick? (Maybe you should add a small commit graph to make your situation a bit more clear.)
Answer: Your commits on branch2 are based on a unrefactored commit and then changes the unrefactored code. Now you try to rebase those changes on a refactored commit, but your changes still try to change the unrefactored lines of code which are no longer contained in your refactored code. - Sorry, this kind of rebase is just not possible.

Let's see if I got things right. This is your starting situation:
  master     branch_1     branch_2
    ↓           ↓           ↓
o---o---o---o---x---a---b---c

You add your refactoring:
              branch_1
                  ↓
  master          r       branch_2
    ↓            /          ↓
o---o---o---o---x---a---b---c

Now your rebase should do this:
              branch_1    branch_2
                  ↓           ↓
  master          r---a---b---c
    ↓            /
o---o---o---o---x

But commit a is changing lines of x which are no longer contained in r. Therefore the rebase should not be able to work without conflicts.
Even if you create a new branch a r and try to cherry-pick a you should run into exactly the same problem. - Please clarify your question if I understood something completely wrong.
Comment: No, you're misunderstanding. I specifically said that if you cherry-picked the commits that were part of branch_2, they'd patch cleanly on top of the refactored code.

Also, it looks like "git rebase --onto" does exactly what I want, I just haven't figured out how to turn it into a one-liner yet.
Comment: `git rebase branch_1 branch_2` should be exactly the same as `git rebase --onto branch_1 branch_1 branch_2`. The `branch_1 branch_2` specifies which commits to move. The `--onto branch_1` specifies where to move them to. But the situation above still remains.
Comment: This was my fault for asking a poor question. I made an attempt at a better question here: http://stackoverflow.com/questions/20834648/chain-of-local-git-branches
Answer: OK, if I know that branch_2 has 3 commits from when it diverged from branch_1, I can do this:
git rebase --onto branch_1 branch_2^^^ branch_2
Is that reasonable? Is there a shorthand way I can specify the point where branch_2 diverged? I tried branch_2@{u}, but that didn't work.


Colorbox video doesn't play

Question: We want to use Colorbox for some of the Youtube videos on our site.
When you click on the "Learn More" link the Colorbox pop-up comes up, but the video is missing, there is just a white box.
cresinsurance.com/product-finder-tool/non-mandatory-individual-real-estate/
On the above page, if you scroll down to the "Policy Details" section, you'll see a play button with the text "Learn More". this is supposed to be a colorbox popup that will play a Youtube video.
Not sure what we're missing.
Thank you in advance.
Answer: never mind... there was another plugin that was interfering with the Colorbox script. All fixed and working

Colorbox video doesn't play


list full string after split the string after comma asp.net C#

Question: I have a string of fruits apple and pear, i want to split this string after "," and display output as
apple
pear

I have tried to use below method but it will only display pear
string[] tokens = str.Split(',');
string last = tokens[tokens.Length-1];

Answer: Try using String#Replace, to simply replace all commas by newline:
string input = "apple,pear";
string output = input.Replace(',', '\n');
Console.WriteLine(input);
Console.WriteLine(output);

This prints:
apple,pear
apple
pear


facing issues with django forms

Question: i am facing some issue in django forms. Problem is even though i put this code "attrs={'class': 'form-control'}" but when ever go to site and inspect-element, html doesn't include this class
it shows this...
<input id="id_name" maxlength="100" name="name" type="text" required="">

as you can see it didn't render 'class':'form-control'
I might be doing something wrong please tell me how to solve this problem???
forms.py, view.py and .html file code is given below
forms.py
from django import forms
from .models import ContactUs

class ContactUsForm(forms.ModelForm):
    name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control'})),
    email = forms.EmailField(required=True),
    subject = forms.CharField(required=True),
    message = forms.CharField(
        required=True,
        widget=forms.Textarea(attrs={'class': 'form-control'})
    ),
    class Meta:
        model = ContactUs
        fields = ['name', 'email', 'subject', 'message']

contact.html

Contact Us

        <form method="POST" action="/contact/">{% csrf_token %}
            {% for fields in form %}

            {{ fields.label }}
            {{ fields }}

            {% endfor %}
            <input class="btn btn-primary" type="submit" value="Submit">
        </form>

views.py
from .forms import ContactUsForm
from django.shortcuts import render, redirect
from django.contrib import messages
from django.http import HttpResponseRedirect

def Contact(request):
    if request.method == 'POST':
        form = ContactUsForm(request.POST)
        if form.is_valid():
            model_instance = form.save()
            messages.add_message(request, messages.SUCCESS, 'YOUR FORM HAS BEEN SUBMITTED')
            return redirect('/contact/')
        else:
            return HttpResponseRedirect('/admin/')
    else:
        return render(request, 'core/contact.html', {'form': ContactUsForm()})

Answer: Just update your forms.py class like below then it will add form field attribute.
forms.py
class ContactUsForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ContactUsForm, self).__init__(*args, **kwargs)
        self.fields['description'].widget = forms.TextInput(attrs={'class': 'form-control'})
        self.fields['message'].widget = forms.Textarea(attrs={'class': 'form-control'})

    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(required=True)
    class Meta:
        model = ContactUs
        fields = ['name', 'email', 'subject', 'message']

Comment: is there something wrong with my previous forms.py, can please tell why my code wasn't working
Comment: https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#widget
This will help you to find out why your forms.py is not working.

facing issues with django forms


i5/OS PASE program not found or in use when CALLing QP2TERM

Question: i5/OS PASE program not found or in use. Path name is
  /QOpenSys/usr/bin/sleep.
I am getting this error on a system that had the PASE software installed recently. I need PASE for an application that is being ported to multiple systems, so I need to know how our admins can get around this issue. I did check this file for IFS locks using the API, and nothing came back. The listing of the folder shows some of these commands as SYMLNK, some as STMF. Any ideas?
Answer: Per the documentation, sleep is included as part of PASE.
Does the system have PASE installed?
GO LICPGM
10. Display installed licensed programs

Page down a few times, you should see
Licensed  Product
Program   Option   Description
5770SS1    33      Portable App Solutions Environment

As far as *STMF vs *SYMLNK
*STMF is stream file, an object that's just a unstructured "stream of bytes"; basically every object on the IFS (or a PC, Linux, Unix) file system.  As opposed to the structured objects in the QSYS.LIB file system.
*SYMLNK is symbolic link, aka "soft link".  The actual contents of the object aren't really in the directory.    If you use WRKOBJLNK DETAIL(*EXTENDED) you'll have an option 12=Work with links that you can use to see where the links point to.  For example:
                            Display Symbolic Link

Object link  . . . . . :   /QOpenSys/usr/bin/admin

Content of Link  . . . :   ../../QIBM/ProdData/OS400/PASE/bin/admin

Comment: It is installed. 5722SS1    33      Portable App Solutions Environment  ... I understand the difference between the two IFS data types, it was just very strange to have many of these commands point to another location. I would imagine this would be a local install, not something pointing to another location, or optical media (would that be possible?).
Comment: All of mine are SYMLNKs to `../../QIBM/ProdData/OS400/PASE/bin`  It's not strange.  AIX programs expect the programs to be in one place.  But for maintaining IBM i, IBM chooses to put them someplace else.
Comment: @Charles, thanks, but that still doesn't explain why I am seeing the error upon the call.
Comment: Seems like PASE isn't installed properly...try `CHKPRDOPT PRDID(5722SS1) RLS(*ALL) OPTION(22) `
Answer: I was able to check both options 22 and 33, and both of them are showing as installed properly.
CHKPRDOPT PRDID(5722SS1) OPTION(33)
Product 5722SS1 release V5R4M0 option 0033 load 2924 correctly installed. Product 5722SS1 release V5R4M0 option 0033 load 5111 correctly installed. No errors detected by CHKPRDOPT.
CHKPRDOPT PRDID(5722SS1) OPTION(22) No errors detected by CHKPRDOPT.


C# How to use Linq on an XmlAttributeCollection within another Linq statement?

Question: I have an XML element with subelements like so:
<Groups>
    <Group1 name="first" value="1" />
    <Group2 value="2" name="second" />
    <Group3 value="3" />
</Groups>

I'm using an already existing method MyMethod() to fetch the Groups element which returns an XmlNodeList object which I cast to an XmlNode. After that I want to use a Linq statement to fetch only those groups which have a name attribute in them and store those names in a list of strings.
In the code snippet below I'm trying to check if the first attribute's name of an XML node equals "name"but it is possible that the "name" attribute isn't always the first one. Could you please help me out here and tell me how to use another Linq statement on Attributes property below? Attributes property is of type XmlAttributeCollection.
List<string> result = MyMethod().Cast<XmlNode>()
    .Where(node => node.Attributes[0].Name == "name")
    .Select(node => node.Attributes[0].Value).ToList();

EDIT:
I managed to find a solution using the built in method GetNamedItem:
List<string> result = MyMethod().Cast<XmlNode>()
    .Where(node => node.Attributes?.GetNamedItem("name") != null)
    .Select(node => node.Attributes?.GetNamedItem("name").Value).ToList();

Comment: You can try something like this:
var groups = groups.Where(c => c.Elements().Count(b => b.Attribute("name") != null) > 0);
Missing only the condition on list of strings value.
Can you give me an example of list of string value?
Answer: What do you think about that:
List<string> result = MyMethod().Cast<XmlNode>()
    .SelectMany(node => node.Attributes).Where(a => a.Name == "name");

Should match your goal to got the object with the specific name, the full code become:
List<string> result = MyMethod().Cast<XmlNode>()
        .SelectMany(node => node.Attributes).Where(a => a.Name == "name")
        .Select(a=> a.Value).ToList();

Answer: Key method for your question is extension method .SelectMany which return flattened collection from collection of collections.
As alternative you can use LINQ to XML (sounds like right tool for the job ;))
var document = XDocument.Load("pathToXmlFile");

// Here you can use more complex logic of "MyMehthod"
var allGroups = document.Descendants("Groups");

var names = allGroups.SelectMany(groups => groups.Elements())
                     .Where(group => group.Attribute("name"))
                     .Where(attribute => attribute != null)
                     .Select(attribute => attribute.Value)
                     .ToList();

Comment: Thank you for your clarification. Unfortunately I cannot modify `MyMethod()` because it's used in several places. But I managed to find another solution using the `GetNamedItem("name")` built in method.


Can you add affiliate links to 'share' URLs?

Question: can anyone let me know if it is possible to add a dynamic URL to a Facebook share website link. So for example would I be able to add an affiliate tracking link to the share URL when a users elects to share one of the items from my store to their facebook page?
I would like to be able to reward users commission if someone see's the share link and then buys the product from my store.
Answer: When sharing a link on facebook, it will most likely output 4 things.

An image
The title of the webpage
The URL found after all redirects
A short description

The image and the bold title of your post will have the link you shared, but the URL mentioned in (3) will have a new URL.
With Facebook's sharer.php you can share any URL (urlencoded):
http://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fclkde.tradedoubler.com%2Fclick%3Fp%3D139965%26a%3D1820176%26g%3D18881802


Create a custom Link to a File-Field in Twig

Question: I'm trying to customize a download-link for a file-field in my entity.
In a similar setup, i was able to customize a link-field in the following way:
 Link

So, for the file-field, i tried something similar:
 Download

However, there is no such thing as a uri field available. I have a hard time figuring out which fields actually are available for me to use in the template. I found kint to be way too noisy, i had to restrict memory consumption and still have no clue which fields are usable.
Alternatively, i tried to create a custom template for the specific file field, called field--field-publication-file.html.twig. The debug info tells me that it is used for rendering.
I had a look at the field that my theme (bootstrap) normally uses and tried to mimick its behavior. Specifically, i wanted to use the field link, which is also used in the bootstrap version. However, this field is always empty when using my version.
What more could i try?
Answer: After more research, i found the answer by accident on this page. One can refer to the link by using:

  Download

The fields that were defined in the bootstrap theme don't seem to be accessible in a sub-theme of bootstrap. I'm sure I could have written a custom preprocessor to do the same thing, but this solution works for me and I don't have to write PHP code.
Comment: You can also use `node.field_publication_file.entity.url()`
Answer: You can do it either way, using the file_url available on twig template or you can use file_create_url($file_uri); in the preprocessor, so that your template can easily consume the processed output.
Code at preprocess layer, assuming node as the host entity.
function mymodule_preprocess_node($node) {
   if (!$node->your_file_field_machine_name->isEmpty()) {
     $file_entities = $node->get('your_file_field_machine_name')->referencedEntities();
     if(count($file_entities)) {
        foreach($file_entities as $file_entity) {
            $variables['file_renderable'][] = file_create_url($file_entity->getFileUri());
        }
     }
   }
}

Other way is what you mentioned, use file_url at your twig template.

  Download


@EnableFeignClients and @FeignClient fail on Autowiring 'FeignContext' NoSuchBeanException

Question: The microservice I'm writting needs to communicate to other microservices in our platform. On that attempt, the ideal solution for us is Spring Cloud Netflix Feign, implemeting a @FeignClient.
However, I'm facing the exception below when I try an @Autowired ReviewProvider:
Exception (cause)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.cloud.netflix.feign.FeignContext' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1093)
    at org.springframework.cloud.netflix.feign.FeignClientFactoryBean.getObject(FeignClientFactoryBean.java:155)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:168)

ReviewProvider.java
@FeignClient("http://metadata-reviews")
public interface ReviewProvider {

    @RequestMapping(path = "sessions", method = POST)
    ReviewSessionDTO createSession();

}

ReviewProvider.java
@RunWith(SpringRunner.class)
@ActiveProfiles(INTEGRATION)
@ContextConfiguration(classes = AppEntry.class)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@DataJpaTest
public class ReviewProviderTest {

    @Autowired
    private ReviewProvider provider;
    private Class<? extends ReviewProvider> providerClass;

    @Before
    public void setup() {
        providerClass = provider.getClass();
    }

    @Test
    public void classAnnotations() {
        assertTrue(providerClass.isAnnotationPresent(FeignClient.class));
        assertEquals("http://metadata-reviews", providerClass.getAnnotation(FeignClient.class).value());
    }

    @Test
    public void createSession() throws Exception {
        final Method method = providerClass.getDeclaredMethod("createSession");
        assertTrue(method.isAnnotationPresent(RequestMapping.class));

        final RequestMapping mapping = method.getAnnotation(RequestMapping.class);
        assertEquals("sessions", mapping.path());
        assertEquals(0, method.getParameters().toString());
    }
}

Comment: Have you ever tried to add `@EnableFeignClients` ?
Comment: Yes, it's in my entrypoint class. Without it, the error is different: it complains that there is no qualifying bean for my provider, not for the FeignContext.
Answer: Seems like there is not anything out there yet about the solution to this stuff...
Here is what I did to solve this:

Add this annotation to your test class:
@ImportAutoConfiguration({RibbonAutoConfiguration.class, FeignRibbonClientAutoConfiguration.class, FeignAutoConfiguration.class})

Try it, if it does not work, you might need the @EnableFeignClients annotation on your main program config
Comment: If you are not using Ribbon, then only this is needed: `@ImportAutoConfiguration({FeignAutoConfiguration.class})`
Comment: I rebuilt the service from scratch, so got no solution yet for this. And I had the EnableFeignClients on... So the problem is no more, but also no real solution for the problem. Thanks for the follow up, thought
Comment: I mean, really its going to be a help for someone else maybe... I figured the cause really has to do with some annotation (I don't know what yet...) that actually prevents the import of FeignClient auto-config. So I tried to import them. Sorry to hear that you have to rebuild everything.. [sad face] but this did fix my issue.
Comment: Spring Cloud Feign seems to be terribly documented and hard to test (since it does not allow one to use MockRestServiceServer). I'm rolling back on using it and moved on to Spring Cloud Ribbon which requires a little bit more coding, but feels much more reliable and is better documented. I will mark your answer as solution, because I have no grounds or interest in Spring Cloud Feign anymore. Thanks for the help!
Answer: Recommended approach is to slice application configuration, this means you need to remove  @EnableFeignClients from SpringBootApplication.
and add dedicated configuration class:
@Configuration
@EnableFeignClients
public class CloudConfiguration {

}

This is required, because all slices annotation (like @WebMvcTest) include default configuration from SpringBootApplication.
Reference:

https://github.com/spring-projects/spring-boot/issues/7270
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#test-auto-configuration
Comment: For me moving `@EnableFeignClients` from Application to dedicated `@Configuration`-annotated class gave app not working.
Comment: @ASten are you sure that your configuration is scanned under application start?
Comment: thanks for answering. I am using `@SpringBootApplication` and I saw there `@ComponentScan` annotation with exclude filters only. My `@Configuration`-annotated classes are included in app context (related classes found them injected). Does it show that configuration have been scanned?
Answer: I solved this problem just by @EnableAutoConfiguration annotation on my class
Comment: To clarify for future readers: `@EnableAutoConfiguration` should go on the `@Configuration` class
Comment: what class?????
Comment: on your main program config class
Answer: The only what you must to do:

add to your build file feign dependency, for example, for gradle

compile 'org.springframework.cloud:spring-cloud-starter-feign'

add @FeignClient to your interface
add @EnableFeignClients to any configuration or to class with annotation @SpringBootApplication
Answer: I also faced this issue I followed MariuszS answer. However had to figure out couple of things so putting here... we need to tell @SpringBootTest from where to pick up the configuration so it would be like this
@SpringBootTest
@ContextConfiguration(classes = { YourClientConfig.class })

Answer: I had to add base packages and configuration
@Configuration
@EnableFeignClients( basePackages = ["com.yourcompany.yourproject"])
internal open class FeignConfiguration


How can one prevent double encoding of html entities when they are allowed in the input

Question: How can I prevent double encoding of html entities, or fix them programmatically?
I am using the encode() function from the HTML::Entities perl module to encode HTML entities in user input. The problem here is that we also allow users to input HTML entities directly and these entities end up being double encoded.
For example, a user may enter:
Stackoverflow & Perl = Awesome…
This ends up being encoded to
Stackoverflow & Perl = Awesome&hellip;
This renders in the browser as
Stackoverflow & Perl = Awesome…
We want this to render as
Stackoverflow & Perl = Awesome...
Is there a way to prevent this double encoding? Or is there a module or snippet of code that can easily correct these double encoding issues?
Any help is greatly appreciated!
Comment: Must … not troll … about static type systems …
Comment: @jleedev => what does this have to do with static type systems?
Comment: Well, I hadn't quite read the whole question. Keeping your dirty user input separate from the sanitized output is related.
Answer: You can decode the string first:
my $input = from_user();

my $encoded = encode_entities( decode_entities $input );

Answer: There is an extremely simple way to avoid this:

Remove all the entities upon input (turn them into Unicode)
Encode into entities again at the stage of output.
Comment: Always. Always store data in a known format. Don't mix and match. Always decode (transform into a known format) on input. Always encode (transform into the necessary format for display or interaction) on output. Applies to HTML-entities just as much as it applies to Unicode.
Answer: Consider saving the call to encode() until you retrieve the value for display, rather than before you store it. So long as you are consistent in your retrieval mechanism, the extra data in your database probably isn't worth fretting over.
Edit
Re-reading your question I realize now my answer doesn't fully address the issue seeing as calling encode() later will still have the same results. Not knowing of an alternative myself, it may not be much help, but you may want to consider finding a more suitable method for encoding that will respect existing symbols.
Comment: I think a method that respects existing entities would be ideal. I know that the corresponding method to encode in PHP has a flag to prevent double encoding. Does such a method exist in Perl?


skip empty text nodes using selenium in python

Question: HTML:

            Type1
            This is Node1
                all Nodes

            Type2
            This is Node2

            Type3

Code:
applicationData = [td.get_attribute("textContent").split("\n")[0] for td in webBrowser.find_elements_by_xpath('//td[@class="wpsTableNrmRow"]')]
print(applicationData)

OUTPUT:
 ["This is Node1", "This is Node2", ""]

I am scraping data from the table and the empty text is also scraped. I don't want to scrape empty text.
I tried ('//td[normalize-space(@class="wpsTableNrmRow")]'),  ('//td[@class="wpsTableNrmRow"]')/*normalize-space() and (//td[@class="wpsTableNrmRow"]/*[.!=''])  but not working.
How can I do this?
Answer: You can apply conditional to list comprehensions which will apply the function to the variable if the variable pass the condition(s).
Like this:
[f(x) for x in sequence if condition]

Applied to your code:
applicationData = [td.get_attribute("textContent").split("\n")[0] for td in webBrowser.find_elements_by_xpath('//td[@class="wpsTableNrmRow"]') if td.get_attribute("textContent").strip() == ""]
print(applicationData)

Comment: https://stackoverflow.com/questions/66292406/how-to-skip-a-tag-while-scraping-data-using-selenium/66295902?noredirect=1#comment117216375_66295902
Answer: you can use loctor to ensure text is not empty:
//td[@class="wpsTableNrmRow" and text()!=" "]

So use:
applicationData = [td.get_attribute("textContent").split("\n")[
    0] for td in driver.find_elements_by_xpath('//td[@class="wpsTableNrmRow" and text()!=" " and text()!=""]')]
print(applicationData)

Comment: https://stackoverflow.com/questions/66292406/how-to-skip-a-tag-while-scraping-data-using-selenium/66295902?noredirect=1#comment117216375_66295902
Comment: did you try the answer ? please accept the answer if it helped
Comment: @user15069057 the comment on previous answer was for this or the other one . Please comment only one respective threads .
Comment: Link is for other one.
Answer: The translate function looks like it might work fine to solve your issue:
applicationData = [td.get_attribute("textContent").split("\n")[0] for td in webBrowser.find_elements_by_xpath('//td[@class="wpsTableNrmRow" and translate(text(), " ", "")]')]
print(applicationData)

Comment: https://stackoverflow.com/questions/66292406/how-to-skip-a-tag-while-scraping-data-using-selenium/66295902?noredirect=1#comment117216375_66295902


Erro no git: "remote: Repository not found. "

Question: Toda vez que eu tento executar o comando git push -u origin master, o Git gera um erro de repositório não encontrado.
Eu segui certinho o passo a passo que está escrito no GitHub. Abaixo está tudo o que eu fiz até mandar o push para vocês verem e tentarem me ajudar:

criei um repositório privado no GitHub sem o arquivo readme.md
criei uma pasta no meu computador
abri o Git nela
digitei os seguintes comandos:
echo "# test-git" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/usuario-do-git/nome-do-repositorio.git
git push -u origin master

Logo em seguida o seguinte erro é gerado:

remote: Repository not found.

Uma amiga minha seguiu esses passos e não obteve este erro, ao contrário, correu tudo certo para ela. Já tentei de tudo, excluí até a conta e criei de novo, e novamente repeti todos os passos.
O que estou fazendo de errado para ser lançado este erro ?
Comment: Teste em vez de "master" por "main"... acredito eu que  possa ser isso...   git push -u origin main
Answer: Primeiro verifique se o repositório remoto já está sendo identificado com o comando git remote -v. Se ele não estiver listado, vincule o repositório remoto ao seu repositório local com o comando git remote add origin email@example.com:leocomelli/curso-git.git.
Repare que na sua tentativa você não utiliza o trecho firstname.lastname@example.com:. Adicione este trecho na tentativa e veja se dá certo.


How do I find IIS web application dependencies using Powershell and webadministration on Server 2012?

Question: Wondering if someone can help with this.
I have a number of servers that host IIS 7.5 and IIS 8.5 web application of various types.  As these are production web applications and servers i can't install any software on the server so i must find a way to remotely interrogate the server to retrieve the windows feature dependencies per web application.
I am aware already the I can use msdeploy to get the dependencies but that means i need to install the msdeploy software on the server which I cant do.
Also I am aware that I can use the Get-OSFeature to remotely retrieve the Windows features that are installed on a particular server.  This also is not useful as i need to connect to the web application to get the dependencies of the application.
So can this be done using powershell and Get-WebConfiguration and if so can someone show me as i have so far only been able to get the installed features using this method also eg.
Get-WebConfiguration system.webServer/* 'IIS:\sites' -Recurse

Thanks
Answer: If you are happy with msdeploy, you can just use it without installing it.
Create a temporary folder on the server, find an existing installation on Web Deploy 3.5 and copy the files from:
C:\Program Files\IIS\Microsoft Web Deploy V3

You can skip all the language folders you don't need.
Navigate into your new directory as elevated admin and just use msdeploy.exe.
When done, just delete the folder.


Como verificar mais de um nivel de um objeto sem que o código fique visualmente feio?

Question: Tenho um objeto postCardImage ele é preenchido por um retorno que eu tenho na minha API, o problema é que preciso testar todo o objeto que retornou para entao atribui-lo.
Faço o teste assim:
postCardImage:
  post._embedded["wp:featuredmedia"] |
  post._embedded["wp:featuredmedia"][0] |
  post._embedded["wp:featuredmedia"][0].media_details |
  post._embedded["wp:featuredmedia"][0].media_details.sizes |
  post._embedded["wp:featuredmedia"][0].media_details.sizes.full |
  post._embedded["wp:featuredmedia"][0].media_details.sizes.full.source_url ? post._embedded["wp:featuredmedia"][0].media_details.sizes.full.source_url : ""

porem achei isso muito grande e feio, queria saber se nao teria um forma mais elegante de testar isso?
por exemplo:
 if(post._embedded["wp:featuredmedia"][0].media_details.sizes.full.source_url){
  console.log("objeto ok");
 }

Isso é um problema muito comum no meu dia a dia, porem ainda nao tive uma solução.
O que é preciso fazer para melhorar essa pergunta?
Comment: Porque os negativos?
Answer: Você pode criar uma função para isso:
function get(obj, path) {
    const attributes = path.split('.');

    for (let attribute of attributes) {
        if (!obj.hasOwnProperty(attribute)) {
            return null;
        }

        obj = obj[attribute];
    }

    return obj;
}

Ela basicamente percorre o caminho de atributos que você deseja e se algum deles não existir retorna null. Pontos fracos desta solução é que se o valor desejado for null você não conseguirá distinguir se retornou o valor corretamente ou se retornou null porque não encontrou o atributo; outro é que como é utilizado o caractere ponto como separador, nenhum dos atributos pode possuí-lo no nome (isso pode ser contornado alterando o separador para outro caractere).

function get(obj, path) {
    const attributes = path.split('.');

    for (let attribute of attributes) {
        if (!obj.hasOwnProperty(attribute)) {
            return null;
        }

        obj = obj[attribute];
    }

    return obj;
}

const obj = {
    _embedded: {
        "wp:featuredmedia": [
            {
                media_details: {
                    sizes: {
                        full: {
                            source_url: 'Conteudo'
                        }
                    }
                }
            }
        ]
    }
};

const existe = get(obj, '_embedded.wp:featuredmedia.0.media_details.sizes.full.source_url');
const naoExiste = get(obj, '_embedded.wp:featuredmedia.1.media_details.sizes.full.source_url');

console.log(existe, naoExiste);
Comment: Boa resposta. Outras ideias que me ocorreram foi o `?.` que está em Stage 1 nas sugestões do TC39. E outra seria ter um `try/catch` mas que não faz o código mais bonito e pode esconder outros erros... `+1`


Runner stays on first: tagged out for not trying to advance?

Question: The situation: a runner on first with 1 out. The batter hit a ground ball to first, but the runner at that base stayed there.
The fielder grabbed the ball, tagged first base, then tagged the runner still occupying the base.
Is he out because he never tried to advance?
Comment: No, as stated below, but the reverse, in which he tags the "runner" on 1st and then steps on first would result in a double play
Answer: In your scenario, the batter (who becomes a runner upon hitting the ground ball to first) is out and the runner originally on first is safe because the force play had been removed upon putting out the batter. This article asking about a similar circumstance and this question about a batter being put out while the runner stayed on first also alludes to such.

This is addressed under Rule 5.09(b)(6) in the 2016 MLB Rule Book.

Any runner is out when:

He or the next base is tagged before he
  touches the next base, after he has been forced to advance by reason
  of the batter becoming a runner. However, if a following runner is put
  out on a force play, the force is removed and the runner must be
  tagged to be put out. The force is removed as soon as the runner
  touches the base to which he is forced to advance, and if he
  overslides or overruns the base, the runner must be tagged to be put
  out.

The definition of "force play" and the example provided illustrate when the force is removed.

A FORCE PLAY is a play in which a runner legally loses his right
  to occupy a base by reason of the batter becoming a runner.
Example: Man on first, one out,
  ball hit sharply to first baseman who touches the bag and batter-runner
  is out. The force is removed at that moment and runner
  advancing to second must be tagged.

Note that the runner on 1st is forced to vacate his base, as addressed under Rule 5.06(a)(1):

A runner acquires the right to an unoccupied base when he touches it
  before he is out. He is then entitled to it until he is put out, or
  forced to vacate it for another runner legally entitled to that base.

When is another runner legally entitled to first base? When he hits a fair ball. This is addressed under Rule 5.05(a)(1):

The batter becomes a runner when:

He hits a fair ball
Comment: @PeterCooperJr. Yes. This would be a double play. Rule 5.09(b)(6) states "A runner is out when: He or the next base is tagged before he touches the next base, after he has been forced to advance by reason of the batter becoming a runner." This [answer](http://sports.stackexchange.com/a/3267) also states "Until the out at first is completed the runner standing on first has no rights to the base." Both answers reference both rules 5.06(a)(1) and 5.09(b)(6).
Comment: So if I'm reading it right isn't the runner on 1st forced to advance to 2nd
Comment: Yes. That's what rule 5.06(a)(1) states. The force is removed if the batter is put out before the runner.
Comment: So is the situation different if the fielder tags the runner still standing on 1st, and then tags the base?
Comment: I keep reading conflicting rules. Bottom line when the batter hits a ground ball in fair territory is the runner on 1st "forced" to advance
Comment: @tim "when the batter hits a ground ball in fair territory is the runner on 1st "forced" to advance"? Yes. That's what rule 5.06(a)(1) *explicitly* states. What may be considered "conflicting" is that your scenario puts out the batter first, removing the force on the runner, allowing him to remain at first.
Answer: The runner on 1st is safe. Making the 1st out out at 1st base removes the runner's obligation to vacate the base. The runner should have been tagged before touching the base.
This happened to the Red Sox in 2013.
"Had Napoli taken a step off the base to receive the throw from Pedroia, he could have tagged Jackson -- and Jackson would have been out just the same as if he'd been running to second base. Napoli then could have stepped on first base to force out Hunter."
http://www.providencejournal.com/article/20130623/SPORTS/306239987
Comment: Good quote (and good, concise, layman's statement) that explains the scenario the OP is asking about.


Using an attribute to update an object passed as a parameter

Question: I have done a bit with C# method attributes but I have not done something that covers this requirement, and I am not even sure it is possible but here goes.
Let say I have a class like..
public class MyObject
{
   public DateTime? TheTime {get;set;}
   public string AValue {get;set;}
}

And a function like this...
public void AddObject(MyObject mo)
{
   //Do Something
}

Now, when the object is passed AValue will be set, but TheTime will be null (as this needs to be set in the AddObject method). I can do this like...
public void AddObject(MyObject mo)
{
   mo.TheTime = DateTime.Now;
   //Do Something
}

But I don't like that, what I want is to create an attribute that will do the job for me. So ultimately, I want something like this
[AutoUpdate(Parameter = "mo")]
public void AddObject(MyObject mo)
{
   //Do Something
}

and the magic is done for me.
Any ideas on how to create an attribute to do this? A simple link would do, I can't seem to find what I am looking for at the minute
Comment: I am not sure I understand why you need the complicated attribute solution. Is there any reason why you can't just make the setter of AValue update the datetime field when it is set or something along those lines? Or indeed do stuff in the constructor of your object. I don't even see how your attribute would work without having the `mo.TheTime = DateTime.Now` line of code somewhere or is it a case of refactoring it out of many methods?
Comment: @Chris, No refactoring to be done. The layer that sets AValue should not be concerned with TheTime. It is the AddObject functions task to care about it. There are also a few other standard properties it needs to care about too. It cannot be done at contruction as this is again not the job of the function calling code. There is more than one common property that needs to be updated this way. I think for now I will add a helper function that does the update (as like the code would for my attribute) and then I can at least limit this to one function call at the start of AddObject
Answer: You can achieve this with a cross-cutting concerns library (AOP), which applies a decorator pattern around your method, allowing you to inject functionality via attributes. It's usually used for things like logging.
Take a look at Spring.Net or Castle Windsor.
A a quick example of decorator pattern to create your own implementation.
public class MyExtendedClass : IMyClass
{
    public MyExtendedClass(IMyClass myClass)
    {
        this.innerMyClass= myClass;
    }

    public void AddObject(MyObject mo)
    {
       // does mo have an attribute on AddObject
       // if so
       Type clsType = innerMyClass.GetType();
       MethodInfo mInfo = clsType.GetMethod("AddObject");
       if (Attribute.IsDefined(mInfo, typeof(AutoUpdateAttribute)))
       {
          mo.TheTime = DateTime.Now;
       }
       innerMyClass.AddObject(mo);
    }
}

Then use like this:
IMyClass myClass = new MyExtendedClass(new MyClass());
myClass.AddObject(mo);

Comment: Thanks for the links, and I will take a look, but I do not want to use any 3rd party apps for this. I would like to create this attribute myself
Comment: Creating the attribute is fine, but need need some engine behind it to invoke it. You can do this with a decorator yourself, which is all the more easier if you are using a IoC container.
Comment: OK, I think I see what you mean. I have used MVC ActionFilterAttributes before and I guess these are setup to do the "extra work" you speak of as they have some useful methods that can be overridden. We are actually using PostSharp for some other stuff and I guess this would work for what I need. Was hoping to be able to create myself though, so I think I will give it a go and see how I get on. Thanks for the information


How can I place an image on a Bootstrap navbar until it reaches the max height, then go under the navbar?

Question: Basically, I saw this fiddle in an answer to a similar question. In that example, I want the image to only have a 40px height but still be at full resolution, and the rest just goes "under" the navbar. The end result should look something like this:

How can I accomplish this?
code because of jsfiddle link

Answer: Just change the overflow to overflow: hidden
See this updated fiddle: http://jsfiddle.net/Hg4CA/1/
Basically overflow: hidden hides anything that is bigger than the bounding box.
You could also do overflow-y: hidden to just hide any vertical overflow.


How to Display popup block when user scrolls down to the bottom of node

Question: I am using drupal 7. I want to display a popup block for a user to share the node on social media, but i want this popup to appear as the user scrolls down to the bottom of the node. Any module(s) possible to achieve this?
I have tried the Popup and Popup On Load modules but none seems to achieve this objective.
Any help or suggestions appreciated. Thank you
Answer: You could do It without modules using some CSS and javascript.
You can create the block with the content you want to show, keep it hidden by CSS and, once the user scrolls down enough, trigger a js event that toggles the blok class to a visible one.
Here You can find how to trigger an event when scrolling to a certain point:
https://stackoverflow.com/questions/21561480/trigger-event-when-user-scroll-to-specific-element-with-jquery
Using the example code, you could use something like:
<code>$(window).scroll(function() {
   var hT = $('#scroll-to').offset().top,
       hH = $('#scroll-to').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
       $('#yourblock').toggleClass('visible');
   }
});
</code>


Using Rules after importing an item using Feeds to set a custom field value

Question: I need a bit of help with Feeds and Rules. I have a Feed Importer that uses XPATH to parse websites for Titles and creates nodes in a custom content type. I've added a field (Field_Source) to the content type. What I'd like to do is create a rule to copy the Feed URL value into the Field_Source. I have a new rule that acts on After importing Feed but I'm not able to get access to the fields in the Node.
If I change the Event to Before saving an item imported by Feeds, I can get access to the node:field_source but not the Feeds URL.
SOLVED: It was much easier than this: I just added a relationship in Views to the Feed Item and was able to use the source URL.
Answer: I'd recommend using Feeds Tamper. do do what you want...i.e. map the pertinent section from your source "Feed URL" to your 'field_source' and then use feeds tamper to shape it up as you like...
Comment: Rules should be a plugin for the Feeds module right. I'm not able to see this option under the Tamper section. I just downloaded Drupal a week ago and installed all new modules including Feeds module as well. Am I missing something?
Comment: Rules is separate module from Feeds tamper.
Comment: I mean apart from the normal Rules, I want to be able to map Drupal taxonomies to a feeded item and currently tamper feed does not have this ability. Only basic string manipulations. Nothing that will read taxonomies on-the-fly.


How To Upload Image From Media Library Programmatically?

Question: I enabled latest version of media module to upload images in wysiwyg. It is working fine. There is no problem. I want to upload images programmatically from media library.
  Below is my code.
function test_form_upload_form_alter(&$form, $form_state) {
 $form['settings']['apply_now_image'] = array(
  '#type' => 'media',
  '#title' => 'Image for apply now',
 );
 $form['#submit'][] = 'test_upload_form_submit';
}

function test_upload_form_submit(&$form, $form_state) {
    global $user;
    if (!empty($form_state['values']['apply_now_image'])) {
    $file = file_load($form_state['values']['apply_now_image']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    // Save.
    file_save($file);
    file_usage_add($file, 'user', 'user', $user->uid);
    $apply_now_image_path = file_create_url($file->uri);
    variable_set('rgit_apply_now_image', $apply_now_image_path);
    variable_set('rgit_apply_now_image1', $file->fid);
  }
}

But it didn't give correct answer. This is only work if the '#type' is managed_file'. It didn't work if the '#type' is media. Is any solutions there to upload images from media library.
Comment: You need to declare `$user` as global in the submit function? :

`file_usage_add($file, 'user', 'user', $user->uid);`
Answer: Not sure what you are trying to achieve here, but files uploaded via media are already permanent managed files once you get to the submit stage, I believe.
The value in the form_state array you need is $fid = $form_state['values']['apply_now_image']['fid']);
You can then use that in a file_load: $file = file_load($fid);
So your code becomes
$file = file_load($form_state['values']['apply_now_image']['fid']);
file_usage_add($file, 'user', 'user', $user->uid);
$apply_now_image_path = file_create_url($file->uri);
variable_set('rgit_apply_now_image', $apply_now_image_path);
variable_set('rgit_apply_now_image1', $file->fid);

Comment: You have described here how to upload image in drupal. I can understood this. But i want to know how to upload image using by '#type' => 'media'


New to servers, just recieved an intransa va expandr

Question: Intransa VA-EXPANDR 12 2 TB Disk array question.
I received this 12 disk array along with a dell poweredge 2850. I would like to set up a RAID but i'm having trouble understanding how to hook up to the 12 disk array. It has an output port on the back that takes a SAS SFF-8088 cable but the poweredge does not have a SAS port. The cable came with it is a SFF-8088 to SFF-8470 SAS cable.
Do i directly hook up the disk array to the poweredge? In that case would it be a raid controller with a SFF-8470 port that i would need to buy for the poweredge or a differn't type of card.
I've been looking this up for hours now, im lost. Thanks for any help.
Answer:
Do i directly hook up the disk array to the poweredge?

Yes

In that case would it be a raid controller with a SFF-8470 port that i
  would need to buy for the poweredge.

Yes


PHP base64_encode failed and script terminated with blank page?

Question: I have an existing php script using base64_encode that works fine and then when i move this script into a new server it doesn't work, the script will just terminate with a blank page.
I tried to catch exception
try
        {
            $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
        }
        catch(Exception $ex)
        {
            echo 'Message: ' . $ex->getMessage(); die;
        }

It still only shows a blank page. Any idea what caused this?
Answer: try
if(!function_exists('base64_encode')){
  echo 'base64_encode function not enabled';
}
if(!function_exists('mcrypt_encrypt')){
  echo 'mcrypt not enabled';
}

to check if those needed functions are enabled.
Comment: Ok mcript is not enabled. Thanks!


Exchange Automation Script

Question: I'm trying to write a powershell script for Exchange that will find the amount of emails a specific mailbox has received within a 1 month time frame and email those object totals to specific individuals. So Far I've Got:
$date = Get-Date -Format MM/dd/yyyy
$time = Get-Date -Format HH:mm:ss
$previousMonth =

PS C:\> Get-MessageTrackingLog -Recipients:mailbox1.org -start "02/01/2017 00:00:00" -end "$date $time" -EventId "Receive" -ResultSize unlimited | Measure-Object
PS C:\> Get-MessageTrackingLog -Recipients:mailbox2.org -start "02/01/2017 00:00:00" -end "$date $time" -EventId "Receive" -ResultSize unlimited | Measure-Object
PS C:\> Get-MessageTrackingLog -Recipients:mailbox3.org -start "02/01/2017 00:00:00" -end "$date $time" -EventId "Receive" -ResultSize unlimited | Measure-Object
PS C:\> Get-MessageTrackingLog -Recipients:mailbox4.org -start "02/01/2017 00:00:00" -end "$date $time" -EventId "Receive" -ResultSize unlimited | Measure-Object
ps c:\> Send-MailMessage  -SmtpServer "server" -To "recipient email<recipient email>" -From "Monthly Mailbox Totals <email address>" -Subject "Monthly Mailbox Item Count"  -Body ""

What I'm having trouble with is this: I can't quite figure out how to calculate the date range for the -start input to get the 1st of the previous month from the current date and time, and secondly I'm stuck on how to get the totals from this formatted into the body of the email that is sent. I want this script to run on the first of every month if that helps at all.
Any tips would be greatly appreciated thank you in advance.
Comment: I see 2-3 separate questions here. You should try to limit yourself to just one. There are date methods your could use to get dates in the past and even keep your current formatting logic. You are not even saving the results from your tracking log requests. Are you also asking how to automate this?
Answer: System.DateTime has a function AddX (Days,Hours,Minutes etc.). With these you can specify an exact timeframe. Then you just add up the returned value from Get-MessageTrackingLog and send the contents of your variable away.
$StartDate = (Get-Date).AddDays(-14) #Get the last 2 Weeks
$EndDate = Get-Date
$i = 0
$ += (Get-MessageTrackingLog -Recipients "RecipientA" -Start $StartDate -End $EndDate -EventId "Receive" -ResultSize unlimited | measure).Count
$ += (Get-MessageTrackingLog -Recipients "RecipientB" -Start $StartDate -End $EndDate -EventId "Receive" -ResultSize unlimited | measure).Count
Send-MailMessage -SmtpServer "server" -To "recipient" -From "sender" -Subject "Mailcount" -Body "Mail count for this month is $i"

If you need the flexibility to set timeframes yourself you can simply use the type accelerator to convert your datestring into DateTime
$StartDate = [DateTime]"3.10.17"

Comment: Awesome thank you so much! Using (Get-Date).AddDays(-14) is it able to be formatted? I need to have it MM/dd/yyyy HH:mm:ss would it be

(Get-Date).AddDays(-14) -Format  MM/dd/yyyy HH:mm:ss
Comment: You don't need to format it to use it in `Get-MessageTrackingLog`. It simply uses the current Date and Time and substracts 14 Days. If you want to format it for output purposes then you can do it like this: `(Get-Date).AddDays(-14).ToString("MM/dd/yyyy HH:mm:ss")`

Exchange Automation Script


Shell voices - what does it mean?

Question: I've tried to answer a question about voicings in Jazz. I was not sure if it was concerning a 4 part or unlimited part voicing.
Now I've seen that I've overlooked in the title of the question the term shell voicing. I haven't heard this term before and looking for clearing I couldn't find an explanation in wiki. I suppose it has to do with the fact that in a sequence of  ii-V7 or in a fifth-fall progression the 3rd e.g. Dm (=F) becomes the 7th of the next chord G7 and and the 7th of Dm (C) is leading half step down to 3rd of G(=B). Are these (often) chromatically leading tones  called shell voicings? Or what did I miss?
Comment: At the risk of sounding Anglo-centric, should our tags be in English?
Answer: The first time I read about shell voicings they were described as only root and seventh or root and third and Bud Powell was the pianist credited as the innovator.
Mark Levine calls them Bud Powell voicings, like this...

But, it seems other user shell to mean voicings that omit unessential tones like the fifth and/or root.
It seems that stride and shells are often presented together in some way. Levine does that. So does this book (Austin, An Approach to Jazz Piano)

I suppose it has to do with the fact that in a sequence of ii-V7 or in a fifth-fall progression the 3rd e.g. Dm (=F) becomes the 7th of the next chord G7...

That is smooth voice leading for descending fifth progressions, but I don't think shell voicing is used exclusively for that kind of progression.
This example from Levine...

...shows Bud Powell (shells) including a progression by step Bb7 A-7.
Comment: Would this mean the third and seventh are building the shell?
Comment: That seems a good way to state it: 'build the shell.' Personally, I think of it as "shell" mean "essential" chord tones. Omitting un-essential tones empties our the chord leaving only a 'shell.'
Answer: A shell voicing is a "barebones" voicing of a chord, usually with the root, 3rd and 7th. For instance:
Cmaj7 : C / E / B
F#7 : F# / A# / E
It's a good way for very bad pianists (like me) to give the basic flavour of a chord at the piano, so they can hesitantly pick out the melody with the other hand and hear how it all fits together.
Answer:
A shell voicing is a chord which contains only the root, third, and seventh. Players will often only use two notes, the root and third, or the root and seventh.

https://www.thejazzresource.com/shell_voicings.html
and this:
For the most part they are 2 note voicings. For each chord you play the root of the chord as your lowest note. The second note will be either the 3rd or 7th of the chord. And that's it.
It seems that by this voicing the bass is playing the circle of 5ths and the upper voice is dropping chromatically by half steps building the 3rd or the 7th from chord to chord.

Shell voices - what does it mean?


Underscore indexOf within a Collection

Question: I've been looking already around for the answer with no luck.
Basically I am reviewing again the Addy Osmani guide to Backbone, and it seems I can't get through this code here.
var people = new Backbone.Collection;

people.comparator = function(a, b) {
    return a.get('name') < b.get('name') ? -1 : 1;
};

var tom = new Backbone.Model({name: 'Tom'});
var rob = new Backbone.Model({name: 'Rob'});
var tim = new Backbone.Model({name: 'Tim'});

people.add(tom);
people.add(rob);
people.add(tim);

console.log(people.indexOf(rob) === 0); // true
console.log(people.indexOf(tim) === 1); // true
console.log(people.indexOf(tom) === 2); // true

I don't see how people.comparator can reorder the collection even though is not called anywhere, plus how comes that returning 1 or -1 can reorder it.
Or is it implicitly called once the Collection is created or indexOf is called on the Collection itself?
Answer: From the backbone documentation:

By default there is no comparator for a collection. If you define a
  comparator, it will be used to maintain the collection in sorted
  order. This means that as models are added, they are inserted at the
  correct index in collection.models.

So every time you call people.add(...) the collection uses the comparator that you have set with people.comparator = function(a, b) { ... } to insert the model in an ordered position.
Comment: Thanks so much for the heads up!I was in fact unsure about the comparator function as is not mentioned on that lecture.

Underscore indexOf within a Collection


Replace client switches with Netgear to match core or instead mix/match Cisco?

Question: We are looking for how we can have a more reliable, simpler network.  How can we keep out administrative burden low, and work smarter not harder when it comes to our infrastructure?
Background:
We are a tech company and pride ourselves on being agile and lean.  We are taking a step back to evaluate potential problem areas before they become problems.
The network administration role has passed through a few hands
We have a mix of Netgear and cisco switches
1 gb fiber internet connection
pfsense firewall
10 gbps network for servers
10 gbps network for some clients (creative)
vlans
We had one of our core switches (netgear fiber stack) fail and it took a while to troubleshoot it because problems were intermittent.
The vision:
everything is simplified as much as possible with easy data/troubleshooting so diagnosing a problem is easy and reliability and ease of administration is maximized.  If we could have everything in one pane, it would be nice.
I have a new consultant who has recommended changing out our client switches to Cisco catalyst.  The switches he wants to replace are older Cisco SG500 switches, with 2 being POE and 2 non-POE.
What we have:
2 Cisco SGE2010 for workstations
1 Cisco SGE500 POE for phones
1 Cisco SFE2010P POE for cameras
1 Netgear M5300 for trunks to client switches and for WAPs, PBX, etc
1 Netgear M7100 for 10 gbe clients and servers
2x Netgear M7300 (stack) 10 gbe for vlan routing
2x pfSense firewalls

Basically I'm looking for an outside opinion.  So far, the cisco switches have been working just fine.  Do I proactively change them?  Should I buy more Netgears and make a stack?  Bang for the buck, it seems like Netgear is the way to go.  What am I giving up by staying with Netgear?  Or do I just leave the current switches with a spare on hand in case one goes I just change it out?  The consultant is saying the Cisco switches have more reporting ability to integrate into 3rd party monitoring tools.
Comment: You should reword your question(s) so it's less of an opinion request and more of a comparison request, because based on your question, the answer depends on how much money you're willing to spend vs the quality of service you get from the equipment.
Answer: He is absolutely correct. Netgear switches are crummy and cheap with low manageability and tiny packet buffers. You're trading capex for opex.
Cisco SMB switches are essentially a small step up from Linksys.
Catalyst are pricier, but if you want your network to work and be manageable you need something in that class. For a tech company, a network is essential.
Comment: Agreed. Netgears are a sack of crap. I wasted a good couple of weeks last year trying to get Netgears to behave.  The cost of my time to the business would have paid for some decent switches.


What is the probability that the mean of N samples is lower than a limit when sample is normal distributed?

Question:
The time it takes a person to complete the crossword puzzle in the newspaper is known to be normally distributed, with a mean of 35 minutes, and with a standard deviation of 6 minutes.
Suppose that 9 people are selected at random, and each person completes a crossword puzzle. What is the probability that the average time to complete the puzzles is no more than 34 minutes?

Hi guys, I need some guidance in order to solve this problem.
My first step was to find the $\text P(x\le 34)$ that represents the probability that ONE person resolve the puzzle in less than 34 minutes.
I found it, it is equal to $0.4338$.
However, I have no idea what to do after this.
Comment: what are you defining $X$ by?
Answer: $0.4338$ is the probability that one person, selected at random, would take no more than $34$ minutes to complete the puzzle. You are interested in the probability that nine people, selected at random, would require a mean time of no more than $34$ minutes to complete the puzzle.
It seems that we should be considering the sampling distribution associated with a sample of nine from the given population for this problem.
Notice that even though the mean of the population is 35 minutes, the mean of a random sample of nine people depends on which nine people are in the sample.
Imagine we generate a new data set by repeatedly sampling nine people from the population and recording the mean of the sample each time.
It turns out that, by the central limit theorem, this new data set will have a normal distribution (for large samples, even if the original population is not normally distributed) with the same mean as the original population.
This new data set will further have a standard deviation $\sigma_{\bar x}$ (which we refer to as a standard error in the context of the original population) that is related to the standard deviation of the original population $\sigma$ and the sample size $n$ via:
$$\sigma_{\bar x}=\frac{\sigma}{\sqrt n}$$
(This makes sense because we would expect a larger sample to have a mean more similar to the population mean than a smaller sample would, on average, and notice that this boils down to $\sigma_{\bar x}=\sigma$ for a sample size of $n=1$, as expected. It is a result worth exploring in more detail, however, with simulations, for example.)
In any case, you are now interested in $\text P(X\le34)$ given that $X\sim \text N\left(35,\frac{6^2}{9}\right)$, or the probability that the sample mean is no more than $34$ given that it is normally distributed with mean $35$ (same as original population mean) and standard deviation $\frac 6 3 = 2$ (smaller than the standard deviation of the original population), that is, $0.3085$.


Elements of Fréchet on a regular are closed

Question: Define the Fréchet filter for a regular cardinal $\kappa$ in the following way:

$\mathcal{F}(\kappa) = \{X \subseteq \kappa \mid |\kappa - X| < \kappa\}$.

I am trying to show that if $X \in \mathcal{F}(\kappa)$, then X is (1) unbounded and (2) closed in $\kappa$.
I have shown (1) but I am struggling with (2) and would appreciate help.
For reference

If $\kappa$ is a limit ordinal, a subset $X \subseteq \kappa$ is closed in $\kappa$ if for any limit ordinal $\alpha \in \kappa$ holds: if $\alpha \cap X$ is unbounded in $\alpha$ (or equivalently $\sup\alpha \cap X = \alpha$), then $\alpha \in X$.
Comment: Why would this be true? Isn't e.g., $\omega_1\setminus\{\omega\}$ in $\mathcal F(\omega_1)$ but not closed in $\omega_1$?
Comment: Also, shouldn't it be $X\subseteq \kappa$ in the definition of $\mathcal F(\kappa)$?
Comment: @spaceisdarkgreen yes, $X \subseteq \kappa$ indeed, that was a mistake.
Answer: (2) is false. If $\kappa$ is any uncountable regular cardinal, just let $X = \kappa\setminus \{\alpha\}$ where $\alpha < \kappa$ is a limit ordinal. Then clearly $X\in \mathcal F(\kappa)$ and $X\cap \alpha=\alpha$ is unbounded in $\alpha$ and $\alpha\notin X,$ so $X$ is not closed.
Comment: Hm, thank you! Then there is a mistake in my notes.


Extract a table out of data frame in pandas based on a condition

Question: Here are the column names of the pandas dataframe
result.columns.values

['A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J']

When I try to filter out using
filtered = result[(result['A'] <result['C']<result['D']) and (result['F'] <result['G']<result['I']) ]

I get this ValueError

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What's going wrong?
How do I correct this
Answer: I believe you will need to structure like:
filtered = result[((result['A'] < result['C']) & (result['C'] < result['D'])) &
                  ((result['F'] < result['G']) & (result['G'] < result['I']))]

Example
import numpy as np

columns = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
np.random.seed(0)
result = pd.DataFrame(np.random.randint(0, 101, size=(100, 10)), columns=columns)
result.head()

filtered = result[((result['A'] < result['C']) & (result['C'] < result['D'])) &
                  ((result['F'] < result['G']) & (result['G'] < result['I']))]
filtered

[out]
     A   B   C   D   E  F   G   H   I   J
7   35  11  46  82  91  0  14  99  53  12
28  34  69  53  80  62  8  61   1  81  35


Entity reference item list with preview images?

Question: In a node type 'album' I have an entity reference field 'photo' that can be used to reference nodes of the type 'single_photo'. This works fine – using the module Entityreference view widget lets the editor choose nodes from a lst view with a preview image and optional additional fields:

The actual list of referenced nodes however does only show the node title:

I now would like to have a similar preview in the actual item list – or maybe even also use other fields of the referenced nodes. Is there a similar module or a combination of views and code or the like, that would provide such a functionality? Any pointers, suggestions, links would be appreciated.
Comment: There is a big problem - what would you want to see as "preview" of a node? If your nodes contains image field called preview, it might be doable. Rendering nodes to images on the fly is hardly feasible, it require some kind of browser engine available on the server. So how do you imagine your preview images uploaded / created?
Comment: I wouldn't want a 'real preview' of the actual node. Instead an option to add fields to the list (as Entityreference view widget provides it for the node selection) would be very helpful. So replacing the default item list with a custom list (view) is currently what I'm looking for – but of course I would also try any other option if there is any…
Answer: The Entity Browser module almost does exactly this (for Drupal 8). The module allows you to create a view display (it adds a new Entity Browser display type) to select items and it also allows you to, via a configuration on the referencing entity's Form Display screen, display a referenced entity's view mode on the edit screen.


Javascript Writing to PDF or Excel

Question: Hey Related to your answer on Can I write files with HTML5/JS?
How would I modify this for say Excel or PDF. I tried but was unable to get it to work. I get a corrupt file downloaded when I change MIME to application/pdf
I am trying to link it to data stored in localstorage which I have all in a variable.
My current code is:
<code>function setSaveFile(contents, file_name, mime_type) {

  var a = document.getElementById('save');
  mime_type = mime_type || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; // text/html, image/png, et c
  if (file_name) a.setAttribute('Log.xls', file_name);
  a.href = 'data:'+ mime_type +';base64,'+ btoa(contents || 'Description' + '   ' + 'Notes' + ' ' + 'Date\n\n' + pdftimeLog);
}
</code>
I want to be able to export it as a CSV with each of those headings: DATE, description, notes in different cells. I want it mobile friendly.Thanks
Comment: Can you post the code for what you have tried so far?
Answer: Excellent Options for CSV Everyone:
http://snapshotmedia.co.uk/blog/jspdf
Is it possible to use any HTML5 fanciness to export local storage to Excel?
http://css-tricks.com/localstorage-examples/
Local Storage manipulation and possible sending
Thanks!
Answer: For a file to be a valid pdf or excelfile their contents need to conform to the standard that defines the respective format, just changing mimetypes won't do much good.
For PDF there's a library jspdf that might work for you.
I haven't seen a solution for Excel yet, it will be a whole lot harder as the (xls) file format is quite complicated, for the time being it's probably preferable to generate the file on the server.
Comment: If you only need to open it as a spread sheet, you could also produce a *.csv file, a comma seperated value file.
Comment: If I opt for CSV how would it work. Currently I am storing data in localstorage. I want to make it so that this data can be exported and emailed by users and I suppose csv will do. The software is intended for mobile use thus, downloadify is not an option. Thanks
Answer: As an alternative to CSV, it's also possible to write an Excel file by writing HTML  to a file with a .xls extension.  Excel opens it up based on the extension.  Haven't yet explored how deeply it can paginate, format.

Javascript Writing to PDF or Excel


Why don't Asp.Net controls expose the same events as…?

Question:
User control receives same events as Page object and just like Page object also exposes Application, Session, Request and Response objects. I realize UserControl class and Page class both inherit from same TemplateControl class and for that reason share so many of same methods and events.
But then why don't Asp.Net controls such as TextBox, Label, GridView etc. also derive from same class as Page and UserControl classes  – in other words, why would it be a bad idea for controls such as TextBox to have same events ( Page_Load etc ) as UserControl and Page classes do?

Thank you
Answer: The single most probable reason for this would be to minimize the serialization size of auto-event-wireup. Everytime you add an event to a handler in WebForms, its persisted across page requests by serializing it into viewstate. By only exposing methods (which are called in tree fashion) that can be overrided, you save yourself from having to serialize those method calls.

Why don’t Asp.Net controls expose the same events as…?


Superlinearly converging infinite series with a closed form

Question:
Let $(x_n)_n$ converge to $L$. Then it converges to $L$ superlinearly if and only if
$$\lim_{n\to\infty}\frac{\ln |x_{n+1}-L|}{\ln |x_n-L|}\gt 1.$$

For example:
If $x_N=\sum_{n=0}^N \frac{1}{n!}$, then $\lim_{N\to\infty}x_N=e$ and $x_N=\frac{e\Gamma (N+1,1)}{\Gamma (N+1)}$, but
$\lim_{n\to\infty}\frac{\ln |x_{N+1}-L|}{\ln |x_N-L|}=1$,
so the convergence is not superlinear.
I observed that a lot of "popular" series with a closed form do not converge superlinearly. Does there exist a superlinearly converging infinite series with a closed form?
Answer: Why, many, but then $x_n$ won't be nice.
Say, $x_n$ is the n'th Newton's iteration for $\sqrt2\left(\text{that is, }x_1=1, x_{n+1}={x_n+2/x_n\over2}\right)$.
Now, Newton's method for any reasonably well-behaved function is known to have quadratic convergence, which basically means that the error on each step is about as small as the square of that on the previous step. In short, your limit for this sequence will be $2$.
On the other hand, we know that $x_n$ is A001601(n)/A051009(n) = A001333($2^n$)/A000129($2^n$), and the latter two sequences are defined by a simple linear recurrence (the same one, but with different starting conditions), so they must have a Binet-like closed form. So after all, $x_n$ does have an elementary closed form as well, albeit an ugly one.
That's an example for you.
Comment: Well, if $x_n$ has a closed form, then obviously $y_n$ does too. Also, $y_n$ converge to $0$, and their sum converges to $\sqrt2$.
Comment: This is not an infinite series.
Comment: Sure. It is a sequence, much like $x_n$ in your question. Well, then consider a series consisting of $y_n=x_{n+1}-x_n$.
Comment: What would $y_n$ converge to? Would that have a closed form?


Disabling mod_mime_magic module per directory

Question: I would like to be able to disable the Apache module mime_magic in a particular directory (and its children). I've searched around, and there seem to be special one-off flags you can set to disable some modules (PHP, deflate, etc), but nothing general (or specific to mime_magic.
Is there a way to disable mime_magic in one directory? There's a known issue with it causing issues serving BAM files with JBrowse, and the recommended workaround is to disable mime_magic.
Answer: The module (like all modules) is enabled server-wide.  The only available configuration directive is MimeMagicFile, which can be set at the server or virtual host level.  So if you wanted to disable it for a specific virtual host, I suppose you could set MimeMagicFile /dev/null in that vhost.  But there doesn't seem to be any way of disabling it for a specific directory.
Comment: Thanks, that was the conclusion I came to as well. `MimeMagicFile` seems to work.


positive definite on 1st quadrant

Question: A positive definite symmetric square $n$-matrix is $A$ is characterized by $z^TAz>0$ for all $z\in \mathbb{R}^n$. One can verify that $A>0$ by checking that all eigenvalues are positive.
Is there a name and/or characterization for a matrix which only satisfies $z^TAz>0$ for $z$ in a quadrant or convex hull e.g. $z\in \mathbb{R}^n_+ $?
Answer: The Term that you are looking for is copositivity.

positive definite on 1st quadrant


How to translate !title field is required

Question: I want to translate '!title field is required.'.
I can see it in 'admin/config/regional/translate/translate' but if I put a translation, it will override the name/label of each field.
So it is taking '!title field is required.' as one string. But I just want to translate 'field is required' and field names separately.
For example a Name and Email required in a form should display same translation but replacing !title with the name of the field.
How to do that.
Answer: To change the field name, you have to translate !name field is required. . To do this, follow these following steps :

Go to admin/config/regional/translate/translate.
Search for the string !name field is required in the String contains textfield.
In search result, change the string for all the languages.
And then save it.

I hope it works.


Como gerar um relatório PDF em Angular

Question: Olá, Gostaria de gerar relatórios em PDF usando o Angular consumindo dados do firebase.
É possível fazer relatórios de multiplas páginas a partir de HTML ou utilizando TypeScript? Por favor me ajudem
Answer: Existe uma lista de soluções, você necessitará estruturar o conteúdo e utilizar alguma dessa possibilidades.
https://www.npmjs.com/package/electron-pdf
https://www.npmjs.com/package/html5-to-pdf
https://www.npmjs.com/package/phantom-html2pdf
http://pdfmake.org/
Recomendo a leitura da documentação de cada um, assim poderá determinar qual a melhor solução, dado que as informações e estrutura do seu projeto não são divulgadas na pergunta. :)
Comment: Obrigado amigo, vou verificar cada uma delas!
Comment: caso não consiga chamar

Como gerar um relatório PDF em Angular


Many groups with a single large element and a lot of small ones - How to assess?

Question: I have a sample of 100 groups, each with 50 elements. All elements in each group are characterized with a single "size" value.
The sizes of all the elements in a group (with 50 elements) are normalized by dividing them with the size of the maximal element (in their group, regardless of the other 49). Hence I have 100 groups, each with at least one element at size 1 (which constitute the maximal element or elements) and the rest are smaller.
Observing the data (manually), I notice that in the majority of groups (96 of them) there is a characteristic distribution of sizes : there always exist either a single or two large element (larger than 0.85) and the rest of the sizes are smaller than 0.3.
Now, I wonder (and would appreciate suggestions :-) of what would be the right statistical tool to generalize this phenomenon and make claims on the probability that this is the prevailing distribution of elements within any group in the population.
Thanks!
Answer: Here are some ideas to start with :

Kullback–Leibler divergence allows to measure distances between probability distributions. Hence it is possible to measure a distance between the given distribution and any artificially generated other distribution(e.g. uniform).
Bootstrapping - will allow the assessment of different variables in the sample (e.g its variance).
Permutation analysis - Take all samples (100 X 50) and reshuffle (permute) them many times. Assess in what percentage of the re-sampled data does the phenomenon reoccur.