text:
Q: Delete user meta but only if found in array I created a SAVE button that saves a page's URL to the user meta in an array.  I'm trying to now create a REMOVE button but I'm finding that when delete_user_meta is used it deletes all entries in the array and the one equal to the current page.
I'm very new to all this so maybe this isn't the best way to go about this...any tips on how to just remove the part of the array that is equal to $currentpage?
<?php
$currentpage = home_url( add_query_arg( NULL, NULL ) ); //Get current page
$user_id = get_current_user_id(); //Get current user ID

if(!$user_id){
        wp_loginout();
} else {
if(isset($_POST["submit"])){
    $data["pluginlink"] = $_POST["pluginlink"];
    foreach ($data as $key => $value)
        {
        add_user_meta($user_id, $key, $currentpage);
        }//end for each
}//end else
}//end if user id
if(!$user_id){
        wp_loginout();
} else {
if(isset($_POST["Remove"])){
    $data["pluginlink"] = $_POST["pluginlink"];
    foreach ($data as $key => $value)
        {
        delete_user_meta($user_id, $key, $currentpage);
        }//end for each
}//end else
}//end if user id
$userdata = get_userdata($user_id);
$meta = get_user_meta($user_id);
$data["pluginlink"] = $meta["pluginlink"][0];
?>
<?php
if(in_array($currentpage,$meta["pluginlink"])) {
    echo "Page has already been saved";
    $savebutton = "display: none;";
    $deletebutton = "display: block;";
    } else {
        echo "page not saved yet";
        $savebutton = "display: block;";
        $deletebutton = "display: none;";
        }
?>
<div class="buttondisplay" style=" <?php echo $savebutton; ?> ">
<form method="post" enctype="multipart/form-data">

Current URL: <?php echo $currentpage; ?>
         <input type="submit" name="submit" value="Save" class="ui blue mini button">

</form>

<div class="deletebutton" style=" <?php echo $deletebutton; ?> ">
<form method="post" enctype="multipart/form-data">

Current URL: <?php echo $currentpage; ?>
         <input type="submit" name="Remove" value="Remove" class="ui blue mini button">

</form>

A: I figured it out...I had to change
$data["pluginlink"] = $meta["pluginlink"][0];

to
$data["pluginlink"] = $meta["pluginlink"];


text:
Q: How can I correctly format this JSON data from a backpack.tf API request? I'm attempting to use the backpack.tf API for a Discord Bot I'm developing. I'm currently attempting the UserInfo portion of it. Using my own Steam ID within the API URL results in this output
Essentially, having users, then the ID, and finally the actual information I'm trying to use. My code is as follows:
const Discord = require("discord.js");
const superagent = require("superagent");
const { apiKey } = require("../db/config.json");
module.exports = {
    run: async(client, message, args) => {
        if (!args[0]) return message.channel.send("Enter in a steam ID!")
        let id = args[0]
        console.log(id)
        let { body } = await superagent
            .get(`https://backpack.tf/api/users/info/v1?steamids=${id}&key=${apiKey}`);
        message.channel.send(
            new Discord.MessageEmbed()
            .setImage(body.users.id.avatar)
        );
        if (!{ body }) return message.channel.send("Check that ID again!");
    },
    aliases: ["bp"]
}

Most of this is just framework, but it's basically making a call to the API through superagent. When it returns, I attempt to use body.users.id.avatar to get the avatar of a a user. Instead of doing this, it outputs a UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'avatar' of undefined error. The API seems to give no errors when it's simply body.users.id, but adding another layer to it prompts it to break.
I'd want it to simply give me the result I'm asking for. Thanks.

A: It looks like you are trying to use a dynamic property name, body.users is an object with key values of actual ids with numbers, there won't be a direct .id property, as such body.users.id is undefined
the reason body.users.id doesn't give any errors is because its only undefined but you aren't trying to call a property on it, like you do when you call body.users.id.avatar
body.users.id.avatar => undefined.avatar
This should fix it:
body.users[id].avatar

An example of how this looks:
const id = "2324389";
const obj = {
  "2324389": 23,
  "1234678": 22,
  "id": 21
};

obj.id
// => 21

obj[id]
// => 23

/* obj[id] is the same as below */

obj["2324389"]
// => 23

Also: if (!{ body })
this line might give errors, either way it will never be false since its evaluating if the object is truthy which it is, regardless of the properties
If you were trying to error handle with this, it needs to be earlier in the code, and you need to use .catch instead, unless the API doesn't throw an error even if ID is invalid

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento 1 - Change Magento custom options date values Hello I am simply trying to find the array of defaults for the product custom-option date
my goal is to change the month from "01,02,03....12" to a string with the month name "Jan. , Feb. , Mar. - Dec."
I believe I found the date custom-option file in
app/code/core/Mage/Catalog/Model/Product/Option/Type/Date.php

and in there you see the 'month' array being called but I can't find the declaration file.
I am new to this stuff so pardon my ignorance if this is obvious or I am making it more convoluted.

A: The month select is generated in the method Mage_Catalog_Block_Product_View_Options_Type_Date::getDropDownsDateHtml by the line $monthsHtml = $this->_getSelectFromToHtml('month', 1, 12);.
You can change that to something that fits your needs.
or you can do an ugly thing and change the dropdown texts via some javascript after the page loads.

A: Go to

app\code\core\Mage\Catalog\Block\Product\View\Options\Type\Date.php

and add the below code into Date.php file.

Mage_Catalog_Block_Product_View_Options_Type_Date (its better to rewrite it in local)

protected function _getMonthSelectFromToHtml($name, $from, $to, $value = null)
{
        $options = array(
                array('value' => '', 'label' => '-')
        );
        for ($i = $from; $i <= $to; $i++) {
                $options[] = array('value' => $i, 'label' => Zend_Locale::getTranslation($i, 'Month', Mage::app()->getLocale()->getLocaleCode()));
        }
        return $this->_getHtmlSelect($name, $value)
                ->setOptions($options)
                ->getHtml();
}

then find out
$monthsHtml = $this->_getSelectFromToHtml('month', 1, 12);

and replace with below code:
$monthsHtml = $this->_getMonthSelectFromToHtml('month', 1, 12);

Hope this helps.


text:
Q: Waiting for a event to be fired in a function I have the following event & function:
    static void rViewer_DocumentLoaded(object sender, EventArgs e)
    {
        //Do something
    }

    static RadPdfViewer rViewer = new RadPdfViewer();
    static RadPrintDocument rpd = new RadPrintDocument();

    internal static bool PrintReportBlocking(string sFileName, REPORT_TYPE reportType)
    {
        try
        {

            rpd = new RadPrintDocument();
            rViewer = new RadPdfViewer();
            rViewer.LoadDocument(sFileName);
            rViewer.DocumentLoaded += rViewer_DocumentLoaded;

            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

My goal is to block in the function, until the event is fired.

A: You can use an AutoResetEvent:
static void rViewer_DocumentLoaded(object sender, EventArgs e)
{
    are.Set();
    //Do something
}

static RadPdfViewer rViewer = new RadPdfViewer();
static RadPrintDocument rpd = new RadPrintDocument();
static AutoResetEvent are = new AutoResetEvent(false);
internal static bool PrintReportBlocking(string sFileName, REPORT_TYPE reportType)
{
    try
    {

        rpd = new RadPrintDocument();
        rViewer = new RadPdfViewer();
        rViewer.DocumentLoaded += rViewer_DocumentLoaded;
        rViewer.LoadDocument(sFileName);
        are.WaitOne();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

A: You can use TaskCompletionSource to achieve this:
static RadPdfViewer rViewer = new RadPdfViewer();
static RadPrintDocument rpd = new RadPrintDocument();

internal static bool PrintReportBlocking(string sFileName, REPORT_TYPE reportType)
{
    var tcs = new TaskCompletionSource<object>();
    try
    {
        rpd = new RadPrintDocument();
        rViewer = new RadPdfViewer();
        rViewer.DocumentLoaded += () => tcs.SetResult(null);
        rViewer.LoadDocument(sFileName);

        // If you really want to block, but you should probably use async/await
        tcs.Task.Wait();

        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}


text:
Q: use apply() to execute array of setTimeouts with args I need to be able to build an array of anonymous functions that execute setTimeout with unique arguments per function.  The following code has already been proposed, and works, on SO, but it only deals with immediate execution of the setTimeout.  It does not explain how one can accumulate a collection of setTimeout functions to an array, with each setTimeout function having its own closure that defines a unique variable to be used in the execution of the setTimeout.
This is what exists already on SO:
var strings = [ "hello", "world" ];
for(var i=0;i<strings.length;i++) {
    setTimeout(
        (function(s) {
            return function() {
                alert(s);
            }
        })(strings[i]), 1000);
}

This is one of many permutations of what I have tried:
var strings = [ "hello", "world" ];
var func_array = [];
for (var i=0; i < strings.length; i++) {
    func_array.push(function() {
      setTimeout(
          (function(s) {
              return function() {
                  alert(s);
              }
          })(strings[i]), 1000);
    });
}

When apply() is called on func_array, the strings[i] value is the same for each call, i.e. the final member of the strings array.
Another attempt: here we make the function that gets pushed onto func_array self-executing in order to scope the strings[i] variable correctly.  However, apply() sees only 'undefined' since the function has already executed.
var strings = [ "hello", "world" ];
var func_array = [];
for (var i=0; i < strings.length; i++) {
    func_array.push(function(s) {
      setTimeout(
          (function(s) {
              return function() {
                  alert(s);
              }
          })(s), 1000);
    }(strings[i]));
}

Ideas?

A: Use Function.prototype.bind(). It becomes much simpler than it actually is.
var strings = [ "hello", "world" ];
var func_array = [];
for (var i=0; i < strings.length; i++) {
    var fn = function(string){
        return setTimeout(function(){ alert(string) } ,1000);
    };
    func_array.push(fn.bind(this, strings[i]));
}

A: This does what you want.

var strings = ["hello", "world"];
var func_array = [];
for (var i = 0; i < strings.length; i++) {
    (function (s) {
        var func = function () {
            alert("String is " + s);
        }

        var futureFunc = function () {
            setTimeout(func, 1000);
        }

        func_array.push(futureFunc);
    } (strings[i]));
}

func_array[0]()
func_array[1]()


text:
Q: To get data of authenticated user failure public void loadUserInformation() {

    final String uid = mAuth.getCurrentUser().getPhoneNumber();
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Users");
//        DatabaseReference uidRef = rootRef.child("ref").child(uid);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot: dataSnapshot.getChildren()){
                String name=postSnapshot.child("Name").getValue().toString();
//                    String email=postSnapshot.child("Email").getValue().toString();

                Name.setText(name);

//                    Email.setText(email);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getActivity(),"Error Loading UserDetails",Toast.LENGTH_LONG).show();
        }
    };
    rootRef.addListenerForSingleValueEvent(eventListener);
}

I know why I'm not getting the expected results, its because there's one more child after users. I'm not sure on how to access it, child(uid) gave me a NullPointerException. The present code gives me name of some random user. I want it to return name of the authenticated user i.e. myself
Database - http://ibb.co/iRnF77

A: Change the phone number to the userid:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();

So you will have this database:
Users
  userid
    Name: namehere
    Phone_Number: numberhere
    //etc

then you can simply retrieve the data of the current user:
 DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);

ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
            String name=dataSnapshot.child("Name").getValue().toString();

            Name.setText(name);

        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
};

You don't need the phone number to be the parent node since you already have it as an attribute Phone_Number: number_here, no need to write it twice.
Also getPhoneNumber() can be used if you did phone authentication:
https://firebase.google.com/docs/auth/android/phone-auth


text:
Q: Javascript generated calendar showing different in mozilla firefox and chrome I make custom calendar in javascript.
In firefox (1st image) calendar is properly generated, but in chrome (2nd image) is "upside-down".

There is JSFiddle example
Can anyone tell me why this happening?
In fiddle example I put button, and calendar is genereting, in some div, but in my webapp, instead in div (document.getElementById('cntcal').appendChild(tbl);), calendar is generated in form (document.form[0].appendChild(tbl);).
p.s. sorry for weak English, I hope you people will understand problem.

A: I tested now in Google Chrome Version 40.0.2214.115 and It is working great. What version of chrome you used for testing ?


text:
Q: Flash drive not writable after removing bootable OS I followed these instructions to wipe out the bootable OS from my flash drive. While the bootable was removed, the drive remained unwritable.  I then tried following these instructions to make it bootable but couldn't:
$ sudo mount -t ntfs-3g -o uid=$(id -u) /dev/sdb1 /mnt/
Mount is denied because the NTFS volume is already exclusively opened.
The volume may be already mounted, or another software may use it which
could be identified for example by the help of the 'fuser' command.

How can I make my flash drive writable again?

A: I've had this problem before, and its probably related to a partition table or MBR problem. Likely, one of those things wasn't configured right and now the hardware is denying you access.
Since you're working with NTFS, jump on a Windows machine and format it again and see if that fixes it.
Unless you know what you're doing, always use a graphical bootable USB writer, and always format USBs back to normal using OS utilities. DD is a low level bit-by-bit operation that can mess with the internal structure of the drive.


text:
Q: How to add two separate fields and aggregate over that sum I have some mock data for banks in elastic search which looks like this:
{
 "_index": "test_data",
 "_type": "test_type",
 "_id": "AVobMd1YHpQD-9cT3TmO",
 "_score": 1,
 "_source": {
 "bank_name": "BOFA",
 "transactions_sent": 79,
 "transactions_received": 27,
 }
}

I want to be able to add the values of transactions_sent and transactions_received to get total transactions and then have an aggregation over total transactions. I'm using elasticsearch 2.4.
I kind of figured out the solution using the script query.
"sum":
  "script":{
    "inline": "doc['transactions_sent'].value+doc['transactions_received'].value"
  }
}

The query time has increased by 8 times when I aggregated using the above query on the inline value compared to if I aggregate on either one of transaction_sent or transactions_received. Is there any other way to do it apart from the script query


text:
Q: Reading SCons environment settings from a file Multiple developers work on a project and each developer has different paths to dependencies, compiler etc. At the moment, all developers share a SConstruct file. When a new developer joins, a new Environment needs to be created, e.g.:
## environment: macbook
macbook = Environment()
### include
macbook.Append(CPPPATH = ["/usr/local/Cellar/gcc48/4.8.1/gcc/include/c++/4.8.", \
                          "/Users/cls/workspace/gtest/include", \
                          "/usr/local/Cellar/log4cxx/0.10.0/include"])

The environments are later selected via a command line parameter.
This works, but it is not very elegant, because the SConstruct file becomes longer with every developer. Is it possible to source the environment settings out to a settings file which needs to be modified per developer?

A: There are a few ways that you can solve this issue:

*

*You can have each developer specify environment variables and those environment variables
could be ready in by your SConscript using pythons os.environ method

*you can use scons Variables

*you can create a config file that is read in by the scons script.

For example since I see you are using gtest.  If you want to specify the path to gtest you could write a script similar to this.
# build variables
vars = Variables()

vars.Add(EnumVariable('VARIANT', 'Build variant', 'debug', allowed_values('debug', 'release'))
vars.Add(PathVariable('GTEST_DIR', 'path to gtest', os.environ.get('GTEST_PATH'), PathVariable.PathIsDir))

## environment: macbook
macbook = Environment(variables = vars)

Help(vars.GenerateHelpText(macbook))

### include
macbook.Append(CPPPATH = ["/usr/local/Cellar/gcc48/4.8.1/gcc/include/c++/4.8.", \
                      "$GTEST_PATH/include", \
                      "/usr/local/Cellar/log4cxx/0.10.0/include"])

Now when you run SCons you add the build variable
scons GTEST_PATH=/Users/cls/workspace/gtest VARIANT=release

if you don't want to type that in every time you run you can specify the environment variable GTEST_PATH or you can specify the SCONSFLAGS environment variable.
using the scons variables helps because when you type scons -h you will get a list of the current value of the variable and the help text.
If you would like you could create a config file that gets read in.  I would checkout this post:
Scons (Build System) Variables : load config file with custom/unknown values


text:
Q: Problems with resolving dependency node-fetch from github - fork still necessary? While trying to install build dependencies in a docker environment (no git), we got follwing error:
npm ERR! git clone --template=/home/node/.npm/_git-remotes/_templates --mirror git@github.com:archilogic-com/node-fetch.git /home/node/.npm/_git-remotes/git-github-com-archilogic-com-node-fetch-git-1-x-03653294: undefined

Problem seems the dependency archilogic-com/node-fetch#1.x here.
Ok. We should be able to handle this.
On the other hand, the question is wether the fork is still necessary.
Imho the reason for forking was overriding the array-buffer,
which is already done in original node-fetch.
Maybe i'm wrong but using the original would help us a lot.
Many thanks in advance

A: Indeed looks like an update would be a good idea!
A Pull request is welcome: https://github.com/archilogic-com/3dio-js
Thank you!


text:
Q: Text and HTML on One Line In Jade, is it possible to create a single line for both text and HTML? For example I want to do the following:

Format: mp3

and

Format: mp3

I know how to do it multi line ...
p Format:
    b #{string}

But, how is this possible on a single line?

A: The only way to achieve one-line would be to use following code:
p Format: #{string}

That will give something like:

Format: 2012

If you did not have Format: label, you could also use following approach:
p: b= string

or
p: b #{string}

Both would return following HTML:

2012

I hope that will help.


text:
Q: Solving $f(x) - g(x) = 0$, where $f(x) = e^x - 2.4$ and the graph of $g(x)$ is shown I'm doing a practice test for my EOC which is coming up soon and I can't solve this (and I don't know what to search). How can I solve this?
Solve $f(x) - g(x) = 0$, to the nearest tenth, where $f(x) = e^x - 2.4$ and $g(x)$ is shown.

A: First, you'll need to solve for g(x), which is a piecewise function.
$g(x)=$
\begin{array}{ll}
      ax^2+bx+c & x < 2 \\
      -1 & x\geq 2 \\
\end{array}
Plug $g(0)=0,g(2)=4$ into $g(x)=ax^2+bx+c$, we get $c=0,b=0,a=1$.
So, $g(x)=$
\begin{array}{ll}
      x^2 & x < 2 \\
      -1 & x\geq 2 \\
\end{array}
Next, solve for $f(x)=g(x)$.
When $x<2$, $f(x)=g(x) \Rightarrow$ $e^x-2.4=x^2$ $\Rightarrow e^x-x^2-2.4=0$
Here, I suggest using bisection method. Let $h(x)=e^x-x^2-2.4$. e is approximately 2.72
Choose upper bound $u=2$, lower bond $l=1$.
$h(1)=2.72-1-2.4=-0.68<0$ and $h(2)=2.72^2-2^2-2.4=0.9984>0$, so we set the middle point $m=(1+2)/2=1.5$
$h(1.5)=2.72^{1.5}-1.5^2-2.4=-0.164<0$, so we set the new lower bound $l=1.5$ and the new middle point $m=(1.5+2)/2=1.75$
$h(1.75)=2.72^{1.75}-1.75^2-2.4=0.298>0$, so we set the new upper bound $u=1.75$ and the new middle point $m=(1.5+1.75)/2=1.625$
So you get $x=1.6$
When $x\geq2$, $e^x-2.4=-1$. You can use the similar method, and get $x=0.3$, which contradicts with the assumption $x \geq 2$.
Therefore, the answer would be $x=1.6$.

A: You should graph $f(x) = \mathrm{e}^x - 2.4$ on the same axes.  Recall that $0 < \mathrm{e}^x \leq 1$ for $x \leq 0$, so $f$ and $g$ have no intersection for $x \leq 0$.  $\mathrm{e}^x$ continues to increase as we go to the right.  For $x = 1$, $\mathrm{e}^1 \approx 2.7$, so $f(1) \approx 0.3$ and we can see $g(1) = 1$, so $f$ has not increased enough to catch up with $g$.  $\mathrm{e}^2 - 2.4 \approx 5$, so $f$ has passed $g$.  Then it is a matter of searching between $1$ and $2$ for an interval like $[1.4,1.5]$ where $f$ is the lesser on the left and $g$ is the lesser on the right.  (Note:  "1.4" may not be the left endpoint, this is only an example of the sort of interval you want.)  I'd make a table of $f$ and $g$ values in that interval.  (It's relatively clear that $g$ is approximately $x^2$ on $[-2,2]$.)


text:
Q: reindent.py - Does not work from the command line I have problems with indentation in Python. So I downloaded reindent.py to correct the indentation errors.
I installed reindent.py using the following command-:
pip install reindent

But I running it from the command line shows me the following error-:
Traceback (most recent call last):
  File "/usr/local/bin/reindent", line 3, in <module>
    main()
  File "/usr/local/lib/python2.7/dist-packages/reindent.py", line 92, in main
    check(arg)
  File "/usr/local/lib/python2.7/dist-packages/reindent.py", line 118, in check
    if r.run():
  File "/usr/local/lib/python2.7/dist-packages/reindent.py", line 177, in run
    tokenize.tokenize(self.getline, self.tokeneater)
  File "/usr/lib/python2.7/tokenize.py", line 170, in tokenize
    tokenize_loop(readline, tokeneater)
  File "/usr/lib/python2.7/tokenize.py", line 176, in tokenize_loop
    for token_info in generate_tokens(readline):
  File "/usr/lib/python2.7/tokenize.py", line 357, in generate_tokens
    ("<tokenize>", lnum, pos, line))
  File "<tokenize>", line 127
    for w in transcript:
    ^
IndentationError: unindent does not match any outer indentation level

I am running it with the following command-:
reindent -n test1.py

I thought reindent was supposed to correct the errors not show me where they occurred.

A: reindent.py changes tabs to spaces and can make irregular indentation a uniform 4-spaces. It does not attempt to catch or fix IndentationErrors.
Consider this code which has an IndentationError:
def foo():
    print("Let's go")
  for i in range(2):   <-- IndentationError
      print('Peay')

It produces a similar error message to the one you are getting:
% reindent.py script.py
Traceback (most recent call last):
  ...
  File "/usr/lib/python2.7/tokenize.py", line 170, in tokenize
    tokenize_loop(readline, tokeneater)
  File "/usr/lib/python2.7/tokenize.py", line 176, in tokenize_loop
    for token_info in generate_tokens(readline):
  File "/usr/lib/python2.7/tokenize.py", line 357, in generate_tokens
    ("<tokenize>", lnum, pos, line))
  File "<tokenize>", line 9
    for i in range(2):
    ^
IndentationError: unindent does not match any outer indentation level

Both
def foo():
    print("Let's go")
    for i in range(2):
        print('Peay')

and
def foo():
    print("Let's go")
for i in range(2):
    print('Peay')

are valid ways to fix the code. reindent.py (or the tokenize module that it
relies on) does not attempt to guess which one the coder intended. Thus,
IndentationErrors are SyntaxErrors that at least sometimes require human
intervention to fix.


text:
Q: Article usage- A tablet, cellphone, [...] and a piece of paper IS/ARE on the table
What is the correct usage of article if different objects are stated in a group in a sentence. Particularly:

There IS/ARE a tablet, a cellphone, a ball pen, a reading glass, a cup of coffee and a piece of paper on the table.

Or

There IS/ARE a tablet, cellphone, ball pen, reading glass, cup of coffee and a piece of paper on the table.

Do I have to repeat them again and again or not? Especially if they are all singular.

A: Idiomatically, it's quite okay in such contexts to use the relaxed / colloquial contracted form There's with a plural referent, instead of There are (which many would find "awkward" to enunciate as contracted There're). Usually (but not always), this can be partially excused by the fact that the plurality of np's1 that follows is often thought of as a "single interrelated collection of things".
But this usage isn't idiomatically acceptable if you explicitly articulate the full singular verb form is, because that would draw unwanted attention to the verb plurality clash.

As regards repetition of the article in such a "list-type" context, this is purely a stylistic choice. Obviously including the article each time emphasises the "rhythm" of the list - so it feels more like a potentially endless series. Since we know what the first word of the next item will be, we "internally anticipate" it in advance, and tend to end up "half-counting" an extra item after the final thing actually specified. (See @KRyan's comment for other reasons to choose verbosity / brevity.)
Thus if you wanted to emphasise the number of things, you might choose to keep repeating a. But if you wanted to downplay the number of things (All I'm asking for is a name, address, and phone number), you might make the opposite choice.

1 Revisiting this post to improve some clumsy phrasing, I considered replacing np's there with fully-expanded noun phrases. But then realised I wouldn't really be happy with that unless I also changed the verb plurality to ...that follow are often thought of as...
Presumably that's because the plurality of np's is a short enough "preceding referent" for me to lump it all together as a singular verb subject. But it's too much trouble for me to remember that far back with the "extended" version, so I just stick with the immediately-preceding plural phrases.
Which just goes to show there's rules and there's rules - an oddball idiomatic usage usually meaning something like There are many rules, but they're often inconsistent, and not all of them always need to be honoured anyway. And certainly different native speakers will disagree on exactly how far it's "acceptable" for "correct" English to ignore strict logic when it comes to singular and plural verb forms.

A: FumbleFingers addresses the question of whether to conjugate the verb as singular or plural (answer: either is OK) so I'll take the other part:  It's fine to omit repeating articles in casual conversation.

There is a cellphone, tablet, pen, coffee cup, and some other things on the table.

I would include them in writing, unless I was transcribing dialogue.

A: If the items are a series of items in the singular, the verb is singular; there is.
There is a cellphone, tablet and ball point pen on the table. [single items, listed separately, singular verb, no need to repeat the determiner a]
If the items are a plural word, the verb is plural.
There are three objects on the table. [three objects=plural, plural verb]
For items listed separately, the verb is never plural:
There is a boy, a girl and a dog in the garden. [here, a is needed as the people and the dog are different categories, in my opinion]
There are three living beings in the garden.
contractions would be: there's (singular) or they're (plural).
Please note: one hears There's + plural noun, as in "There's people who live around here who think that drunk driving is a sport".
Use that type of construction at your own risk. It is marked as informal but can also sound quite unschooled. For example, "There's chickens in the yard."

A: Here is a famous post from the erstwhile  ELL stalwart and CamGEL champion F.E. on this exact topic over on English Language & Usage. You'll find that the normal rules do not apply in this situation—whether or not you use there's or there is... :

You should trust your ear. :)
This topic comes up a lot. Your question involves an existential construction.
It is safest (imo) to consider that the dummy pronoun "there" to be the grammatical subject. There are syntactic tests that can be used to sorta figure out the grammatical subject. Both the 1985 reference grammar by Quirk et al., A Comprehensive Grammar of the English Language, and the 2002 reference grammar by Huddleston and Pullum, The Cambridge Grammar of the English Language, basically consider that "there" is the grammatical subject.
In Quirk et al., page 1405, in section "The status of existential there as subject", it has:

18.46 The there of existential sentences differs from there as an introductory adverb in lacking stress, in carrying none of the locative meaning of the place-adjunct there, and in behaving in most ways like the subject of the clause, doubtless reflecting the structural dislocation from the basic clause types:
(i) It often determines concord, governing a singular form of the verb (cf 10.34 ff) even when the following 'notional subject' is plural:

*

*There's some people in the waiting room. < informal >

  occurs alongside:

*

*There are some people in the waiting room.

  (ii) It can act as subject in yes--no and tag questions:

*

*Is there any more soup?  There's nothing wrong, is there?

  (iii) It can act as subject in infinitive and -ing clauses:

*

*I don't want there to be any misunderstanding.

*He was disappointed at there being so little to do.

*There having been trouble over this in the past, I wanted to treat the matter cautiously.

Huddleston and Pullum et al. go into this in even more depth, in their section "Evidence that subject function is uniquely filled by dummy it and there" on pages 241-3.
I discussed the above because there are numerous, er, grammatical sources out there that get this wrong.
So, if we consider that the "there" is the subject, then that which is to the right-hand-side (RHS) of the BE verb is NOT the grammatical subject. That RHS has been called a whole bunch of stuff, such as "true subject", "notional subject", "displaced subject", etc. So, there is no such thing as a grammatical rule of subject-verb agreement between the BE verb and the RHS -- because the RHS is not the grammatical subject.
When teachers and "pop grammarians" and pedants say that there must be "subject-verb" agreement between the BE verb and the RHS, they are wrong. It is a bogus rule. It is like the other bogus rules like: "You must not start a sentence with a conjunction", "You must not split an infinitive", "You must not strand a preposition", "You must not use a relative 'that' to refer to a human", etc.
I've seen a lot of bad guidance, er, "rules" getting passed around as to the pseudo-subject/verb agreement. Here's one:

"there is" + < plural noun phrase > is indeed nonstandard . . . but "there's" + < plural noun phrase > should really be characterized, in current English, as merely informal/colloquial, rather than nonstandard.

Let's address this part:

"there is" + < plural noun phrase > is indeed nonstandard

for that evaluation is dubious, obviously. One can easily create contexts and examples to disprove that evaluation. For example, using the plural noun phrase "two hundred dollars",

*

*There is two hundred dollars in the man's wallet.
I'd think it'll be quite easy to create a context where that example sentence is acceptable.
Many instructors teach that the verb should be plural or singular depending on what that verb would be in a corresponding sentence where the RHS is the subject. Using the above example:

*

*Two hundred dollars is in the man's wallet.
is acceptable and grammatical. (That example uses a subject that is a measure phrase, and this issue is discussed in Huddleston and Pullum et al., CGEL, section "(a) Measure phrases", page 504.)
And so, an existential construction corresponding to that could then be:

*

*There is two hundred dollars in the man's wallet.
That sounds fine to me.
When the RHS includes a coordination of noun phrases, things can get confusing. Some usage guides and usage commentators prefer that the BE verb agree with the closest noun phrase for that situation. E.g.

*

*There is one fat dog and two skinny cats in the box.

*There are two skinny cats and one fat dog in the box.
and some still want the plural verb even when the first noun phrase is singular,

*

*There are one fat dog and two skinny cats in the box.
Of course, if this is dirtied up with an "or" or "nor" coordination, then existential constructions can really clash with their corresponding versions where the RHS is the subject. E.g.,

*

*(Either) One fat dog or two skinny cats are in the box that's sinking in the pond.

*There are (either) one fat dog or two skinny cats in the box that's sinking in the pond. (ugh)

*There is (either) one fat dog or two skinny cats in the box that's sinking in the pond.
.
Context is king. For instance,

I come from a small family. There is grandpa, mother, my big sister, me.

Hopefully an "editor" won't dare to mark that use of "There is" -- if the editor did, then that's an instant STET and a request for a different editor.
.
This post is getting long. Let me end it with this following bit of info.
A decent usage dictionary, such as MWDEU or MWCDEU, can provide useful info as to standard usage of the existential construction. In my Merriam-Webster's Concise Dictionary of English Usage, entry "there is, there are", on pages 732-3, this is the concluding paragraph:

Jespersen notes that the invariable singular occurs mostly in the colloquial style--speech and speechlike prose--and is generally avoided in the literary style. That observation accords with our evidence. In the more complex constructions, you are best guided by your own sense of what sounds right in the particular context to avoid awkwardness and maintain the smooth flow of the sentence.

Their last sentence basically says it pretty well, imo.

A: "There is a tablet and a cellphone" can be interpreted as "There is a table and there is a cellphone", in which case the singular verb is appropriate. However, it can also be interpreted as "A tablet and a cellphone exist", in which case a plural verb would be appropriate. If you don't repeat the article, I would lean towards plural verb. Note, however, that in this case you have "reading glass", which should be "reading glasses". This pushes it even further towards plural.


text:
Q: How to add optgroup to dropdown loop? I have a loop that displays a list of variables in a dropdown box (based on the filtered category).  I'd like to add in option groups (using subcategories) from my table.  How can I add this to part of my loop?
In the example below, the category is "countries" and subcategory is "continents".  I'd like the countries to be listed within the appropriate continent optgroup.
<select id="country">
  <option value="">Select</option>

 <?php
     $c_sth = $c_dbh->query ("SELECT category, subcategory, display, value
                              FROM constants WHERE category='Countries'
                              ORDER BY display");
     while ($row = $c_sth->fetch ()) {
       echo '<option value="'.$row['value'].'">'.$row['display'].</option>'."\n";
     }
 ?>

</select>

A: <?php
 $c_sth = $c_dbh->query ("SELECT category, subcategory, display, value
                          FROM constants WHERE category='Countries'
                          ORDER BY subcategory, display"); # group by category first
 $current_subcategory = "";
 while ($row = $c_sth->fetch ()) {
   if ($row["subcategory"] != $current_subcategory) { # if category has changed
       if ($current_subcategory != "") { # if there was already a category active
           echo "</optgroup>"; # close it
       }
       echo '<optgroup label="'.$row['subcategory'].'">'; # open a new group
       $current_subcategory = $row['subcategory'];
   }
   echo '<option value="'.$row['value'].'">'.$row['display'].</option>'."\n';
 }
 echo "</optgroup>"; # close the final group
?>

A: <select id="country">
  <option value="">Select</option>

 <?php
     $c_sth = $c_dbh->query ("SELECT category, subcategory, display, value
                              FROM constants WHERE category='Countries'
                              ORDER BY subcategory, display");

     $lastgroup = "";
     while ($row = $c_sth->fetch ()) {
       if ($lastgroup != $row['subcategory'])
         echo '<optgroup label="'.$row['subcategory'].'">\n';
       echo '<option value="'.$row['value'].'">'.$row['display'].'</option>\n';
       if ($lastgroup != $row['subcategory'])
         echo '</optgroup>\n';
       $lastgroup = $row['subcategory'];
     }
 ?>

</select>


text:
Q: request.security() results appears on next bar when using on lower timeframe I'm trying run a script that basically will use 2 timeframes - 1 hour and 1 day.
The way I'm doing this is running the script in 1 hour timeframe, and using the request.security() function to get the data from the 1 day timeframe.
While doing this,I've noticed a differences I can't figure out - while on the 1 day timeframe a condition is met on day X, the 1 hour timeframe will not show this condition is met on that day (which is what I expected it to be - on the last bar of the same day) but rather on the opening bar of the next day.
Any help will be most appreciated.
Here is an example code:
/@version=5
indicator("test", overlay=true)

sma20 = ta.sma(close, 20)
sma40 = ta.sma(close, 40)

crossover() =>
    ta.crossover(sma20, sma40)

cross1D = request.security(syminfo.tickerid, "D", crossover(), barmerge.gaps_on)
plotshape(cross1D)

// sma201D = request.security(syminfo.tickerid, "D", sma20, barmerge.gaps_on)
// sma401D = request.security(syminfo.tickerid, "D", sma40, barmerge.gaps_on)
// plot(sma201D)
// plot(sma401D)

Here are the results of the 1 day chart showing the condition is met on 29/7:

Here are the results of the 1 hour chart showing the condition is met on 1/8:


text:
Q: Is the observable pattern the right tool for this scenario? Suppose I have a Player that wants to build a Tower in the Board of a tabletop game.
My first approach to this would have been something like:
function onConfirm() {
  player.consumeResources();
  board.addTower();
}

Meaning this event knows the interfaces of player and board so it has some level of coupling.
If the observer pattern was used, with an observable buildTower, to which Board and Player were subscribed to in some initialization procedure:
class Player() {
  onTowerBuilt() {
    this.decreaseResources();
  }
}

class Board() {
  onTowerBuilt() {
    this.addTower();
  }
}

function onConfirm() {
  buildTower.notify();
}

Player and Board each receive the notification, and so the logic for discounting player resources is in the player, and for placing the tower in the board is in the board. Which from my persepective reduces coupling and increases cohesion.
So after this, some questions:

*

*Is this a good use of the observer pattern?

*If before this event, a check was needed for seeing whether the player has enough resources to build a tower, what would be a good way of doing so?

A: This seems a nice usage of the observer pattern, that in theory decouples somewhat the different kinds of objects. However, I'm not sure that the scenario is sufficient.
Suppose you'd have smallTower and bigTower with different resource needs. The orchestration according to your scenario would require to know what kind of tower is to be build, create the tower object (which knows the resources needed), then check if the player has enough resources and reserve them, then subscribe to the tower notifications, build the tower, and notify the elements that the tower is build to consume the reserved resources.
As you see there is in fact in this scenario an interdependence between tower, player and board before the notification can happen. Especially considering that the tower belongs to the player. It is moreover weird to have to subscribe to the new object before being sure that it can be build.
I'd therefore suggest to consider the use of the builder pattern (attention: the GoF builder, and not Bloch's builder pattern). The responsibility of that object would be to verify that the building is feasible and then orchestrate the interrelation between the board, the tower and the player.
This builder would  have to know the interface of the 3 objects and would depend on them. But the other objects would remain as loosely coupled as possible.
You could still foresee an observer for all the events happening to the tower that might be of interest (tower is finished, tower is damaged, tower is destroyed).

A: The observer pattern is definitely nice for decoupling the interface events from the game logic, but aside from that, you probably want a single listener that has enough information to process the event entirely. I would rather avoid events to be fired inside the game logic, they tend to obfuscate execution path.
Whether or not Player should handle that is unclear, but if checking the player's ressources is necessary, you would end up with something more similar to this:
function onConfirm() {
  requestTower.notify();
}
class Player() {
  onTowerRequest() {
    if this.hasResources(){
        this.decreaseResources();
        this.board.addTower();
    }
  }
}

There are design flaws with this. This imply the Player knows about Board. And if we think about it, this event processing has little reason to belong to an actual Player object, if Player is used as a game container for player-related information.
So I usually group the I/O handling to a higher level class, call it for example Game. It makes it logical for this class to have both Player and Board, and dispatch the processing to them accordingly.
function onConfirm() {
  requestTower.notify();
}
class Game() {
  onTowerRequest(){
      // May be necessary to solve who is requesting player here
      if player.hasResources(){
          player.decreaseResources();
          this.board.addTower();
      }
  }
}

A: This is a very good candidate for use of the observer pattern because it does decrease coupling in your case and, in my opinion, it makes the whole concept more elegant.
Your problem is very valid and, of course, it can occur in many different scenarios and across a large variety of domains. Domain events may, or may not, take place actually at the end. The most typical and elegant (again, in my opinion) solution to the problem of almost-occurring events comes after you realize that your event is not one event, actually, but two!
You need two distinct events happening sequentially in the same handler, and a structure that will be passed along with the events to all listeners, so they can communicate potential problems back to the handler. The first event signifies validation logic, and the second event is the actual domain event occurrence.
I am sorry for any potential mistakes, but I am not entirely sure what your language is. I hope the following can adequately illustrate the main idea:
class Player() {
    onBuildTowerRequested(eventFeedback) {
      if (!this.hasResources)
      {
          eventFeedback.Cancel();
      }
    }

    onBuildTowerConfirmed() {
        this.decreaseResources();
    }
}

class Board() {
    onBuildTowerRequested(eventFeedback) {
      //Anything to validate?
    }

    onBuildTowerConfirmed() {
      this.addTower();
    }
}

function onBuildTowerRequested(eventFeedback) {
    if (eventFeedback.cancel != true)
    {
        //Fire the confirmation event.
        //buildTower.notify() should NOT be simply called here because
        //listeners have additional logic to perform upon confirmation.
        //It is imperative that the onConfirmed event is fired as well.
    }
    //If the eventFeedback.cancel is true, do NOT fire the onConfirmed
    //event. This way, validation logic is decoupled from domain event
    //logic and you acquire wider flexibility in the range of scenarios
    //you can implement.
}

function onBuildTowerConfirmed() {
    //This will only be fired if no participating listener has cancelled the validation.
    buildTower.notify();
}

In common practice, events are paired as onValidating something and onValidated something, although you may name them as it best suits your domain and implemented logic. These two occur sequentially and one immediately after the other (onValidating and then onValidated, obviously), and all listeners have a chance to cancel the onValidating event through a passed feedback structure (the event-arguments). After the onValidating event, if nobody has requested a cancel (because of insufficient resources or for any other reason), the onValidated event is raised, to which all ensuing changes are declared to be inevitable, but have also been verified as possible to occur! On the other hand, if the onValidating event has its feedback structure's cancel variable set to true, the onValidated event will not be fired/raised.
Notice that, in my example above, I assumed the eventFeedback structure uses a method to notify cancel, rather than direct access to a bool cancel, for example. This is to avoid problems such as, for example, having the 2nd of 5 listeners change the cancel to true, and the 5th listener changing it to false again (by mistake), which would introduce a hard-to-find bug, let alone it would make the order of event "listenings" matter. If you employ this, make sure you use a method and make the cancel variable read-only, so if any of the listeners cancels, the cancel is irreversible. You can also make the listeners check for cancel first, so that they avoid performing expensive validation if the validation has already been canceled by a previous listener.


text:
Q: Drawing transparent rectangle wxWidgets how is it possible to draw a transparent rectangle using wxWidgets, I have tried using transparent brush, but it didn't work , also when I searched I found that anything uses wxDC wont support transparent , therefore I have to use wxGraphicsContext , but when I tried using it , I got this error wxGraphicsContext was not declared in this scope, and it's not going to work on all the platforms , so what is the best solution to draw transparent shapes/images and it will work on most of the platforms ?

A: As you have already discovered, you need to use wxGraphicsContext for any non-trivial transparency support (support for it in wxDC is limited to drawing bitmaps with alpha channel). Your build of wxWidgets might not include it as it's disabled by default when using MinGW because it doesn't always come with the necessary headers and libraries. If you have them -- and if you're using MinGW-w64 or TDM-GCC, chances are that you do -- you have to explicitly enable GDI+ support when building wxWidgets, either with a --enable-graphics_ctx option if you're using configure or by directly editing the wx/setup.h file and setting wxUSE_GRAPHICS_CONTEXT to 1 in it.


text:
Q: Laravel DOMPDF cannot read absolute image path I am using https://github.com/barryvdh/laravel-dompdf package for Laravel 5.5 to generate PDF. One thing I cannot get pass is rendering the image in PDF using Laravel's helper function such as e.g. asset(), url() etc. I am using the function because I have had bad experiences when the web is hosted not using the helper functions, or you might say using relative source for the image.
For example my code looks like this in template-pdf.blade.php :

It works. The image shows in the PDF. The image location is in the public folder of Laravel. But if I used

The image shows up in the browser, but once it's generated to PDF, it takes forever with an error message

PHP Fatal error: Maximum execution time of 60 seconds exceeded

That is only for 1 picture. No I don't want to increase my execution time settings.
What is the workaround?
Yes I do have enable_remote enabled


text:
Q: Increase search result snippet length on Google Search Applicance Is there a possibility to increase the length of the search result snippet (RES/R/S in XML output) provided by the GSA? Either per frontend or in general?

A: Default number of search results for a single query is 100. Maximum number is 1000.
You can increase the default number of search results by using the num query parameter.
Source: https://support.google.com/gsa/answer/4411411?hl=en#results
Update:
To Change the Snippet Length
By default the Search Appliance, for most languages, will return Snippets with the length of 160 characters. Some exceptions to this rule are CJK languages for which Snippets are by default 240 characters.
Search > Search Features > Query Settings > Snippets Generation > Snippet Length
Source: http://www.google.com/support/enterprise/static/gsa/docs/admin/72/admin_console_help/serve_query_expansion.html


text:
Q: Memory increase when returning to GameScene I'm creating a game which consists of multiple scenes but my problem is in the game scene. When I start playing and then return to the menu scene I notice that memory isn't being freed, instead memory keeps increasing every time I go to the game scene and eventually it crashes.
I've already tried to remove all actions and children from self in the function 'willMove', like this:
override func willMove(from view: SKView) {
        self.removeAllActions()
        self.removeAllChildren()
    }

But it did nothing.
I believe my problem is that I have too many animations made with SKActions like these:
//example 1, whiteCircle is an SKShapeNode
whiteCircle.run(.sequence([.scale(to: 1.5, duration: 0.5), .removeFromParent()]))

//example 2, SKAction.colorize doesn't work with SKLabels so I did this
        let color1 = SKAction.run {
            label.fontColor = .red
        }
        let color2 = SKAction.run {
            label.fontColor = .yellow
        }
        let color3 = SKAction.run {
            label.fontColor = .blue
        }
        let color4 = SKAction.run {
            label.fontColor = .green
        }

        let wait = SKAction.wait(forDuration: 0.2)

        label.run(SKAction.repeatForever(SKAction.sequence([color1, wait, color2, wait, color3, wait, color4, wait])))

//example 3, this is to refresh the label's text and change it's color
coinLabel.run(SKAction.sequence([.wait(forDuration: 3.25), .run {
            self.coinLabel.fontColor = .yellow
            self.coinLabel.text = "\(UserDefaults.standard.integer(forKey: "coins"))"
            }]))

I'm using lots of images as SKTextures too, used like this:
    coinIcon.texture = SKTexture(image: UIImage(named: "coinImage")!)

My variables are all declared like this in the GameScene class:
    var ground = SKSpriteNode()
    var ceiling = SKSpriteNode()
    var character = SKSpriteNode()
    var scoreLabel = SKLabelNode()
    var coinLabel = SKLabelNode()
    var coinIcon = SKLabelNode()

I think I may be creating a strong reference cycle, but I don't know where or how to identify it, I'm new to SpriteKit so sorry if my question seems dumb. Any help is very much appreciated.

A: It's hard to actually give you a solution not being able to debug with you and see how you are managing references in your Game, but I've encoutered this issue and I was able to solve it using those two things:

deinit {
    print("(Name of the SKNode) deinit")
}

Using this, I could find which objects the arc could not remove reference.

 let color4 = SKAction.run { [weak self] in
     self?.label.fontColor = .green
 }

This one helped me clean all strong references in my Game. For many of us, it's best practice to always use weak combined with self inside closures to avoid retain cycles. However, this is only needed if self also retains the closure. More Information.


text:
Q: Find all packages in the project I'm trying to know the packages I created in my project, and then goes deeply throw each package to know the classes.
Thus, is there a way to do that?

A: The Reflections library should be helpfull for that, if you want to do it during runtime without trying to read the .jar file(s). Should allow you to list all classes from your base package (for example com.ibrahim or whatever you are using).


text:
Q: How do I format webpageURL to get WatchKit to handoff user to a website in Safari? I have an app that generates a small amount of information in a WatchKit app. I then want to hand the user off to Safari on another device to pursue more information at a website, with specific information in a url query string. I've written this:
var QueryVar = SomeArray.description
var website = NSURL(string: "http://www.example.com/index.html?query="+QueryVar)

updateUserActivity("com.example.myapp.anactivity", userInfo: nil, webpageURL: website)

When I println(website) it comes up nil, and the console warns that both userInfo and webpageURL cannot be nil. I've tried a number of different ways of formatting that URL as a string, nothing seems to work.
The Swift documentation is good but lacks examples.
Most of the examples out there don't bother with the webpageURL element.
What's worse is even if I get this to not generate an error message, I won't be sure that it works because webpageURL isn't supported in the IOS simulator. Does anyone have some working code, ideally tested on an actual watch, they can share?

A: Thanks to Schemetrical who pointed out my error in thinking that
  QueryVar.description

would yield only the elements of an array stringified. As that variable contained brackets and commas it was illegal content for an NSURL type. I cleaned up the code and got to a working solution:
 var URLwithQuery = "http://www.example.com?query="+QueryVar

   var urlPath: String = URLwithQuery
   var website: NSURL = NSURL(string: urlPath)!

  updateUserActivity("com.example.myapp.anactivity", userInfo: nil, webpageURL: website)


text:
Q: Lvalue istringstream Required for istream_iterator? Given a string foo in Visual Studio I can break the words into a vector by doing:
vector fooVec{ istream_iterator<string>(istringstream(foo)), istream_iterator<string>() };

But this won't compile in gcc 5.1. I get the error:

invalid initialization of non-const reference of type std::istream_iterator<std::basic_string<char> >::istream_type& {aka std::basic_istream<char>&} from an rvalue of type std::basic_istream<char>

Now I know that gcc had a bug that was fixed by our own Jonathan Wakely. Is this an extension of that bug or should it be illegal for me to use an Rvalue istringstream here?

A: This is not a gcc bug but an evil MSVC extension.  std::istream_iterator::istream_iteraor() requires an lvalue reference.  Since istringstream(foo) is a temporary gcc correctly tells you you cannot bind the temporary to the lvalue reference.
The reason this works on MSVC is that previously mentioned extension that allows temporaries to be bound to lvalue references.  This allows the non standard compliant code to work on MSVC.
So to answer

Is this an extension of that bug or should it be illegal for me to use an Rvalue istringstream here?

No this is not a bug and you need a non-temporary stream here to construct the istream_iterator.


text:
Q: Add a month of padding from minimum date First I want to dynamically handle the range of dates for any kind of temporal data set. This I achieved using:
var earliest = d3.min(data.map(d=>d.date));
var latest = d3.max(data.map(d=>d.date));

Then I want to add a month of padding so the data don't look so precarious hanging on the edges. So I tried:
var dateMin = earliest;
var dateMax = latest;

dateMin.setDate(dateMin.getMonth()-30);
dateMax.setDate(dateMax.getMonth()+30);

It seems that the scale still remembers the initial earliest value, even though I copied it. That is to say, all this ended up doing was literally change my data point to be an earlier date, meaning that the result is unchanged; it still hangs on the edge.
Question
Is there a fool-proof way that I can use to calculate the scale such that there is an extra 30 days of padding?

A: Regarding your problem: earliest and dateMin point to the same object. Changing one will change the other:

var earliest = new Date();
var dateMin = earliest;
dateMin.setDate(dateMin.getMonth() - 30);
console.log(earliest);

This, of course, has nothing to do with D3, this is a JavaScript feature. However, D3 provides a method which is not only easier but also avoids such mistakes.
A D3 fool-proof way:
You should use interval.offset, which:

Returns a new date equal to date plus step intervals.

For instance, adding 30 days:

const date = new Date();
const datePlus30Days = d3.timeDay.offset(date, 30);
console.log(datePlus30Days)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Alternatively, removing 30 days:

const date = new Date();
const dateMinus30Days = d3.timeDay.offset(date, -30);
console.log(dateMinus30Days)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

So, in your scale, use:
var dateMin = d3.min(data, function(d){
    return d3.timeDay.offset(d.date, -30);
});

var dateMax = d3.max(data, function(d){
    return d3.timeDay.offset(d.date, 30);
});


text:
Q: How can import more files simultaneously and clean them in Mathematica? I would like to import three files in Mathematica (I am using the Import function[]) and try to clean them.
I used
Import[#,"Table"]&/@FileNames["/DirectoryPath/*.txt"]

to import the files (it is a list, where each file is a string of this list).
What I would like to know is how to clean each file; for example, if I want to use
StringReplace[StringDelete[data, "@"],"\n"..->"\n"]

to clean all of them, how could I do? At the end, I would like to train a neural network.
Many thanks for your help.

A: For illustration, here are three text files (copied from the first three paragraphs of this Wikipedia page), called "history1.txt", "history2.txt", and "history3.txt".
data = Import[#] & /@ FileNames["history*.txt"]
(*
{"Independence Day (colloquial: the Fourth of July) is a federal \
holiday in the United States commemorating the Declaration of \
Independence of the United States, on July 4, 1776. ...", \
"Independence Day is commonly associated with fireworks, parades, \
barbecues, carnivals, fairs, picnics, concerts, baseball games, \
family reunions, political speeches, and ceremonies, ...",
"During the American Revolution, the legal separation of the Thirteen \
Colonies from Great Britain in 1776 actually occurred on July 2, when \
the Second Continental Congress voted to approve a resolution of \
independence ..."}
*)

You can then do some work on all of the files. For example:
StringReplace[#, "Independence Day" -> "July 4th"] & /@ data

(*
{"July 4th (colloquial: the Fourth of July) is a federal holiday in \
the United States commemorating the Declaration of Independence of \
the United States, on July 4, 1776. ...",
"July 4th is commonly \
associated with fireworks, parades, barbecues, carnivals, fairs, \
picnics, concerts, baseball games, family reunions, political \
speeches, and ceremonies, ...",
"During the American Revolution, the \
legal separation of the Thirteen Colonies from Great Britain in 1776 \
actually occurred on July 2, when the Second Continental Congress \
voted to approve a resolution of independence ..."}
*)


text:
Q: Basic browser authentication with Safari Capybara Selenium I've got a problem with browser authentication on Safari using Capybara/Selenium.
I'm using this code to authenticate:
visit "https://#{ENV['AUTH_USERNAME']}:#{ENV['AUTH_PASSWORD']}@my-staging-app.heroku.com"

This works just fine on Chrome and FF but not on Safari.
Any ideas how to bypass this?

A: Okey, I've found the solution for this. I had to use reversed proxy using e.g. Nginx and send proper headers :)
Here is how I've done it:
In this example I'll be using creds login: admin and password: secret123.
Go to https://www.base64encode.org and encode your creds admin:secret123.
In this example it's YWRtaW46c2VjcmV0MTIz
brew install nginx
sudo vim /usr/local/etc/nginx/nginx.conf
Past there this code:
worker_processes  1;

events {
    worker_connections 1024;
}

http {
    server {
        listen 8080;
        server_name localhost;

        location / {
            proxy_pass https://your_app.herokuapp.com;
            proxy_set_header Authorization "Basic YWRtaW46c2VjcmV0MTIz";
        }
    }
}

Change proxy_pass to match your app url.
And proxy_set_header to Authorization "Basic <your_encoded_creds>"
Then: brew services start nginx
From now on, when you'll hit http://localhost:8080 you'll be redirected to your page and logged in.


text:
Q: What's the best way to get started with OSGI? What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module?
I'm interested in using OSGi in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using Spring Dynamic Modules for OSGi(tm) Service Platforms. I'm looking for a good way to incorporate a little bit of OSGi into an application as a trial. Has anyone here used this or a similar OSGi technology? Are there any pitfalls?
@Nicolas - Thanks, I've seen that one. It's a good tutorial, but I'm looking more for ideas on how to do my first "real" OSGi bundle, as opposed to a Hello World example.
@david - Thanks for the link! Ideally, with a greenfield app, I'd design the whole thing to be dynamic. What I'm looking for right now, though, is to introduce it in a small piece of an existing application. Assuming I can pick any piece of the app, what are some factors to consider that would make that piece better or worse as an OSGi guinea pig?

A: When learning a new technology rich tooling gets you into things without big headaches.
At this point the community at ops4j.org provides a rich toolset called "PAX" which includes:

*

*Pax Runner: Run and switch between Felix, Equinox, Knopflerfish and Concierge easily

*Pax Construct: Construct, Organize & Build OSGi projects with maven easily

*Pax Drone: Test your OSGi bundles with Junit while being framework independent (uses PaxRunner)

Then there are many implementations of OSGi compendium services:

*

*Pax Logging (logging),

*Pax Web (http service),

*Pax Web Extender (war support),

*Pax Coin (configuration),

*Pax Shell (shell implementation, part of the next osgi release)

*and much more.

.. and there is a helpful, framework independend community, - but thats now advertisement ;-)

A: This answer comes nearly 3 years after the question was asked, but the link I just found is really good, especially for starters using maven. A step-by-step explanation.

A: Well, since you can not have one part OSGi and one part non-OSGi you'll need to make your entire app OSGi. In its simplest form you make a single OSGi bundle out of your entire application. Clearly this is not a best practice but it can be useful to get a feel for deploying a bundle in an OSGi container (Equinox, Felix, Knoplerfish, etc).
To take it to the next level you'll want to start splitting your app into components, components should typically have a set of responsibilities that can be isolated from the rest of your application through a set of interfaces and class dependencies. Identifying these purely by hand can range from rather straightforward for a well designed highly cohesive but loosely coupled application to a nightmare for interlocked source code that you are not familiar with.
Some help can come from tools like JDepend which can show you the coupling of Java packages against other packages/classes in your system. A package with low efferent coupling should be easier to extract into an OSGi bundle than one with high efferent coupling. Even more architectural insight can be had with pro tools like Structure 101.
Purely on a technical level, working daily with an application that consists of 160 OSGi bundles and using Spring DM I can confirm that the transition from "normal" Spring to Spring DM is largely pain free. The extra namespace and the fact that you can (and should) isolate your OSGi specific Spring configuration in separate files makes it even easier to have both with and without OSGi deployment scenarios.
OSGi is a deep and wide component model, documentation I recommend:

*

*OSGi R4 Specification: Get the PDFs of the Core and Compendium specification, they are canonical, authoritative and very readable. Have a shortcut to them handy at all times, you will consult them.

*Read up on OSGi best practices, there is a large set of things you can do but a somewhat smaller set of things you should do and there are some things you should never do (DynamicImport: * for example).

Some links:

*

*OSGi best practices and using Apache Felix

*Peter Kriens and BJ Hargrave in a Sun presentation on OSGi best practices

*one key OSGi concept are Services, learn why and how they supplant the Listener pattern with the Whiteboard pattern

*The Spring DM Google Group is very responsive and friendly in my experience
The Spring DM Google Group is no longer active and has moved to Eclipse.org as the Gemini Blueprint project which has a forum here.

A: Is your existing application monolithic or tiered in seperate processes/layers?
If tiered, you can convert the middle/app-tier to run in an OSGi container.
In my team's experience, we've found trying to do web-stuff in OSGi painful.  Other pain points are Hibernate and Jakarta Commons Logging.
I find the OSGi specs pretty readable and I recommend you print out the flowchart that shows the algorithm for class loading.  I'll guarantee you'll have moments of, "why am I getting a NoClassDefFoundError?": the flowchart will tell you why.

A: Try http://neilbartlett.name/blog/osgibook/. The book has hands on examples with OSGi best practices.

A: Try http://njbartlett.name/files/osgibook_preview_20091217.pdf
OR
http://www.manning.com/hall/
The second is not a book i have read myself but I have heard good things about it.
The first was very useful for me. He takes you through the architecture initially and then it's hands on OSGi.

A: There are a couple of thinks to keep in mind if you are starting with OSGi.
As mentioned elsewhere in this thread, knowing about classloading is really important. In my experience everybody sooner or later runs into problems with it.
Another important thing to remember is: never hold references! Have a look at the whiteboard pattern on which the services concept of OSGi is build (see the link in one of the other answers).
In my experience you should not try to convert a monolitic application into an OSGi-based one. This usually leads to a badly and unmanageable mess. Start anew.
Download one of the freely available stand-alone OSGi implementations. I found Knopflerfish rather good and stable (I use it in many projects). It also comes with lots of source code. You can find it here: http://www.knopflerfish.org
Another good tutorial can be found here. https://pro40.abac.com/deanhiller/cgi-bin/moin.cgi/OsgiTutorial
Peter Kriens of the OSGi Alliance gave a nice interview: http://www.infoq.com/interviews/osgi-peter-kriens. His homepage and blog (which is always a good read can be found here: http://www.aqute.biz

A: I really like the Apache Felix tutorials. However, I think in general leveraging OSGi in your application isn't one of those "let's use this framework, because it's hype" decision. It's more of a design question, but then everything that OSGi gives you in terms of design, you can have with vanilla Java as well.
As for the runtime, you cannot just add an existing application and make it OSGi enabled. It needs to be design to be dynamic. Spring DM makes it easy to hide that from you, but it's still there and you need to be aware of it.


text:
Q: Centering sections without centering subsections This question is about how to center all the sections (including chapters) without centering subsections.
I have browsed all the related questions asked here but I found no one to which my question is duplicate. I have tried a proposed solution that centers all the headlines. But I do not know how to partially center the headlines.
Need your help, thanks so much, with my codes:
\documentclass[a4paper]{article}
\usepackage{mathtools}
\usepackage{colonequals}
\usepackage{mathrsfs}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{amsmath}`enter code here`
\usepackage{natbib}
\usepackage{bm}
\usepackage{mathdots}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{rotating, threeparttable, booktabs}
\usepackage{color}
\usepackage{dcolumn}
\usepackage{type1cm}
%\usepackage[margin=1.2in]{geometry}
%\usepackage{times}
\captionsetup{font=sf,font=small}
\setlength{\bibsep}{2pt}
\captionsetup{font=sf,font=small,labelfont=bf,textfont=bf}
\theoremstyle{plain}
\newtheorem{thm}{Theorem}[section]
\newtheorem{lem}[thm]{Lemma}
\newtheorem{cor}[thm]{Corollary}
\newtheorem{pro}[thm]{Proposition}
\newtheorem{assump}{Assumption}
\newtheorem{axiom}{Axiom}
\newtheorem{conj}{Conjecture}
\theoremstyle{definition}
\newtheorem{defi}[thm]{Definition}
\newtheorem{exam}[thm]{Example}
\newtheorem{exer}{Exercise}
\newtheorem*{rem}{Remark}
\newtheorem*{notation}{Notation}
%\renewcommand{\proofname}{\textbf{\textup{Proof}}}
\renewcommand*{\qedsymbol}{$\blacksquare$}
%\renewcommand{\baselinestretch}{2}
\renewcommand{\textfraction}{0.15}
\renewcommand{\topfraction}{0.85}
\renewcommand{\bottomfraction}{0.65}
\renewcommand{\floatpagefraction}{0.60}
%\renewcommand\familydefault{\sfdefault}

\newcommand\laref{\fontsize{12}{20pt}\selectfont \smallskip\noindent%
\hangindent=19pt}
\newcommand\xitem{\par\noindent\hangindent=8mm}

% To increase line space in footnote.
%
\let\oldfootnote\footnote
\renewcommand\footnote[1]{\oldfootnote{%
  \renewcommand\baselinestretch{1.5}%
  \large\scriptsize\ignorespaces#1}}
\addtolength{\footnotesep}{1pt}

%centering all titles
\usepackage{sectsty}
\sectionfont{\centering}

A: One way with sectsty:
\documentclass{article}
\usepackage{sectsty}
\sectionfont{\centering}
\begin{document}
  \section{Some section}
  \subsection{A subsection}
\end{document}

sectsty also offers \chapterfont (but in article class, there ain't no chapter), \subsectionfont etc along with \allsectionsfont which will apply to all sections.
With titlesec:
\documentclass{article}
\usepackage{titlesec}
\titleformat*{\section}{\Large\bfseries\centering}
\begin{document}
  \section{Some section}
  \subsection{A subsection}
\end{document}


text:
Q: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: user.first_name I have received the error message when I try to sign up a new user to my website. Any suggestions as to how I can fix it?: Below is the error message and also the code I have wrote

'sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: user.first_name
[SQL: SELECT user.id AS user_id, user.email AS user_email, user.password AS user_password, user.first_name AS user_first_name
FROM user
WHERE user.email = ?
 LIMIT ? OFFSET ?]
[parameters: ('jackt@learningpython.com', 1, 0)]
(Background on this error at: http://sqlalche.me/e/14/e3q8)'

@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    if request.method =='POST':
        first_name = request.form.get('firstName')
        email = request.form.get('email')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        user = User.query.filter_by(email=email).first()
        if user:
            flash('Email already exists.', category='error')
        elif len(first_name) < 2:
            flash('First Name must be greater than 1 character.', category='error')
        elif len(email) < 4:
            flash('Email must be greater than 3 characters.', category='error')
        elif password1 != password2:
            flash('Passwords don\'t match.', category='error')
        elif len(password1) < 7:
            flash('Password must be atleast 7 characters.', category='error')
        else:
            new_user = User(email=email, first_name=first_name, password=generate_password_hash(password1, method='sha256'))
            db.session.add(new_user)
            db.session.commit()
            flash('Account created!', category='success')
            return redirect(url_for('views.home'))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))
    notes = db.relationship('Note')


text:
Q: FactoryGirl: How To Set Trait to True I have created a factory for my Request model. This model has a Boolean value that defaults to "false" at the database level. I have created a factory called :fulfilled_request that uses the trait feature in FactoryGirl, but, even though it is being called, the Request instance created has a is_fulfilled attribute of false. Any ideas? Below is my factory:
  factory :request do
    content { Faker::Lorem.paragraph }
    association :requester
    association :group

    trait :has_neighbor do
      association :responder
    end

    trait :is_fulfilled do
      is_fulfilled true
    end

    trait :created_one_day_ago do
      created_at { 1.day.ago }
    end

    factory :request_with_neighbor, traits: [:has_neighbor]
    factory :fulfilled_request , traits: [:has_neighbor, :is_fulfilled]
    factory :day_old_request, traits: [:created_one_day_ago]
  end

A: Call your factory like this.
FactoryGirl.create(:request, :is_fulfilled)

This will use the trait as you need it.

A: Unfortunately, the reason that this was not working was that there was a after_create callback in the model that set is_fulfilled attribute to false.
This was done to mirror the database constraints in the model. I think this is one of those rare times when it doesn't make sense to mirror the database constraints in the model. The database is set to default this attribute to false. (The database therefore should not have a NOT NULL constraint either).
I'm just posting this for full documentation and to help others who might have this problem. Check your callbacks!
P.S. Thanks to sikachu on #thoughtbot (irc) for helping me spot that.


text:
Q: Pipeline keeps failing in Azure Synapse (running a simple query) I am learning how to create pipelines with the help of a Udemy course in Azure Synapse. I created a link service that connects to my 'master' database of my serverless SQL pool. The connection itself was successful:

I then created a simple 'script activity' in the Pipeline which connects to this linked service and then returns a query.

Here is the full query I used (I masked some of the data):

SELECT
    TOP 100 *, result.filename()
FROM
    OPENROWSET(
        BULK 'https://xxxx.dfs.core.windows.net/taxi/raw/trip_data_green_parquet/year=*/month=*/*.parquet',
        FORMAT = 'PARQUET'
    )
    WITH (
        VendorID INT,
        lpep_pickup_datetime datetime2(7)
        )   AS [result]

It should be noted that the above query works fine when I run  it outside of the pipeline. I then clicked 'validate' to check for errors and no errors were found:

But when I clicked 'Debug' it failed:

Here is the full error code:
{
    "errorCode": "2011",
    "message": "Argument {0} is null or empty.\r\nParameter name: paraKey",
    "failureType": "UserError",
    "target": "Script1",
    "details": []
}

Any help would be greatly appreciated.
I tried running the following SQL query and it worked:
SELECT
    TOP 10 *
FROM
    OPENROWSET(
        BULK 'https://xxxx.dfs.core.windows.net/taxi/raw/taxi_zone_without_header.csv',
        FORMAT = 'CSV',
        PARSER_VERSION = '2.0'
    )
   WITH(
        LocationID SMALLINT 1,
        Borough VARCHAR(15) COLLATE Latin1_General_100_CI_AI_SC_UTF8 2,
        service_zone VARCHAR(15) COLLATE Latin1_General_100_CI_AI_SC_UTF8 4,
        Zone VARCHAR(50) COLLATE Latin1_General_100_CI_AI_SC_UTF8 3
    ) AS [result]

I'm not too sure why the other one did not work.

A:
"Argument {0} is null or empty.\r\nParameter name: paraKey"

This error is because there is no column name for results.filename() in the SQL script. Try giving result.filename() as file_name in the script.
I repro'd this without alias name for filename() function and got the same error.

*

*Then column name is added in script and synapse pipeline is run successfully.

SQL script:
SELECT
    TOP 100 *, result.filename() as file_name
FROM
    OPENROWSET(
        BULK 'https://xxxx.dfs.core.windows.net/taxi/raw/trip_data_green_parquet/year=*/month=*/*.parquet',
        FORMAT = 'PARQUET'
    )
    WITH (
        VendorID INT,
        lpep_pickup_datetime datetime2(7)
        )   AS [result]


text:
Q: React Native: when should you call function in constructor vs componentDidMount I know from reading this article that the contructor is called pre-render, and componentDidMount is called post-render, but I don't understand how this influences how we decide which one to use. What happens during render that would make me want to call an initialization function before or after that render?

A: Constructor is solid to initialize state variables, bind event handlers, and call super(props).
ComponentDidMount is when a component is mounted. It is where you want to set up DOM nodes, interact with browsers/API (ex: pulling data from MongoDB), and loading data elsewhere.


text:
Q: Unable to create a blob in a container Scenario: unable to deploy a blob within a container tha is created in a storage account, read in as a data source. Obscure error is produced in GitHub actions workflow.
Error:
Error: creating Blob "xrdpdeploy.sh" (Container "morpheus-tinkering-csecontainer" / Account "***"): opening: open # update available packages

[ERROR] provider.terraform-provider-azurerm_v3.35.0_x5: Response contains error diagnostic: @caller=github.com/hashicorp/terraform-plugin-go@v0.14.1/tfprotov5/internal/diag/diagnostics.go:55 @module=sdk.proto diagnostic_detail= diagnostic_severity=ERROR tf_proto_version=5.3 diagnostic_summary="creating Blob "xrdpdeploy.sh" (Container "morpheus-tinkering-csecontainer" / Account "***"): opening: open # update available packages

Hi folks, given the above scenario I am stuck with; do you have any suggestions to help me upload the blob object correct. The terraform config is shown below:
resource "azurerm_storage_container" "cse_container" {
    name = "${local.naming_prefix}csecontainer"
    storage_account_name = data.azurerm_storage_account.storage_account.name
    container_access_type = "blob"
}

#-------------------------------------------------------------

# storage container blob script used to run as a custom script extension
resource "azurerm_storage_blob" "cse_blob" {
    name = "xrdpdeploy.sh"
    storage_account_name = data.azurerm_storage_account.storage_account.name
    storage_container_name = azurerm_storage_container.cse_container.name
    type = "Block"
    access_tier = "Hot"
    # absolute path to file on local system
    source = file("${path.module}/cse-script/xrdpdeploy.sh")
    #explicit dependency on storage container to be deployed first prior to uploading blobk blob
    depends_on = [
      azurerm_storage_container.cse_container
    ]
}

#-------------------------------------------------------------

data "azurerm_storage_account" "storage_account" {
  name = "morpheuszcit10394"
  resource_group_name = "zimcanit-morpheus-tinkering-rg"
}

#-------------------------------------------------------------

I'm using Azure Terraform provider version 3.35.0.
What I've done; ensured the container is being created correctly; explicitly set access tier and  even tried dropping Azure provider version to 3.30.0.
Thanks in advance!


text:
Q: Ошибка AttributeError: 'Text' object has no attribute 'die' Изучаю книгу Майлка Доусона по Python, написал игру "Прерванный Полет".
При уничтожении астероида вылезает следующая ошибка.
Traceback (most recent call last):
  File "C:/Users/Чебупелька/Desktop/Python/!Читаю с клавиатуры.py", line 249, in <module>
main()
  File "C:/Users/Чебупелька/Desktop/Python/!Читаю с клавиатуры.py", line 246, in main
game.play()
  File "C:/Users/Чебупелька/Desktop/Python/!Читаю с клавиатуры.py", line 27, in play
games.screen.mainloop()
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\livewires\games.py", line 308, in mainloop
object._tick()
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\livewires\games.py", line 506, in _tick
self.update()
  File "C:/Users/Чебупелька/Desktop/Python/!Читаю с клавиатуры.py", line 126, in update
super(Missile, self).update()
  File "C:/Users/Чебупелька/Desktop/Python/!Читаю с клавиатуры.py", line 90, in update
sprite.die()
AttributeError: 'Text' object has no attribute 'die'
Exception ignored in: <bound method Sprite.__del__ of <__main__.Missile object at 0x06283610>>

Код ниже.
import random
import math

from livewires import games, color

games.init(screen_width=800, screen_height=600, fps=60)

class Game(object):
    def __init__(self):
        self.level = 0
        self.score = games.Text(value='0',
                                size=30,
                                color=color.black,
                                top=0,
                                left=games.screen.width)
        games.screen.add(self.score)
        self.ship = Ship(game=self,
                         x=games.screen.width / 2,
                         y=games.screen.height / 2)
        games.screen.add(self.ship)

    def play(self):
        nebula_image = games.load_image('nebula228.jpg', transparent=False)
        games.screen.background = nebula_image
        self.lvlup()
        games.screen.mainloop()

    def lvlup(self):
        self.level += 1
        BUFFER = 150
        for i in range(self.level):
            x_min = random.randrange(BUFFER)
            y_min = BUFFER - x_min
            x_distance = random.randrange(y_min, games.screen.width - x_min)
            y_distance = random.randrange(x_min, games.screen.height - y_min)
            x = self.ship.x + x_distance
            y = self.ship.y + y_distance
            y %= games.screen.height
            x %= games.screen.width
            new_asteroid = Asteroid(game=self,
                                    x=x, y=y,
                                    size=Asteroid.LARGE)
            games.screen.add(new_asteroid)
            level_message = games.Message(value='Level ' + str(self.level),
                                          size=40,
                                          color=color.yellow,
                                          x=games.screen.width / 2,
                                          y=games.screen.height / 10,
                                          lifetime=3 * games.screen.fps,
                                          is_collideable=False)
            games.screen.add(level_message)

    def end(self):
        end_message = games.Message(value='Game Over!', lifetime=5 * games.screen.fps,
                                    x=games.screen.width / 2,
                                    y=games.screen.height / 2,
                                    is_collideable=False,
                                    after_death=games.screen.quit)
        games.screen.add(end_message)

class Wrapper(games.Sprite):
    def upadte(self):
        if self.top > games.screen.height:
            self.bottom = 0
        if self.bottom < 0:
            self.top = games.screen.height
        if self.left > games.screen.width:
            self.right = 0
        if self.right < 0:
            self.left = games.screen.width

    def die(self):
        self.destroy()

class Collider(Wrapper):
    def update(self):
        if self.top > games.screen.height:
            self.bottom = 0
        if self.bottom < 0:
            self.top = games.screen.height
        if self.left > games.screen.width:
            self.right = 0
        if self.right < 0:
            self.left = games.screen.width
        if self.overlapping_sprites:
            for sprite in self.overlapping_sprites:
                sprite.die()
            self.die()

    def die(self):
        new_expl = Explosion(x=self.x, y=self.y)
        games.screen.add(new_expl)
        self.destroy()

class Missile(Collider):
    image = games.load_image('missile.bmp', transparent=True)
    BUFFER = 40
    VELOCITY_FACTOR = 7
    LIFETIME = 100

    def __init__(self, sx, sy, sangle):
        angle = sangle * math.pi / 180
        bx = Missile.BUFFER * math.sin(angle)
        by = Missile.BUFFER * -math.cos(angle)
        x = sx + bx
        y = sy + by
        dy = Missile.VELOCITY_FACTOR * -math.cos(angle)
        dx = Missile.VELOCITY_FACTOR * math.sin(angle)
        super(Missile, self).__init__(image=Missile.image,
                                      x=x, y=y,
                                      dx=dx, dy=dy)
        self.lifetime = Missile.LIFETIME

    def update(self):
        if self.overlapping_sprites:
            for sprite in self.overlapping_sprites:
                sprite.die()
            self.die()
        self.lifetime -= 1
        if self.lifetime == 0:
            self.destroy()
        super(Missile, self).update()

    def die(self):
        self.destroy()

class Ship(Collider):
    image = games.load_image('ship.bmp', transparent=True)
    ROTATION_STEP = 3
    VELOCITY_STEP = .03
    VELOCITY_MAX = 3
    MISSILE_DELAY = 25

    def __init__(self, game, x, y):
        self.game = game
        super(Ship, self).__init__(image=Ship.image, x=x, y=y)
        self.missile_wait = 0

    def update(self):
        if self.missile_wait > 0:
            self.missile_wait -= 1
        if games.keyboard.is_pressed(games.K_w):
            angle = self.angle * math.pi / 180
            self.dy += Ship.VELOCITY_STEP * -math.cos(angle)
            self.dx += Ship.VELOCITY_STEP * math.sin(angle)
            self.dx = min(max(self.dx, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX)
            self.dy = min(max(self.dy, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX)
        if games.keyboard.is_pressed(games.K_LEFT):
            self.angle -= Ship.ROTATION_STEP
        if games.keyboard.is_pressed(games.K_RIGHT):
            self.angle += Ship.ROTATION_STEP
        if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0:
            new_missile = Missile(self.x, self.y, self.angle)
            games.screen.add(new_missile)
            self.missile_wait = Ship.MISSILE_DELAY
        if self.top > games.screen.height:
            self.bottom = 0
        if self.bottom < 0:
            self.top = games.screen.height
        if self.left > games.screen.width:
            self.right = 0
        if self.right < 0:
            self.left = games.screen.width
        super(Ship, self).update()

    def die(self):
        self.game.end()
        super(Ship, self).die()

class Asteroid(Wrapper):
    POINTS = 30
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
    SPAWN = 2
    images = {SMALL: games.load_image('asteroid_small.bmp'),
              MEDIUM: games.load_image('asteroid_med.bmp'),
              LARGE: games.load_image('asteroid_big.bmp')}
    SPEED = 2
    total = 1

    def __init__(self, game, x, y, size):
        self.game = game
        Asteroid.total += 1
        super(Asteroid, self).__init__(
            image=Asteroid.images[size],
            x=x, y=y,
            dx=random.choice([1, -1]) * Asteroid.SPEED * random.random() / size,
            dy=random.choice([1, -1]) * Asteroid.SPEED * random.random() / size)
        self.size = size

    def update(self):
        if self.top > games.screen.height:
            self.bottom = 0
        if self.bottom < 0:
            self.top = games.screen.height
        if self.left > games.screen.width:
            self.right = 0
        if self.right < 0:
            self.left = games.screen.width
        super(Asteroid, self).update()

    def die(self):
        Asteroid.total -= 1
        self.game.score.value += str(30)
        self.game.score.right = games.screen.width - 10
        new_expl = Explosion(x=self.x, y=self.y)
        games.screen.add(new_expl)
        self.destroy()
        if self.size != 1:
            for i in range(Asteroid.SPAWN):
                new_aster = Asteroid(x=self.x, y=self.y,
                                     size=self.size - 1)
                games.screen.add(new_aster)
        if Asteroid.total == 0:
            self.game.lvlup()
        super(Asteroid, self).die()

class Explosion(games.Animation):
    ALLAHU_AKBAR = ('1.bmp',
                    '2.bmp',
                    '3.bmp',
                    '4.bmp',
                    '5.bmp',
                    '6.bmp',
                    '7.bmp',
                    '8.bmp',
                    '9.bmp')

    def __init__(self, x, y):
        super(Explosion, self).__init__(images=Explosion.ALLAHU_AKBAR,
                                        x=x, y=y,
                                        repeat_interval=4, n_repeats=1,
                                        is_collideable=False)

def main():
    game = Game()
    game.play()

main()

A: Сначала определите функцию die() и только потом функцию где она вызывается.
class Collider(Wrapper):
    def die(self):
        new_expl = Explosion(x=self.x, y=self.y)
        games.screen.add(new_expl)
        self.destroy()

    def update(self):
        if self.top > games.screen.height:
            self.bottom = 0
        if self.bottom < 0:
            self.top = games.screen.height
        if self.left > games.screen.width:
            self.right = 0
        if self.right < 0:
            self.left = games.screen.width
        if self.overlapping_sprites:
            for sprite in self.overlapping_sprites:
                sprite.die()
            self.die()